blob: 8783bc072b17b96e3775463404f27dc447538225 [file] [log] [blame]
Chris Lattner27aa7d22009-06-21 20:16:42 +00001//===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This class implements the parser for assembly files.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbarb95a0792010-09-24 01:59:56 +000014#include "llvm/ADT/APFloat.h"
Daniel Dunbar7c0a3342009-08-26 22:49:51 +000015#include "llvm/ADT/SmallString.h"
Chad Rosierabde6752013-02-13 18:38:58 +000016#include "llvm/ADT/STLExtras.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000017#include "llvm/ADT/StringMap.h"
Daniel Dunbarf9507ff2009-07-27 23:20:52 +000018#include "llvm/ADT/Twine.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000019#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000020#include "llvm/MC/MCContext.h"
Evan Cheng94b95502011-07-26 00:24:13 +000021#include "llvm/MC/MCDwarf.h"
Daniel Dunbar28c251b2009-08-31 08:06:59 +000022#include "llvm/MC/MCExpr.h"
Chad Rosierb1f8c132012-10-18 15:49:34 +000023#include "llvm/MC/MCInstPrinter.h"
24#include "llvm/MC/MCInstrInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000025#include "llvm/MC/MCParser/AsmCond.h"
26#include "llvm/MC/MCParser/AsmLexer.h"
27#include "llvm/MC/MCParser/MCAsmParser.h"
28#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Evan Chenge76a33b2011-07-20 05:58:47 +000029#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000030#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000031#include "llvm/MC/MCStreamer.h"
Daniel Dunbardce0f3c2009-06-29 23:43:14 +000032#include "llvm/MC/MCSymbol.h"
Evan Cheng94b95502011-07-26 00:24:13 +000033#include "llvm/MC/MCTargetAsmParser.h"
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000034#include "llvm/Support/CommandLine.h"
Benjamin Kramer518ff562012-01-28 15:28:41 +000035#include "llvm/Support/ErrorHandling.h"
Jim Grosbach254cf032011-06-29 16:05:14 +000036#include "llvm/Support/MathExtras.h"
Kevin Enderbyf187ac52010-06-28 21:45:58 +000037#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000038#include "llvm/Support/SourceMgr.h"
Chris Lattnerb0789ed2009-06-21 20:54:55 +000039#include "llvm/Support/raw_ostream.h"
Nick Lewycky476b2422010-12-19 20:43:38 +000040#include <cctype>
Chad Rosierb1f8c132012-10-18 15:49:34 +000041#include <set>
42#include <string>
Daniel Dunbaraef87e32010-07-18 18:31:38 +000043#include <vector>
Chris Lattner27aa7d22009-06-21 20:16:42 +000044using namespace llvm;
45
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000046static cl::opt<bool>
47FatalAssemblerWarnings("fatal-assembler-warnings",
48 cl::desc("Consider warnings as error"));
49
Eric Christopher2318ba12012-12-18 00:30:54 +000050MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
Nick Lewycky0d7d11d2012-10-19 07:00:09 +000051
Daniel Dunbar81ea00f2010-07-12 17:54:38 +000052namespace {
53
Eli Benderskyf9f40bd2013-01-16 18:56:50 +000054/// \brief Helper types for tracking macro definitions.
55typedef std::vector<AsmToken> MCAsmMacroArgument;
56typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
57typedef std::pair<StringRef, MCAsmMacroArgument> MCAsmMacroParameter;
58typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
59
60struct MCAsmMacro {
61 StringRef Name;
62 StringRef Body;
63 MCAsmMacroParameters Parameters;
64
65public:
66 MCAsmMacro(StringRef N, StringRef B, const MCAsmMacroParameters &P) :
67 Name(N), Body(B), Parameters(P) {}
68
69 MCAsmMacro(const MCAsmMacro& Other)
70 : Name(Other.Name), Body(Other.Body), Parameters(Other.Parameters) {}
71};
72
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000073/// \brief Helper class for storing information about an active macro
74/// instantiation.
75struct MacroInstantiation {
76 /// The macro being instantiated.
Eli Benderskyc0c67b02013-01-14 23:22:36 +000077 const MCAsmMacro *TheMacro;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000078
79 /// The macro instantiation with substitutions.
80 MemoryBuffer *Instantiation;
81
82 /// The location of the instantiation.
83 SMLoc InstantiationLoc;
84
Daniel Dunbar4259a1a2012-12-01 01:38:48 +000085 /// The buffer where parsing should resume upon instantiation completion.
86 int ExitBuffer;
87
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000088 /// The location where parsing should resume upon instantiation completion.
89 SMLoc ExitLoc;
90
91public:
Eli Benderskyc0c67b02013-01-14 23:22:36 +000092 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000093 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000094};
95
Eli Friedman2128aae2012-10-22 23:58:19 +000096struct ParseStatementInfo {
97 /// ParsedOperands - The parsed operands from the last parsed statement.
98 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
99
100 /// Opcode - The opcode from the last parsed instruction.
101 unsigned Opcode;
102
Chad Rosier57498012012-12-12 22:45:52 +0000103 /// Error - Was there an error parsing the inline assembly?
104 bool ParseError;
105
Eli Friedman2128aae2012-10-22 23:58:19 +0000106 SmallVectorImpl<AsmRewrite> *AsmRewrites;
107
Chad Rosier57498012012-12-12 22:45:52 +0000108 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
Eli Friedman2128aae2012-10-22 23:58:19 +0000109 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier57498012012-12-12 22:45:52 +0000110 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman2128aae2012-10-22 23:58:19 +0000111
112 ~ParseStatementInfo() {
113 // Free any parsed operands.
114 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
115 delete ParsedOperands[i];
116 ParsedOperands.clear();
117 }
118};
119
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000120/// \brief The concrete assembly parser instance.
121class AsmParser : public MCAsmParser {
Craig Topper85aadc02012-09-15 16:23:52 +0000122 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
123 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000124private:
125 AsmLexer Lexer;
126 MCContext &Ctx;
127 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000128 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000129 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +0000130 SourceMgr::DiagHandlerTy SavedDiagHandler;
131 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000132 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000133
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000134 /// This is the current buffer index we're lexing from as managed by the
135 /// SourceMgr object.
136 int CurBuffer;
137
138 AsmCond TheCondState;
139 std::vector<AsmCond> TheCondStack;
140
Eli Bendersky6ee13082013-01-15 22:59:42 +0000141 /// ExtensionDirectiveMap - maps directive names to handler methods in parser
142 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000143 /// addDirectiveHandler.
Eli Bendersky6ee13082013-01-15 22:59:42 +0000144 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000145
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000146 /// MacroMap - Map of currently defined macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000147 StringMap<MCAsmMacro*> MacroMap;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000148
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000149 /// ActiveMacros - Stack of active macro instantiations.
150 std::vector<MacroInstantiation*> ActiveMacros;
151
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000152 /// Boolean tracking whether macro substitution is enabled.
Eli Bendersky733c3362013-01-14 18:08:41 +0000153 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000154
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000155 /// Flag tracking whether any errors have been encountered.
156 unsigned HadError : 1;
157
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000158 /// The values from the last parsed cpp hash file line comment if any.
159 StringRef CppHashFilename;
160 int64_t CppHashLineNumber;
161 SMLoc CppHashLoc;
Kevin Enderby32c1a822012-11-05 21:55:41 +0000162 int CppHashBuf;
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000163
Devang Patel0db58bf2012-01-31 18:14:05 +0000164 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
165 unsigned AssemblerDialect;
166
Preston Gurd7b6f2032012-09-19 20:36:12 +0000167 /// IsDarwin - is Darwin compatibility enabled?
168 bool IsDarwin;
169
Chad Rosier8f138d12012-10-15 17:19:13 +0000170 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000171 bool ParsingInlineAsm;
172
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000173public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000174 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000175 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000176 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000177
178 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
179
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000180 virtual void addDirectiveHandler(StringRef Directive,
Eli Bendersky171192f2013-01-16 00:50:52 +0000181 ExtensionDirectiveHandler Handler) {
182 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000183 }
184
185public:
186 /// @name MCAsmParser Interface
187 /// {
188
189 virtual SourceMgr &getSourceManager() { return SrcMgr; }
190 virtual MCAsmLexer &getLexer() { return Lexer; }
191 virtual MCContext &getContext() { return Ctx; }
192 virtual MCStreamer &getStreamer() { return Out; }
Eric Christopher2318ba12012-12-18 00:30:54 +0000193 virtual unsigned getAssemblerDialect() {
Devang Patel0db58bf2012-01-31 18:14:05 +0000194 if (AssemblerDialect == ~0U)
Eric Christopher2318ba12012-12-18 00:30:54 +0000195 return MAI.getAssemblerDialect();
Devang Patel0db58bf2012-01-31 18:14:05 +0000196 else
197 return AssemblerDialect;
198 }
199 virtual void setAssemblerDialect(unsigned i) {
200 AssemblerDialect = i;
201 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000202
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000203 virtual bool Warning(SMLoc L, const Twine &Msg,
204 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
205 virtual bool Error(SMLoc L, const Twine &Msg,
206 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000207
Craig Topper345d16d2012-08-29 05:48:09 +0000208 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000209
Chad Rosier84125ca2012-10-13 00:26:04 +0000210 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosierc5ac87d2012-10-16 20:16:20 +0000211 bool isParsingInlineAsm() { return ParsingInlineAsm; }
Chad Rosierb1f8c132012-10-18 15:49:34 +0000212
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000213 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000214 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +0000215 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000216 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000217 SmallVectorImpl<std::string> &Clobbers,
218 const MCInstrInfo *MII,
219 const MCInstPrinter *IP,
220 MCAsmParserSemaCallback &SI);
Chad Rosier84125ca2012-10-13 00:26:04 +0000221
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000222 bool parseExpression(const MCExpr *&Res);
223 virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc);
Chad Rosierba69b362013-04-10 17:35:30 +0000224 virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000225 virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
226 virtual bool parseAbsoluteExpression(int64_t &Res);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000227
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000228 /// parseIdentifier - Parse an identifier or string (as a quoted identifier)
Eli Benderskybf706b32013-01-12 00:05:00 +0000229 /// and set \p Res to the identifier contents.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000230 virtual bool parseIdentifier(StringRef &Res);
231 virtual void eatToEndOfStatement();
Eli Benderskybf706b32013-01-12 00:05:00 +0000232
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000233 virtual void checkForValidSection();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000234 /// }
235
236private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000237
Eli Friedman2128aae2012-10-22 23:58:19 +0000238 bool ParseStatement(ParseStatementInfo &Info);
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000239 void EatToEndOfLine();
240 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000241
Kevin Enderby221514e2013-01-22 21:44:53 +0000242 void CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
243 MCAsmMacroParameters Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +0000244 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000245 const MCAsmMacroParameters &Parameters,
246 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000247 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000248
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000249 /// \brief Are macros enabled in the parser?
250 bool MacrosEnabled() {return MacrosEnabledFlag;}
251
252 /// \brief Control a flag in the parser that enables or disables macros.
253 void SetMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
254
255 /// \brief Lookup a previously defined macro.
256 /// \param Name Macro name.
257 /// \returns Pointer to macro. NULL if no such macro was defined.
258 const MCAsmMacro* LookupMacro(StringRef Name);
259
260 /// \brief Define a new macro with the given name and information.
261 void DefineMacro(StringRef Name, const MCAsmMacro& Macro);
262
263 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
264 void UndefineMacro(StringRef Name);
265
266 /// \brief Are we inside a macro instantiation?
267 bool InsideMacroInstantiation() {return !ActiveMacros.empty();}
268
269 /// \brief Handle entry to macro instantiation.
270 ///
271 /// \param M The macro.
272 /// \param NameLoc Instantiation location.
273 bool HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
274
275 /// \brief Handle exit from macro instantiation.
276 void HandleMacroExit();
277
278 /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
279 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
280 /// correct delimiter by the method.
281 bool ParseMacroArgument(MCAsmMacroArgument &MA,
282 AsmToken::TokenKind &ArgumentDelimiter);
283
284 /// \brief Parse all macro arguments for a given macro.
285 bool ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
286
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000287 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000288 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000289 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
290 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000291 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000292 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000293
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000294 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
295 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000296 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
297 /// This returns true on failure.
298 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000299
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000300 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000301 /// current token is not set; clients should ensure Lex() is called
302 /// subsequently.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000303 ///
304 /// \param InBuffer If not -1, should be the known buffer id that contains the
305 /// location.
306 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000307
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000308 /// \brief Parse up to the end of statement and a return the contents from the
309 /// current token until the end of the statement; the current token on exit
310 /// will be either the EndOfStatement or EOF.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000311 virtual StringRef parseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000312
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000313 /// \brief Parse until the end of a statement or a comma is encountered,
314 /// return the contents from the current token up to the end or comma.
315 StringRef ParseStringToComma();
316
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000317 bool ParseAssignment(StringRef Name, bool allow_redef,
318 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000319
320 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
321 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
322 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000323 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000324
Eli Bendersky6ee13082013-01-15 22:59:42 +0000325 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola787c3372010-10-28 20:02:27 +0000326
Eli Bendersky6ee13082013-01-15 22:59:42 +0000327 // Generic (target and platform independent) directive parsing.
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000328 enum DirectiveKind {
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000329 DK_NO_DIRECTIVE, // Placeholder
330 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
331 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
332 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky9b1bb052013-01-11 22:55:28 +0000333 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000334 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
335 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
336 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
337 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
338 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
339 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
340 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
Eli Bendersky6ee13082013-01-15 22:59:42 +0000341 DK_ELSEIF, DK_ELSE, DK_ENDIF,
342 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
343 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
344 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
345 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
346 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
347 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
348 DK_CFI_REGISTER,
349 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
350 DK_SLEB128, DK_ULEB128
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000351 };
352
Eli Bendersky6ee13082013-01-15 22:59:42 +0000353 /// DirectiveKindMap - Maps directive name --> DirectiveKind enum, for
354 /// directives parsed by this class.
355 StringMap<DirectiveKind> DirectiveKindMap;
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000356
357 // ".ascii", ".asciz", ".string"
Rafael Espindola787c3372010-10-28 20:02:27 +0000358 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000359 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000360 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000361 bool ParseDirectiveFill(); // ".fill"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000362 bool ParseDirectiveZero(); // ".zero"
Eric Christopher2318ba12012-12-18 00:30:54 +0000363 // ".set", ".equ", ".equiv"
364 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000365 bool ParseDirectiveOrg(); // ".org"
366 // ".align{,32}", ".p2align{,w,l}"
367 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
368
Eli Bendersky6ee13082013-01-15 22:59:42 +0000369 // ".file", ".line", ".loc", ".stabs"
370 bool ParseDirectiveFile(SMLoc DirectiveLoc);
371 bool ParseDirectiveLine();
372 bool ParseDirectiveLoc();
373 bool ParseDirectiveStabs();
374
375 // .cfi directives
376 bool ParseDirectiveCFIRegister(SMLoc DirectiveLoc);
377 bool ParseDirectiveCFISections();
378 bool ParseDirectiveCFIStartProc();
379 bool ParseDirectiveCFIEndProc();
380 bool ParseDirectiveCFIDefCfaOffset();
381 bool ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
382 bool ParseDirectiveCFIAdjustCfaOffset();
383 bool ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
384 bool ParseDirectiveCFIOffset(SMLoc DirectiveLoc);
385 bool ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
386 bool ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
387 bool ParseDirectiveCFIRememberState();
388 bool ParseDirectiveCFIRestoreState();
389 bool ParseDirectiveCFISameValue(SMLoc DirectiveLoc);
390 bool ParseDirectiveCFIRestore(SMLoc DirectiveLoc);
391 bool ParseDirectiveCFIEscape();
392 bool ParseDirectiveCFISignalFrame();
393 bool ParseDirectiveCFIUndefined(SMLoc DirectiveLoc);
394
395 // macro directives
396 bool ParseDirectivePurgeMacro(SMLoc DirectiveLoc);
397 bool ParseDirectiveEndMacro(StringRef Directive);
398 bool ParseDirectiveMacro(SMLoc DirectiveLoc);
399 bool ParseDirectiveMacrosOnOff(StringRef Directive);
400
Eli Bendersky4766ef42012-12-20 19:05:53 +0000401 // ".bundle_align_mode"
402 bool ParseDirectiveBundleAlignMode();
403 // ".bundle_lock"
404 bool ParseDirectiveBundleLock();
405 // ".bundle_unlock"
406 bool ParseDirectiveBundleUnlock();
407
Eli Bendersky6ee13082013-01-15 22:59:42 +0000408 // ".space", ".skip"
409 bool ParseDirectiveSpace(StringRef IDVal);
410
411 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
412 bool ParseDirectiveLEB128(bool Signed);
413
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000414 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
415 /// accepts a single symbol (which should be a label or an external).
416 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000417
418 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
419
420 bool ParseDirectiveAbort(); // ".abort"
421 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000422 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000423
424 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000425 // ".ifb" or ".ifnb", depending on ExpectBlank.
426 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000427 // ".ifc" or ".ifnc", depending on ExpectEqual.
428 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000429 // ".ifdef" or ".ifndef", depending on expect_defined
430 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000431 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
432 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
433 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000434 virtual bool parseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000435
436 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
437 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000438
Rafael Espindola761cb062012-06-03 23:57:14 +0000439 // Macro-like directives
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000440 MCAsmMacro *ParseMacroLikeBody(SMLoc DirectiveLoc);
441 void InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +0000442 raw_svector_ostream &OS);
443 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000444 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000445 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000446 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000447
Chad Rosier469b1442013-02-12 21:33:51 +0000448 // "_emit" or "__emit"
449 bool ParseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
450 size_t Len);
451
452 // "align"
453 bool ParseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000454
Eli Bendersky6ee13082013-01-15 22:59:42 +0000455 void initializeDirectiveKindMap();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000456};
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000457}
458
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000459namespace llvm {
460
461extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000462extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000463extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000464
465}
466
Chris Lattneraaec2052010-01-19 19:46:13 +0000467enum { DEFAULT_ADDRSPACE = 0 };
468
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000469AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000470 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000471 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Eli Bendersky6ee13082013-01-15 22:59:42 +0000472 PlatformParser(0),
Eli Bendersky733c3362013-01-14 18:08:41 +0000473 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000474 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000475 // Save the old handler.
476 SavedDiagHandler = SrcMgr.getDiagHandler();
477 SavedDiagContext = SrcMgr.getDiagContext();
478 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000479 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000480 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000481
Daniel Dunbare4749702010-07-12 18:12:02 +0000482 // Initialize the platform / file format parser.
483 //
484 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
485 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000486 if (_MAI.hasMicrosoftFastStdCallMangling()) {
487 PlatformParser = createCOFFAsmParser();
488 PlatformParser->Initialize(*this);
489 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000490 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000491 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000492 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000493 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000494 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000495 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000496 }
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000497
Eli Bendersky6ee13082013-01-15 22:59:42 +0000498 initializeDirectiveKindMap();
Chris Lattnerebb89b42009-09-27 21:16:52 +0000499}
500
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000501AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000502 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
503
504 // Destroy any macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000505 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
Daniel Dunbar56491302010-07-29 01:51:55 +0000506 ie = MacroMap.end(); it != ie; ++it)
507 delete it->getValue();
508
Daniel Dunbare4749702010-07-12 18:12:02 +0000509 delete PlatformParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000510}
511
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000512void AsmParser::PrintMacroInstantiations() {
513 // Print the active macro instantiation stack.
514 for (std::vector<MacroInstantiation*>::const_reverse_iterator
515 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000516 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
517 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000518}
519
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000520bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000521 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000522 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000523 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000524 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000525 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000526}
527
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000528bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000529 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000530 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000531 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000532 return true;
533}
534
Sean Callananfd0b0282010-01-21 00:19:58 +0000535bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000536 std::string IncludedFile;
537 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000538 if (NewBuf == -1)
539 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000540
Sean Callananfd0b0282010-01-21 00:19:58 +0000541 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000542
Sean Callananfd0b0282010-01-21 00:19:58 +0000543 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000544
Sean Callananfd0b0282010-01-21 00:19:58 +0000545 return false;
546}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000547
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000548/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000549/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000550/// returns true on failure.
551bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
552 std::string IncludedFile;
553 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
554 if (NewBuf == -1)
555 return true;
556
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000557 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000558 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
559 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000560 return false;
561}
562
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000563void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
564 if (InBuffer != -1) {
565 CurBuffer = InBuffer;
566 } else {
567 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
568 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000569 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
570}
571
Sean Callananfd0b0282010-01-21 00:19:58 +0000572const AsmToken &AsmParser::Lex() {
573 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000574
Sean Callananfd0b0282010-01-21 00:19:58 +0000575 if (tok->is(AsmToken::Eof)) {
576 // If this is the end of an included file, pop the parent file off the
577 // include stack.
578 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
579 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000580 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000581 tok = &Lexer.Lex();
582 }
583 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000584
Sean Callananfd0b0282010-01-21 00:19:58 +0000585 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000586 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000587
Sean Callananfd0b0282010-01-21 00:19:58 +0000588 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000589}
590
Chris Lattner79180e22010-04-05 23:15:42 +0000591bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000592 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000593 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000594 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000595
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000596 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000597 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000598
599 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000600 AsmCond StartingCondState = TheCondState;
601
Kevin Enderby613b7572011-11-01 22:27:22 +0000602 // If we are generating dwarf for assembly source files save the initial text
603 // section and generate a .file directive.
604 if (getContext().getGenDwarfForAssembly()) {
Peter Collingbournedf39be62013-04-17 21:18:16 +0000605 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
Kevin Enderby94c2e852011-12-09 18:09:40 +0000606 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
607 getStreamer().EmitLabel(SectionStartSym);
608 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000609 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
Eric Christopher6c583142012-12-18 00:31:01 +0000610 StringRef(),
611 getContext().getMainFileName());
Kevin Enderby613b7572011-11-01 22:27:22 +0000612 }
613
Chris Lattnerb717fb02009-07-02 21:53:43 +0000614 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000615 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000616 ParseStatementInfo Info;
617 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000618
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000619 // We had an error, validate that one was emitted and recover by skipping to
620 // the next line.
621 assert(HadError && "Parse statement returned an error, but none emitted!");
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000622 eatToEndOfStatement();
Chris Lattnerb717fb02009-07-02 21:53:43 +0000623 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000624
625 if (TheCondState.TheCond != StartingCondState.TheCond ||
626 TheCondState.Ignore != StartingCondState.Ignore)
627 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000628
629 // Check to see there are no empty DwarfFile slots.
Manman Ren9e999ad2013-03-12 20:17:00 +0000630 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000631 getContext().getMCDwarfFiles();
632 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000633 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000634 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000635 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000636
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000637 // Check to see that all assembler local symbols were actually defined.
638 // Targets that don't do subsections via symbols may not want this, though,
639 // so conservatively exclude them. Only do this if we're finalizing, though,
640 // as otherwise we won't necessarilly have seen everything yet.
641 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
642 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
643 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
644 e = Symbols.end();
645 i != e; ++i) {
646 MCSymbol *Sym = i->getValue();
647 // Variable symbols may not be marked as defined, so check those
648 // explicitly. If we know it's a variable, we have a definition for
649 // the purposes of this check.
650 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
651 // FIXME: We would really like to refer back to where the symbol was
652 // first referenced for a source location. We need to add something
653 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000654 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
655 "assembler local symbol '" + Sym->getName() +
656 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000657 }
658 }
659
660
Chris Lattner79180e22010-04-05 23:15:42 +0000661 // Finalize the output stream if there are no errors and if the client wants
662 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000663 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000664 Out.Finish();
665
Chris Lattnerb717fb02009-07-02 21:53:43 +0000666 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000667}
668
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000669void AsmParser::checkForValidSection() {
Peter Collingbournedf39be62013-04-17 21:18:16 +0000670 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000671 TokError("expected section directive before assembly directive");
Eli Bendersky030f63a2013-01-14 19:04:57 +0000672 Out.InitToTextSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000673 }
674}
675
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000676/// eatToEndOfStatement - Throw away the rest of the line for testing purposes.
677void AsmParser::eatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000678 while (Lexer.isNot(AsmToken::EndOfStatement) &&
679 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000680 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000681
Chris Lattner2cf5f142009-06-22 01:29:09 +0000682 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000683 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000684 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000685}
686
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000687StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000688 const char *Start = getTok().getLoc().getPointer();
689
690 while (Lexer.isNot(AsmToken::EndOfStatement) &&
691 Lexer.isNot(AsmToken::Eof))
692 Lex();
693
694 const char *End = getTok().getLoc().getPointer();
695 return StringRef(Start, End - Start);
696}
Chris Lattnerc4193832009-06-22 05:51:26 +0000697
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000698StringRef AsmParser::ParseStringToComma() {
699 const char *Start = getTok().getLoc().getPointer();
700
701 while (Lexer.isNot(AsmToken::EndOfStatement) &&
702 Lexer.isNot(AsmToken::Comma) &&
703 Lexer.isNot(AsmToken::Eof))
704 Lex();
705
706 const char *End = getTok().getLoc().getPointer();
707 return StringRef(Start, End - Start);
708}
709
Chris Lattner74ec1a32009-06-22 06:32:03 +0000710/// ParseParenExpr - Parse a paren expression and return it.
711/// NOTE: This assumes the leading '(' has already been consumed.
712///
713/// parenexpr ::= expr)
714///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000715bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000716 if (parseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000717 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000718 return TokError("expected ')' in parentheses expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000719 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000720 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000721 return false;
722}
Chris Lattnerc4193832009-06-22 05:51:26 +0000723
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000724/// ParseBracketExpr - Parse a bracket expression and return it.
725/// NOTE: This assumes the leading '[' has already been consumed.
726///
727/// bracketexpr ::= expr]
728///
729bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000730 if (parseExpression(Res)) return true;
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000731 if (Lexer.isNot(AsmToken::RBrac))
732 return TokError("expected ']' in brackets expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000733 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000734 Lex();
735 return false;
736}
737
Chris Lattner74ec1a32009-06-22 06:32:03 +0000738/// ParsePrimaryExpr - Parse a primary expression and return it.
739/// primaryexpr ::= (parenexpr
740/// primaryexpr ::= symbol
741/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000742/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000743/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000744bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby5de048e2013-01-22 21:09:20 +0000745 SMLoc FirstTokenLoc = getLexer().getLoc();
746 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
747 switch (FirstTokenKind) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000748 default:
749 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000750 // If we have an error assume that we've already handled it.
751 case AsmToken::Error:
752 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000753 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000754 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000755 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000756 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000757 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000758 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000759 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000760 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000761 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000762 StringRef Identifier;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000763 if (parseIdentifier(Identifier)) {
Kevin Enderby5de048e2013-01-22 21:09:20 +0000764 if (FirstTokenKind == AsmToken::Dollar)
765 return Error(FirstTokenLoc, "invalid token in expression");
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000766 return true;
Kevin Enderby5de048e2013-01-22 21:09:20 +0000767 }
Daniel Dunbare17edff2010-08-24 19:13:42 +0000768
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000769 EndLoc = SMLoc::getFromPointer(Identifier.end());
770
Daniel Dunbarfffff912009-10-16 01:34:54 +0000771 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000772 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000773 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000774
775 // Lookup the symbol variant if used.
776 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000777 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000778 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000779 if (Variant == MCSymbolRefExpr::VK_Invalid) {
780 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000781 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000782 }
783 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000784
Daniel Dunbarfffff912009-10-16 01:34:54 +0000785 // If this is an absolute variable reference, substitute it now to preserve
786 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000787 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000788 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000789 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000790
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000791 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000792 return false;
793 }
794
795 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000796 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000797 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000798 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000799 case AsmToken::Integer: {
800 SMLoc Loc = getTok().getLoc();
801 int64_t IntVal = getTok().getIntVal();
802 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000803 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000804 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000805 // Look for 'b' or 'f' following an Integer as a directional label
806 if (Lexer.getKind() == AsmToken::Identifier) {
807 StringRef IDVal = getTok().getString();
808 if (IDVal == "f" || IDVal == "b"){
809 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
810 IDVal == "f" ? 1 : 0);
811 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
812 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000813 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000814 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000815 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000816 Lex(); // Eat identifier.
817 }
818 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000819 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000820 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000821 case AsmToken::Real: {
822 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000823 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000824 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000825 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000826 Lex(); // Eat token.
827 return false;
828 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000829 case AsmToken::Dot: {
830 // This is a '.' reference, which references the current PC. Emit a
831 // temporary label to the streamer and refer to it.
832 MCSymbol *Sym = Ctx.CreateTempSymbol();
833 Out.EmitLabel(Sym);
834 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000835 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattnerd3050352010-04-14 04:40:28 +0000836 Lex(); // Eat identifier.
837 return false;
838 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000839 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000840 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000841 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000842 case AsmToken::LBrac:
843 if (!PlatformParser->HasBracketExpressions())
844 return TokError("brackets expression not supported on this target");
845 Lex(); // Eat the '['.
846 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000847 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000848 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000849 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000850 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000851 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000852 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000853 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000854 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000855 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000856 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000857 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000858 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000859 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000860 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000861 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000862 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000863 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000864 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000865 }
866}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000867
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000868bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000869 SMLoc EndLoc;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000870 return parseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000871}
872
Chad Rosierba69b362013-04-10 17:35:30 +0000873bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
874 return ParsePrimaryExpr(Res, EndLoc);
875}
876
Daniel Dunbarcceba832010-09-17 02:47:07 +0000877const MCExpr *
878AsmParser::ApplyModifierToExpr(const MCExpr *E,
879 MCSymbolRefExpr::VariantKind Variant) {
880 // Recurse over the given expression, rebuilding it to apply the given variant
881 // if there is exactly one symbol.
882 switch (E->getKind()) {
883 case MCExpr::Target:
884 case MCExpr::Constant:
885 return 0;
886
887 case MCExpr::SymbolRef: {
888 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
889
890 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
891 TokError("invalid variant on expression '" +
892 getTok().getIdentifier() + "' (already modified)");
893 return E;
894 }
895
896 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
897 }
898
899 case MCExpr::Unary: {
900 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
901 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
902 if (!Sub)
903 return 0;
904 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
905 }
906
907 case MCExpr::Binary: {
908 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
909 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
910 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
911
912 if (!LHS && !RHS)
913 return 0;
914
915 if (!LHS) LHS = BE->getLHS();
916 if (!RHS) RHS = BE->getRHS();
917
918 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
919 }
920 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000921
Craig Topper85814382012-02-07 05:05:23 +0000922 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000923}
924
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000925/// parseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000926///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000927/// expr ::= expr &&,|| expr -> lowest.
928/// expr ::= expr |,^,&,! expr
929/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
930/// expr ::= expr <<,>> expr
931/// expr ::= expr +,- expr
932/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000933/// expr ::= primaryexpr
934///
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000935bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000936 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000937 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000938 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
939 return true;
940
Daniel Dunbarcceba832010-09-17 02:47:07 +0000941 // As a special case, we support 'a op b @ modifier' by rewriting the
942 // expression to include the modifier. This is inefficient, but in general we
943 // expect users to use 'a@modifier op b'.
944 if (Lexer.getKind() == AsmToken::At) {
945 Lex();
946
947 if (Lexer.isNot(AsmToken::Identifier))
948 return TokError("unexpected symbol modifier following '@'");
949
950 MCSymbolRefExpr::VariantKind Variant =
951 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
952 if (Variant == MCSymbolRefExpr::VK_Invalid)
953 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
954
955 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
956 if (!ModifiedRes) {
957 return TokError("invalid modifier '" + getTok().getIdentifier() +
958 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000959 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000960
Daniel Dunbarcceba832010-09-17 02:47:07 +0000961 Res = ModifiedRes;
962 Lex();
963 }
964
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000965 // Try to constant fold it up front, if possible.
966 int64_t Value;
967 if (Res->EvaluateAsAbsolute(Value))
968 Res = MCConstantExpr::Create(Value, getContext());
969
970 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000971}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000972
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000973bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000974 Res = 0;
975 return ParseParenExpr(Res, EndLoc) ||
976 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000977}
978
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000979bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000980 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000981
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000982 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000983 if (parseExpression(Expr))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000984 return true;
985
Daniel Dunbare00b0112009-10-16 01:57:52 +0000986 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000987 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000988
989 return false;
990}
991
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000992static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000993 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000994 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000995 default:
996 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000997
Jim Grosbachfbe16812011-08-20 16:24:13 +0000998 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000999 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001000 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001001 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001002 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001003 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001004 return 1;
1005
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001006
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001007 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +00001008 //
1009 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +00001010 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001011 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001012 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001013 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001014 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001015 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001016 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001017 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001018 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001019
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001020 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001021 case AsmToken::EqualEqual:
1022 Kind = MCBinaryExpr::EQ;
1023 return 3;
1024 case AsmToken::ExclaimEqual:
1025 case AsmToken::LessGreater:
1026 Kind = MCBinaryExpr::NE;
1027 return 3;
1028 case AsmToken::Less:
1029 Kind = MCBinaryExpr::LT;
1030 return 3;
1031 case AsmToken::LessEqual:
1032 Kind = MCBinaryExpr::LTE;
1033 return 3;
1034 case AsmToken::Greater:
1035 Kind = MCBinaryExpr::GT;
1036 return 3;
1037 case AsmToken::GreaterEqual:
1038 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001039 return 3;
1040
Jim Grosbachfbe16812011-08-20 16:24:13 +00001041 // Intermediate Precedence: <<, >>
1042 case AsmToken::LessLess:
1043 Kind = MCBinaryExpr::Shl;
1044 return 4;
1045 case AsmToken::GreaterGreater:
1046 Kind = MCBinaryExpr::Shr;
1047 return 4;
1048
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001049 // High Intermediate Precedence: +, -
1050 case AsmToken::Plus:
1051 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001052 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001053 case AsmToken::Minus:
1054 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001055 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001056
Jim Grosbachfbe16812011-08-20 16:24:13 +00001057 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001058 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001059 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001060 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001061 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001062 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001063 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001064 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001065 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001066 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001067 }
1068}
1069
1070
1071/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1072/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001073bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1074 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001075 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001076 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001077 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001078
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001079 // If the next token is lower precedence than we are allowed to eat, return
1080 // successfully with what we ate already.
1081 if (TokPrec < Precedence)
1082 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001083
Sean Callanan79ed1a82010-01-19 20:22:31 +00001084 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001085
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001086 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001087 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001088 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001089
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001090 // If BinOp binds less tightly with RHS than the operator after RHS, let
1091 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001092 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001093 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001094 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001095 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001096 }
1097
Daniel Dunbar475839e2009-06-29 20:37:27 +00001098 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001099 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001100 }
1101}
1102
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001103/// ParseStatement:
1104/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001105/// ::= Label* Directive ...Operands... EndOfStatement
1106/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001107bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001108 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001109 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001110 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001111 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001112 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001113
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001114 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001115 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001116 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001117 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001118 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001119 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001120 if (Lexer.is(AsmToken::Hash))
1121 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001122
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001123 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001124 if (Lexer.is(AsmToken::Integer)) {
1125 LocalLabelVal = getTok().getIntVal();
1126 if (LocalLabelVal < 0) {
1127 if (!TheCondState.Ignore)
1128 return TokError("unexpected token at start of statement");
1129 IDVal = "";
Eli Benderskyed5df012013-01-16 19:32:36 +00001130 } else {
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001131 IDVal = getTok().getString();
1132 Lex(); // Consume the integer token to be used as an identifier token.
1133 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001134 if (!TheCondState.Ignore)
1135 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001136 }
1137 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001138 } else if (Lexer.is(AsmToken::Dot)) {
1139 // Treat '.' as a valid identifier in this context.
1140 Lex();
1141 IDVal = ".";
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001142 } else if (parseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001143 if (!TheCondState.Ignore)
1144 return TokError("unexpected token at start of statement");
1145 IDVal = "";
1146 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001147
Chris Lattner7834fac2010-04-17 18:14:27 +00001148 // Handle conditional assembly here before checking for skipping. We
1149 // have to do this so that .endif isn't skipped in a ".if 0" block for
1150 // example.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001151 StringMap<DirectiveKind>::const_iterator DirKindIt =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001152 DirectiveKindMap.find(IDVal);
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001153 DirectiveKind DirKind =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001154 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1155 DirKindIt->getValue();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001156 switch (DirKind) {
1157 default:
1158 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001159 case DK_IF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001160 return ParseDirectiveIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001161 case DK_IFB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001162 return ParseDirectiveIfb(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001163 case DK_IFNB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001164 return ParseDirectiveIfb(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001165 case DK_IFC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001166 return ParseDirectiveIfc(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001167 case DK_IFNC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001168 return ParseDirectiveIfc(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001169 case DK_IFDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001170 return ParseDirectiveIfdef(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001171 case DK_IFNDEF:
1172 case DK_IFNOTDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001173 return ParseDirectiveIfdef(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001174 case DK_ELSEIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001175 return ParseDirectiveElseIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001176 case DK_ELSE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001177 return ParseDirectiveElse(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001178 case DK_ENDIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001179 return ParseDirectiveEndIf(IDLoc);
1180 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001181
Eli Benderskyed5df012013-01-16 19:32:36 +00001182 // Ignore the statement if in the middle of inactive conditional
1183 // (e.g. ".if 0").
Chad Rosier17feeec2012-10-20 00:47:08 +00001184 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001185 eatToEndOfStatement();
Chris Lattner7834fac2010-04-17 18:14:27 +00001186 return false;
1187 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001188
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001189 // FIXME: Recurse on local labels?
1190
1191 // See what kind of statement we have.
1192 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001193 case AsmToken::Colon: {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001194 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001195
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001196 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001197 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001198
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001199 // Diagnose attempt to use '.' as a label.
1200 if (IDVal == ".")
1201 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1202
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001203 // Diagnose attempt to use a variable as a label.
1204 //
1205 // FIXME: Diagnostics. Note the location of the definition as a label.
1206 // FIXME: This doesn't diagnose assignment to a symbol which has been
1207 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001208 MCSymbol *Sym;
1209 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001210 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001211 else
1212 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001213 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001214 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001215
Daniel Dunbar959fd882009-08-26 22:13:22 +00001216 // Emit the label.
Chad Rosierdeb1bab2013-01-07 20:34:12 +00001217 if (!ParsingInlineAsm)
1218 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001219
Kevin Enderby94c2e852011-12-09 18:09:40 +00001220 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001221 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001222 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001223 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1224 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001225
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001226 // Consume any end of statement token, if present, to avoid spurious
1227 // AddBlankLine calls().
1228 if (Lexer.is(AsmToken::EndOfStatement)) {
1229 Lex();
1230 if (Lexer.is(AsmToken::Eof))
1231 return false;
1232 }
1233
Eli Friedman2128aae2012-10-22 23:58:19 +00001234 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001235 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001236
Daniel Dunbar3f872332009-07-28 16:08:33 +00001237 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001238 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001239 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001240
Nico Weber4c4c7322011-01-28 03:04:41 +00001241 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001242
1243 default: // Normal instruction or directive.
1244 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001245 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001246
1247 // If macros are enabled, check to see if this is a macro instantiation.
Eli Bendersky733c3362013-01-14 18:08:41 +00001248 if (MacrosEnabled())
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001249 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1250 return HandleMacroEntry(M, IDLoc);
1251 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001252
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001253 // Otherwise, we have a normal instruction or directive.
Eli Bendersky6ee13082013-01-15 22:59:42 +00001254
1255 // Directives start with "."
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001256 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00001257 // There are several entities interested in parsing directives:
1258 //
1259 // 1. The target-specific assembly parser. Some directives are target
1260 // specific or may potentially behave differently on certain targets.
1261 // 2. Asm parser extensions. For example, platform-specific parsers
1262 // (like the ELF parser) register themselves as extensions.
1263 // 3. The generic directive parser implemented by this class. These are
1264 // all the directives that behave in a target and platform independent
1265 // manner, or at least have a default behavior that's shared between
1266 // all targets and platforms.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001267
Eli Bendersky6ee13082013-01-15 22:59:42 +00001268 // First query the target-specific parser. It will return 'true' if it
1269 // isn't interested in this directive.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001270 if (!getTargetParser().ParseDirective(ID))
1271 return false;
1272
Eli Bendersky6ee13082013-01-15 22:59:42 +00001273 // Next, check the extention directive map to see if any extension has
1274 // registered itself to parse this directive.
1275 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1276 ExtensionDirectiveMap.lookup(IDVal);
1277 if (Handler.first)
1278 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1279
1280 // Finally, if no one else is interested in this directive, it must be
1281 // generic and familiar to this class.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001282 switch (DirKind) {
1283 default:
1284 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001285 case DK_SET:
1286 case DK_EQU:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001287 return ParseDirectiveSet(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001288 case DK_EQUIV:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001289 return ParseDirectiveSet(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001290 case DK_ASCII:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001291 return ParseDirectiveAscii(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001292 case DK_ASCIZ:
1293 case DK_STRING:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001294 return ParseDirectiveAscii(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001295 case DK_BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001296 return ParseDirectiveValue(1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001297 case DK_SHORT:
1298 case DK_VALUE:
1299 case DK_2BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001300 return ParseDirectiveValue(2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001301 case DK_LONG:
1302 case DK_INT:
1303 case DK_4BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001304 return ParseDirectiveValue(4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001305 case DK_QUAD:
1306 case DK_8BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001307 return ParseDirectiveValue(8);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001308 case DK_SINGLE:
1309 case DK_FLOAT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001310 return ParseDirectiveRealValue(APFloat::IEEEsingle);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001311 case DK_DOUBLE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001312 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001313 case DK_ALIGN: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001314 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1315 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1316 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001317 case DK_ALIGN32: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001318 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1319 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1320 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001321 case DK_BALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001322 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001323 case DK_BALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001324 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001325 case DK_BALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001326 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001327 case DK_P2ALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001328 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001329 case DK_P2ALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001330 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001331 case DK_P2ALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001332 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001333 case DK_ORG:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001334 return ParseDirectiveOrg();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001335 case DK_FILL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001336 return ParseDirectiveFill();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001337 case DK_ZERO:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001338 return ParseDirectiveZero();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001339 case DK_EXTERN:
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001340 eatToEndOfStatement(); // .extern is the default, ignore it.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001341 return false;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001342 case DK_GLOBL:
1343 case DK_GLOBAL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001344 return ParseDirectiveSymbolAttribute(MCSA_Global);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001345 case DK_INDIRECT_SYMBOL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001346 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001347 case DK_LAZY_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001348 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001349 case DK_NO_DEAD_STRIP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001350 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001351 case DK_SYMBOL_RESOLVER:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001352 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001353 case DK_PRIVATE_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001354 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001355 case DK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001356 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001357 case DK_WEAK_DEFINITION:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001358 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001359 case DK_WEAK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001360 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001361 case DK_WEAK_DEF_CAN_BE_HIDDEN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001362 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001363 case DK_COMM:
1364 case DK_COMMON:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001365 return ParseDirectiveComm(/*IsLocal=*/false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001366 case DK_LCOMM:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001367 return ParseDirectiveComm(/*IsLocal=*/true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001368 case DK_ABORT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001369 return ParseDirectiveAbort();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001370 case DK_INCLUDE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001371 return ParseDirectiveInclude();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001372 case DK_INCBIN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001373 return ParseDirectiveIncbin();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001374 case DK_CODE16:
1375 case DK_CODE16GCC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001376 return TokError(Twine(IDVal) + " not supported yet");
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001377 case DK_REPT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001378 return ParseDirectiveRept(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001379 case DK_IRP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001380 return ParseDirectiveIrp(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001381 case DK_IRPC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001382 return ParseDirectiveIrpc(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001383 case DK_ENDR:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001384 return ParseDirectiveEndr(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001385 case DK_BUNDLE_ALIGN_MODE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001386 return ParseDirectiveBundleAlignMode();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001387 case DK_BUNDLE_LOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001388 return ParseDirectiveBundleLock();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001389 case DK_BUNDLE_UNLOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001390 return ParseDirectiveBundleUnlock();
Eli Bendersky6ee13082013-01-15 22:59:42 +00001391 case DK_SLEB128:
1392 return ParseDirectiveLEB128(true);
1393 case DK_ULEB128:
1394 return ParseDirectiveLEB128(false);
1395 case DK_SPACE:
1396 case DK_SKIP:
1397 return ParseDirectiveSpace(IDVal);
1398 case DK_FILE:
1399 return ParseDirectiveFile(IDLoc);
1400 case DK_LINE:
1401 return ParseDirectiveLine();
1402 case DK_LOC:
1403 return ParseDirectiveLoc();
1404 case DK_STABS:
1405 return ParseDirectiveStabs();
1406 case DK_CFI_SECTIONS:
1407 return ParseDirectiveCFISections();
1408 case DK_CFI_STARTPROC:
1409 return ParseDirectiveCFIStartProc();
1410 case DK_CFI_ENDPROC:
1411 return ParseDirectiveCFIEndProc();
1412 case DK_CFI_DEF_CFA:
1413 return ParseDirectiveCFIDefCfa(IDLoc);
1414 case DK_CFI_DEF_CFA_OFFSET:
1415 return ParseDirectiveCFIDefCfaOffset();
1416 case DK_CFI_ADJUST_CFA_OFFSET:
1417 return ParseDirectiveCFIAdjustCfaOffset();
1418 case DK_CFI_DEF_CFA_REGISTER:
1419 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1420 case DK_CFI_OFFSET:
1421 return ParseDirectiveCFIOffset(IDLoc);
1422 case DK_CFI_REL_OFFSET:
1423 return ParseDirectiveCFIRelOffset(IDLoc);
1424 case DK_CFI_PERSONALITY:
1425 return ParseDirectiveCFIPersonalityOrLsda(true);
1426 case DK_CFI_LSDA:
1427 return ParseDirectiveCFIPersonalityOrLsda(false);
1428 case DK_CFI_REMEMBER_STATE:
1429 return ParseDirectiveCFIRememberState();
1430 case DK_CFI_RESTORE_STATE:
1431 return ParseDirectiveCFIRestoreState();
1432 case DK_CFI_SAME_VALUE:
1433 return ParseDirectiveCFISameValue(IDLoc);
1434 case DK_CFI_RESTORE:
1435 return ParseDirectiveCFIRestore(IDLoc);
1436 case DK_CFI_ESCAPE:
1437 return ParseDirectiveCFIEscape();
1438 case DK_CFI_SIGNAL_FRAME:
1439 return ParseDirectiveCFISignalFrame();
1440 case DK_CFI_UNDEFINED:
1441 return ParseDirectiveCFIUndefined(IDLoc);
1442 case DK_CFI_REGISTER:
1443 return ParseDirectiveCFIRegister(IDLoc);
1444 case DK_MACROS_ON:
1445 case DK_MACROS_OFF:
1446 return ParseDirectiveMacrosOnOff(IDVal);
1447 case DK_MACRO:
1448 return ParseDirectiveMacro(IDLoc);
1449 case DK_ENDM:
1450 case DK_ENDMACRO:
1451 return ParseDirectiveEndMacro(IDVal);
1452 case DK_PURGEM:
1453 return ParseDirectivePurgeMacro(IDLoc);
Eli Friedman5d68ec22010-07-19 04:17:25 +00001454 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001455
Jim Grosbach686c0182012-05-01 18:38:27 +00001456 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001457 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001458
Chad Rosier469b1442013-02-12 21:33:51 +00001459 // __asm _emit or __asm __emit
1460 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1461 IDVal == "_EMIT" || IDVal == "__EMIT"))
1462 return ParseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1463
1464 // __asm align
1465 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1466 return ParseDirectiveMSAlign(IDLoc, Info);
Eli Friedman2128aae2012-10-22 23:58:19 +00001467
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001468 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001469
Chris Lattnera7f13542010-05-19 23:34:33 +00001470 // Canonicalize the opcode to lower case.
Eli Benderskyed5df012013-01-16 19:32:36 +00001471 std::string OpcodeStr = IDVal.lower();
Chad Rosier6a020a72012-10-25 20:41:34 +00001472 ParseInstructionInfo IInfo(Info.AsmRewrites);
Eli Benderskyed5df012013-01-16 19:32:36 +00001473 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr,
1474 IDLoc, Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001475 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001476
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001477 // Dump the parsed representation, if requested.
1478 if (getShowParsedOperands()) {
1479 SmallString<256> Str;
1480 raw_svector_ostream OS(Str);
1481 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001482 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001483 if (i != 0)
1484 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001485 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001486 }
1487 OS << "]";
1488
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001489 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001490 }
1491
Kevin Enderby613b7572011-11-01 22:27:22 +00001492 // If we are generating dwarf for assembly source files and the current
1493 // section is the initial text section then generate a .loc directive for
1494 // the instruction.
1495 if (!HadError && getContext().getGenDwarfForAssembly() &&
Peter Collingbournedf39be62013-04-17 21:18:16 +00001496 getContext().getGenDwarfSection() ==
1497 getStreamer().getCurrentSection().first) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001498
Eli Benderskyed5df012013-01-16 19:32:36 +00001499 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
Kevin Enderby938482f2012-11-01 17:31:35 +00001500
Eli Benderskyed5df012013-01-16 19:32:36 +00001501 // If we previously parsed a cpp hash file line comment then make sure the
1502 // current Dwarf File is for the CppHashFilename if not then emit the
1503 // Dwarf File table for it and adjust the line number for the .loc.
Manman Ren9e999ad2013-03-12 20:17:00 +00001504 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
Eli Benderskyed5df012013-01-16 19:32:36 +00001505 getContext().getMCDwarfFiles();
1506 if (CppHashFilename.size() != 0) {
1507 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
Kevin Enderby938482f2012-11-01 17:31:35 +00001508 CppHashFilename)
Eli Benderskyed5df012013-01-16 19:32:36 +00001509 getStreamer().EmitDwarfFileDirective(
1510 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001511
Kevin Enderby32c1a822012-11-05 21:55:41 +00001512 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
Kevin Enderby938482f2012-11-01 17:31:35 +00001513 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
Eli Benderskyed5df012013-01-16 19:32:36 +00001514 }
Kevin Enderby938482f2012-11-01 17:31:35 +00001515
Kevin Enderby613b7572011-11-01 22:27:22 +00001516 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001517 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001518 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001519 StringRef());
1520 }
1521
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001522 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001523 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001524 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001525 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1526 Info.ParsedOperands,
1527 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001528 ParsingInlineAsm);
1529 }
Chris Lattner98986712010-01-14 22:21:20 +00001530
Chris Lattnercbf8a982010-09-11 16:18:25 +00001531 // Don't skip the rest of the line, the instruction parser is responsible for
1532 // that.
1533 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001534}
Chris Lattner9a023f72009-06-24 04:43:34 +00001535
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001536/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1537/// since they may not be able to be tokenized to get to the end of line token.
1538void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001539 if (!Lexer.is(AsmToken::EndOfStatement))
1540 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001541 // Eat EOL.
1542 Lex();
1543}
1544
1545/// ParseCppHashLineFilenameComment as this:
1546/// ::= # number "filename"
1547/// or just as a full line comment if it doesn't have a number and a string.
1548bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1549 Lex(); // Eat the hash token.
1550
1551 if (getLexer().isNot(AsmToken::Integer)) {
1552 // Consume the line since in cases it is not a well-formed line directive,
1553 // as if were simply a full line comment.
1554 EatToEndOfLine();
1555 return false;
1556 }
1557
1558 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001559 Lex();
1560
1561 if (getLexer().isNot(AsmToken::String)) {
1562 EatToEndOfLine();
1563 return false;
1564 }
1565
1566 StringRef Filename = getTok().getString();
1567 // Get rid of the enclosing quotes.
1568 Filename = Filename.substr(1, Filename.size()-2);
1569
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001570 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1571 CppHashLoc = L;
1572 CppHashFilename = Filename;
1573 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001574 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001575
1576 // Ignore any trailing characters, they're just comment.
1577 EatToEndOfLine();
1578 return false;
1579}
1580
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001581/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001582/// for the Filename and LineNo if any in the diagnostic.
1583void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1584 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1585 raw_ostream &OS = errs();
1586
1587 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1588 const SMLoc &DiagLoc = Diag.getLoc();
1589 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1590 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1591
1592 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1593 // before printing the message.
1594 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001595 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001596 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1597 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1598 }
1599
Eric Christopher2318ba12012-12-18 00:30:54 +00001600 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001601 // manager changed or buffer changed (like in a nested include) then just
1602 // print the normal diagnostic using its Filename and LineNo.
1603 if (!Parser->CppHashLineNumber ||
1604 &DiagSrcMgr != &Parser->SrcMgr ||
1605 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001606 if (Parser->SavedDiagHandler)
1607 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1608 else
1609 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001610 return;
1611 }
1612
Eric Christopher2318ba12012-12-18 00:30:54 +00001613 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001614 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1615 // the diagnostic.
1616 const std::string Filename = Parser->CppHashFilename;
1617
1618 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1619 int CppHashLocLineNo =
1620 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1621 int LineNo = Parser->CppHashLineNumber - 1 +
1622 (DiagLocLineNo - CppHashLocLineNo);
1623
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001624 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1625 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001626 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001627 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001628
Benjamin Kramer04a04262011-10-16 10:48:29 +00001629 if (Parser->SavedDiagHandler)
1630 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1631 else
1632 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001633}
1634
Rafael Espindola799aacf2012-08-21 18:29:30 +00001635// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1636// difference being that that function accepts '@' as part of identifiers and
1637// we can't do that. AsmLexer.cpp should probably be changed to handle
1638// '@' as a special case when needed.
1639static bool isIdentifierChar(char c) {
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001640 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1641 c == '.';
Rafael Espindola799aacf2012-08-21 18:29:30 +00001642}
1643
Rafael Espindola761cb062012-06-03 23:57:14 +00001644bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001645 const MCAsmMacroParameters &Parameters,
1646 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001647 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001648 unsigned NParameters = Parameters.size();
1649 if (NParameters != 0 && NParameters != A.size())
1650 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001651
Preston Gurd7b6f2032012-09-19 20:36:12 +00001652 // A macro without parameters is handled differently on Darwin:
1653 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001654 while (!Body.empty()) {
1655 // Scan for the next substitution.
1656 std::size_t End = Body.size(), Pos = 0;
1657 for (; Pos != End; ++Pos) {
1658 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001659 if (!NParameters) {
1660 // This macro has no parameters, look for $0, $1, etc.
1661 if (Body[Pos] != '$' || Pos + 1 == End)
1662 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001663
Rafael Espindola65366442011-06-05 02:43:45 +00001664 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001665 if (Next == '$' || Next == 'n' ||
1666 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola65366442011-06-05 02:43:45 +00001667 break;
1668 } else {
1669 // This macro has parameters, look for \foo, \bar, etc.
1670 if (Body[Pos] == '\\' && Pos + 1 != End)
1671 break;
1672 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001673 }
1674
1675 // Add the prefix.
1676 OS << Body.slice(0, Pos);
1677
1678 // Check if we reached the end.
1679 if (Pos == End)
1680 break;
1681
Rafael Espindola65366442011-06-05 02:43:45 +00001682 if (!NParameters) {
1683 switch (Body[Pos+1]) {
1684 // $$ => $
1685 case '$':
1686 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001687 break;
1688
Rafael Espindola65366442011-06-05 02:43:45 +00001689 // $n => number of arguments
1690 case 'n':
1691 OS << A.size();
1692 break;
1693
1694 // $[0-9] => argument
1695 default: {
1696 // Missing arguments are ignored.
1697 unsigned Index = Body[Pos+1] - '0';
1698 if (Index >= A.size())
1699 break;
1700
1701 // Otherwise substitute with the token values, with spaces eliminated.
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001702 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001703 ie = A[Index].end(); it != ie; ++it)
1704 OS << it->getString();
1705 break;
1706 }
1707 }
1708 Pos += 2;
1709 } else {
1710 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001711 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001712 ++I;
1713
1714 const char *Begin = Body.data() + Pos +1;
1715 StringRef Argument(Begin, I - (Pos +1));
1716 unsigned Index = 0;
1717 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001718 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001719 break;
1720
Preston Gurd7b6f2032012-09-19 20:36:12 +00001721 if (Index == NParameters) {
1722 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1723 Pos += 3;
1724 else {
1725 OS << '\\' << Argument;
1726 Pos = I;
1727 }
1728 } else {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001729 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Preston Gurd7b6f2032012-09-19 20:36:12 +00001730 ie = A[Index].end(); it != ie; ++it)
1731 if (it->getKind() == AsmToken::String)
1732 OS << it->getStringContents();
1733 else
1734 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001735
Preston Gurd7b6f2032012-09-19 20:36:12 +00001736 Pos += 1 + Argument.size();
1737 }
Rafael Espindola65366442011-06-05 02:43:45 +00001738 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001739 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001740 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001741 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001742
Rafael Espindola65366442011-06-05 02:43:45 +00001743 return false;
1744}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001745
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001746MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001747 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001748 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001749 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1750 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001751{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001752}
1753
Preston Gurd7b6f2032012-09-19 20:36:12 +00001754static bool IsOperator(AsmToken::TokenKind kind)
1755{
1756 switch (kind)
1757 {
1758 default:
1759 return false;
1760 case AsmToken::Plus:
1761 case AsmToken::Minus:
1762 case AsmToken::Tilde:
1763 case AsmToken::Slash:
1764 case AsmToken::Star:
1765 case AsmToken::Dot:
1766 case AsmToken::Equal:
1767 case AsmToken::EqualEqual:
1768 case AsmToken::Pipe:
1769 case AsmToken::PipePipe:
1770 case AsmToken::Caret:
1771 case AsmToken::Amp:
1772 case AsmToken::AmpAmp:
1773 case AsmToken::Exclaim:
1774 case AsmToken::ExclaimEqual:
1775 case AsmToken::Percent:
1776 case AsmToken::Less:
1777 case AsmToken::LessEqual:
1778 case AsmToken::LessLess:
1779 case AsmToken::LessGreater:
1780 case AsmToken::Greater:
1781 case AsmToken::GreaterEqual:
1782 case AsmToken::GreaterGreater:
1783 return true;
1784 }
1785}
1786
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001787bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
Preston Gurd7b6f2032012-09-19 20:36:12 +00001788 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001789 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001790 unsigned AddTokens = 0;
1791
1792 // gas accepts arguments separated by whitespace, except on Darwin
1793 if (!IsDarwin)
1794 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001795
1796 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001797 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1798 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001799 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001800 }
1801
1802 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1803 // Spaces and commas cannot be mixed to delimit parameters
1804 if (ArgumentDelimiter == AsmToken::Eof)
1805 ArgumentDelimiter = AsmToken::Comma;
1806 else if (ArgumentDelimiter != AsmToken::Comma) {
1807 Lexer.setSkipSpace(true);
1808 return TokError("expected ' ' for macro argument separator");
1809 }
1810 break;
1811 }
1812
1813 if (Lexer.is(AsmToken::Space)) {
1814 Lex(); // Eat spaces
1815
1816 // Spaces can delimit parameters, but could also be part an expression.
1817 // If the token after a space is an operator, add the token and the next
1818 // one into this argument
1819 if (ArgumentDelimiter == AsmToken::Space ||
1820 ArgumentDelimiter == AsmToken::Eof) {
1821 if (IsOperator(Lexer.getKind())) {
1822 // Check to see whether the token is used as an operator,
1823 // or part of an identifier
Jordan Rose3ebe59c2013-01-07 19:00:49 +00001824 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd7b6f2032012-09-19 20:36:12 +00001825 if (*NextChar == ' ')
1826 AddTokens = 2;
1827 }
1828
1829 if (!AddTokens && ParenLevel == 0) {
1830 if (ArgumentDelimiter == AsmToken::Eof &&
1831 !IsOperator(Lexer.getKind()))
1832 ArgumentDelimiter = AsmToken::Space;
1833 break;
1834 }
1835 }
1836 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001837
1838 // HandleMacroEntry relies on not advancing the lexer here
1839 // to be able to fill in the remaining default parameter values
1840 if (Lexer.is(AsmToken::EndOfStatement))
1841 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001842
1843 // Adjust the current parentheses level.
1844 if (Lexer.is(AsmToken::LParen))
1845 ++ParenLevel;
1846 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1847 --ParenLevel;
1848
1849 // Append the token to the current argument list.
1850 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001851 if (AddTokens)
1852 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001853 Lex();
1854 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001855
1856 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001857 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001858 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001859 return false;
1860}
1861
1862// Parse the macro instantiation arguments.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001863bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001864 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001865 // Argument delimiter is initially unknown. It will be set by
1866 // ParseMacroArgument()
1867 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001868
1869 // Parse two kinds of macro invocations:
1870 // - macros defined without any parameters accept an arbitrary number of them
1871 // - macros defined with parameters accept at most that many of them
1872 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1873 ++Parameter) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001874 MCAsmMacroArgument MA;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001875
Preston Gurd7b6f2032012-09-19 20:36:12 +00001876 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001877 return true;
1878
Preston Gurd6c9176a2012-09-19 20:29:04 +00001879 if (!MA.empty() || !NParameters)
1880 A.push_back(MA);
1881 else if (NParameters) {
1882 if (!M->Parameters[Parameter].second.empty())
1883 A.push_back(M->Parameters[Parameter].second);
1884 }
Jim Grosbach97146442012-07-30 22:44:17 +00001885
Preston Gurd6c9176a2012-09-19 20:29:04 +00001886 // At the end of the statement, fill in remaining arguments that have
1887 // default values. If there aren't any, then the next argument is
1888 // required but missing
1889 if (Lexer.is(AsmToken::EndOfStatement)) {
1890 if (NParameters && Parameter < NParameters - 1) {
1891 if (M->Parameters[Parameter + 1].second.empty())
1892 return TokError("macro argument '" +
1893 Twine(M->Parameters[Parameter + 1].first) +
1894 "' is missing");
1895 else
1896 continue;
1897 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001898 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001899 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001900
1901 if (Lexer.is(AsmToken::Comma))
1902 Lex();
1903 }
1904 return TokError("Too many arguments");
1905}
1906
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001907const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1908 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1909 return (I == MacroMap.end()) ? NULL : I->getValue();
1910}
1911
1912void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1913 MacroMap[Name] = new MCAsmMacro(Macro);
1914}
1915
1916void AsmParser::UndefineMacro(StringRef Name) {
1917 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1918 if (I != MacroMap.end()) {
1919 delete I->getValue();
1920 MacroMap.erase(I);
1921 }
1922}
1923
1924bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001925 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1926 // this, although we should protect against infinite loops.
1927 if (ActiveMacros.size() == 20)
1928 return TokError("macros cannot be nested more than 20 levels deep");
1929
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001930 MCAsmMacroArguments A;
Rafael Espindola8a403d32012-08-08 14:51:03 +00001931 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001932 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001933
Jim Grosbach97146442012-07-30 22:44:17 +00001934 // Remove any trailing empty arguments. Do this after-the-fact as we have
1935 // to keep empty arguments in the middle of the list or positionality
1936 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001937 while (!A.empty() && A.back().empty())
1938 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001939
Rafael Espindola65366442011-06-05 02:43:45 +00001940 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1941 // to hold the macro body with substitutions.
1942 SmallString<256> Buf;
1943 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001944 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001945
Rafael Espindola8a403d32012-08-08 14:51:03 +00001946 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001947 return true;
1948
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001949 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola761cb062012-06-03 23:57:14 +00001950 // instantiation.
1951 OS << ".endmacro\n";
1952
Rafael Espindola65366442011-06-05 02:43:45 +00001953 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001954 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001955
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001956 // Create the macro instantiation object and add to the current macro
1957 // instantiation stack.
1958 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001959 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001960 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001961 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001962 ActiveMacros.push_back(MI);
1963
1964 // Jump to the macro instantiation and prime the lexer.
1965 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1966 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1967 Lex();
1968
1969 return false;
1970}
1971
1972void AsmParser::HandleMacroExit() {
1973 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001974 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001975 Lex();
1976
1977 // Pop the instantiation entry.
1978 delete ActiveMacros.back();
1979 ActiveMacros.pop_back();
1980}
1981
Rafael Espindolae71cc862012-01-28 05:57:00 +00001982static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001983 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001984 case MCExpr::Binary: {
1985 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1986 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001987 break;
1988 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001989 case MCExpr::Target:
1990 case MCExpr::Constant:
1991 return false;
1992 case MCExpr::SymbolRef: {
1993 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001994 if (S.isVariable())
1995 return IsUsedIn(Sym, S.getVariableValue());
1996 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001997 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001998 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001999 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002000 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00002001
2002 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002003}
2004
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002005bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
2006 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002007 // FIXME: Use better location, we should use proper tokens.
2008 SMLoc EqualLoc = Lexer.getLoc();
2009
Daniel Dunbar821e3332009-08-31 08:09:28 +00002010 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002011 if (parseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002012 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002013
Rafael Espindolae71cc862012-01-28 05:57:00 +00002014 // Note: we don't count b as used in "a = b". This is to allow
2015 // a = b
2016 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002017
Daniel Dunbar3f872332009-07-28 16:08:33 +00002018 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002019 return TokError("unexpected token in assignment");
2020
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00002021 // Error on assignment to '.'.
2022 if (Name == ".") {
2023 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2024 "(use '.space' or '.org').)"));
2025 }
2026
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002027 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00002028 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002029
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002030 // Validate that the LHS is allowed to be a variable (either it has not been
2031 // used as a symbol, or it is an absolute symbol).
2032 MCSymbol *Sym = getContext().LookupSymbol(Name);
2033 if (Sym) {
2034 // Diagnose assignment to a label.
2035 //
2036 // FIXME: Diagnostics. Note the location of the definition as a label.
2037 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00002038 if (IsUsedIn(Sym, Value))
2039 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2040 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00002041 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00002042 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2043 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00002044 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002045 return Error(EqualLoc, "redefinition of '" + Name + "'");
2046 else if (!Sym->isVariable())
2047 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00002048 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002049 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2050 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002051
2052 // Don't count these checks as uses.
2053 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002054 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002055 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002056
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002057 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002058
2059 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00002060 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002061 if (NoDeadStrip)
2062 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2063
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002064
2065 return false;
2066}
2067
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002068/// parseIdentifier:
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002069/// ::= identifier
2070/// ::= string
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002071bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00002072 // The assembler has relaxed rules for accepting identifiers, in particular we
2073 // allow things like '.globl $foo', which would normally be separate
2074 // tokens. At this level, we have already lexed so we cannot (currently)
2075 // handle this as a context dependent token, instead we detect adjacent tokens
2076 // and return the combined identifier.
2077 if (Lexer.is(AsmToken::Dollar)) {
2078 SMLoc DollarLoc = getLexer().getLoc();
2079
2080 // Consume the dollar sign, and check for a following identifier.
2081 Lex();
2082 if (Lexer.isNot(AsmToken::Identifier))
2083 return true;
2084
2085 // We have a '$' followed by an identifier, make sure they are adjacent.
2086 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2087 return true;
2088
2089 // Construct the joined identifier and consume the token.
2090 Res = StringRef(DollarLoc.getPointer(),
2091 getTok().getIdentifier().size() + 1);
2092 Lex();
2093 return false;
2094 }
2095
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002096 if (Lexer.isNot(AsmToken::Identifier) &&
2097 Lexer.isNot(AsmToken::String))
2098 return true;
2099
Sean Callanan18b83232010-01-19 21:44:56 +00002100 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002101
Sean Callanan79ed1a82010-01-19 20:22:31 +00002102 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002103
2104 return false;
2105}
2106
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002107/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002108/// ::= .equ identifier ',' expression
2109/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002110/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002111bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002112 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002113
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002114 if (parseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002115 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002116
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002117 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002118 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002119 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002120
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002121 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002122}
2123
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002124bool AsmParser::parseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002125 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002126
2127 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002128 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002129 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2130 if (Str[i] != '\\') {
2131 Data += Str[i];
2132 continue;
2133 }
2134
2135 // Recognize escaped characters. Note that this escape semantics currently
2136 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2137 ++i;
2138 if (i == e)
2139 return TokError("unexpected backslash at end of string");
2140
2141 // Recognize octal sequences.
2142 if ((unsigned) (Str[i] - '0') <= 7) {
2143 // Consume up to three octal characters.
2144 unsigned Value = Str[i] - '0';
2145
2146 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2147 ++i;
2148 Value = Value * 8 + (Str[i] - '0');
2149
2150 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2151 ++i;
2152 Value = Value * 8 + (Str[i] - '0');
2153 }
2154 }
2155
2156 if (Value > 255)
2157 return TokError("invalid octal escape sequence (out of range)");
2158
2159 Data += (unsigned char) Value;
2160 continue;
2161 }
2162
2163 // Otherwise recognize individual escapes.
2164 switch (Str[i]) {
2165 default:
2166 // Just reject invalid escape sequences for now.
2167 return TokError("invalid escape sequence (unrecognized character)");
2168
2169 case 'b': Data += '\b'; break;
2170 case 'f': Data += '\f'; break;
2171 case 'n': Data += '\n'; break;
2172 case 'r': Data += '\r'; break;
2173 case 't': Data += '\t'; break;
2174 case '"': Data += '"'; break;
2175 case '\\': Data += '\\'; break;
2176 }
2177 }
2178
2179 return false;
2180}
2181
Daniel Dunbara0d14262009-06-24 23:30:00 +00002182/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002183/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2184bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002185 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002186 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002187
Daniel Dunbara0d14262009-06-24 23:30:00 +00002188 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002189 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002190 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002191
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002192 std::string Data;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002193 if (parseEscapedString(Data))
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002194 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002195
2196 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002197 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002198 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2199
Sean Callanan79ed1a82010-01-19 20:22:31 +00002200 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002201
2202 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002203 break;
2204
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002205 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002206 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002207 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002208 }
2209 }
2210
Sean Callanan79ed1a82010-01-19 20:22:31 +00002211 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002212 return false;
2213}
2214
2215/// ParseDirectiveValue
2216/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2217bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002218 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002219 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002220
Daniel Dunbara0d14262009-06-24 23:30:00 +00002221 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002222 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002223 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002224 if (parseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002225 return true;
2226
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002227 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002228 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2229 assert(Size <= 8 && "Invalid size");
2230 uint64_t IntValue = MCE->getValue();
2231 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2232 return Error(ExprLoc, "literal value out of range for directive");
2233 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2234 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002235 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002236
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002237 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002238 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002239
Daniel Dunbara0d14262009-06-24 23:30:00 +00002240 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002241 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002242 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002243 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002244 }
2245 }
2246
Sean Callanan79ed1a82010-01-19 20:22:31 +00002247 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002248 return false;
2249}
2250
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002251/// ParseDirectiveRealValue
2252/// ::= (.single | .double) [ expression (, expression)* ]
2253bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2254 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002255 checkForValidSection();
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002256
2257 for (;;) {
2258 // We don't truly support arithmetic on floating point expressions, so we
2259 // have to manually parse unary prefixes.
2260 bool IsNeg = false;
2261 if (getLexer().is(AsmToken::Minus)) {
2262 Lex();
2263 IsNeg = true;
2264 } else if (getLexer().is(AsmToken::Plus))
2265 Lex();
2266
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002267 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002268 getLexer().isNot(AsmToken::Real) &&
2269 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002270 return TokError("unexpected token in directive");
2271
2272 // Convert to an APFloat.
2273 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002274 StringRef IDVal = getTok().getString();
2275 if (getLexer().is(AsmToken::Identifier)) {
2276 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2277 Value = APFloat::getInf(Semantics);
2278 else if (!IDVal.compare_lower("nan"))
2279 Value = APFloat::getNaN(Semantics, false, ~0);
2280 else
2281 return TokError("invalid floating point literal");
2282 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002283 APFloat::opInvalidOp)
2284 return TokError("invalid floating point literal");
2285 if (IsNeg)
2286 Value.changeSign();
2287
2288 // Consume the numeric token.
2289 Lex();
2290
2291 // Emit the value as an integer.
2292 APInt AsInt = Value.bitcastToAPInt();
2293 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2294 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2295
2296 if (getLexer().is(AsmToken::EndOfStatement))
2297 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002298
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002299 if (getLexer().isNot(AsmToken::Comma))
2300 return TokError("unexpected token in directive");
2301 Lex();
2302 }
2303 }
2304
2305 Lex();
2306 return false;
2307}
2308
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002309/// ParseDirectiveZero
2310/// ::= .zero expression
2311bool AsmParser::ParseDirectiveZero() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002312 checkForValidSection();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002313
2314 int64_t NumBytes;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002315 if (parseAbsoluteExpression(NumBytes))
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002316 return true;
2317
Rafael Espindolae452b172010-10-05 19:42:57 +00002318 int64_t Val = 0;
2319 if (getLexer().is(AsmToken::Comma)) {
2320 Lex();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002321 if (parseAbsoluteExpression(Val))
Rafael Espindolae452b172010-10-05 19:42:57 +00002322 return true;
2323 }
2324
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002325 if (getLexer().isNot(AsmToken::EndOfStatement))
2326 return TokError("unexpected token in '.zero' directive");
2327
2328 Lex();
2329
Rafael Espindolae452b172010-10-05 19:42:57 +00002330 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002331
2332 return false;
2333}
2334
Daniel Dunbara0d14262009-06-24 23:30:00 +00002335/// ParseDirectiveFill
2336/// ::= .fill expression , expression , expression
2337bool AsmParser::ParseDirectiveFill() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002338 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002339
Daniel Dunbara0d14262009-06-24 23:30:00 +00002340 int64_t NumValues;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002341 if (parseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002342 return true;
2343
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002344 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002345 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002346 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002347
Daniel Dunbara0d14262009-06-24 23:30:00 +00002348 int64_t FillSize;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002349 if (parseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002350 return true;
2351
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002352 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002353 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002354 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002355
Daniel Dunbara0d14262009-06-24 23:30:00 +00002356 int64_t FillExpr;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002357 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002358 return true;
2359
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002360 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002361 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002362
Sean Callanan79ed1a82010-01-19 20:22:31 +00002363 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002364
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002365 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2366 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002367
2368 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002369 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002370
2371 return false;
2372}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002373
2374/// ParseDirectiveOrg
2375/// ::= .org expression [ , expression ]
2376bool AsmParser::ParseDirectiveOrg() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002377 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002378
Daniel Dunbar821e3332009-08-31 08:09:28 +00002379 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002380 SMLoc Loc = getTok().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002381 if (parseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002382 return true;
2383
2384 // Parse optional fill expression.
2385 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002386 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2387 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002388 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002389 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002390
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002391 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002392 return true;
2393
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002394 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002395 return TokError("unexpected token in '.org' directive");
2396 }
2397
Sean Callanan79ed1a82010-01-19 20:22:31 +00002398 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002399
Jim Grosbachebd4c052012-01-27 00:37:08 +00002400 // Only limited forms of relocatable expressions are accepted here, it
2401 // has to be relative to the current section. The streamer will return
2402 // 'true' if the expression wasn't evaluatable.
2403 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2404 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002405
2406 return false;
2407}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002408
2409/// ParseDirectiveAlign
2410/// ::= {.align, ...} expression [ , expression [ , expression ]]
2411bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002412 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002413
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002414 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002415 int64_t Alignment;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002416 if (parseAbsoluteExpression(Alignment))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002417 return true;
2418
2419 SMLoc MaxBytesLoc;
2420 bool HasFillExpr = false;
2421 int64_t FillExpr = 0;
2422 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002423 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2424 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002425 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002426 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002427
2428 // The fill expression can be omitted while specifying a maximum number of
2429 // alignment bytes, e.g:
2430 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002431 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002432 HasFillExpr = true;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002433 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002434 return true;
2435 }
2436
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002437 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2438 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002439 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002440 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002441
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002442 MaxBytesLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002443 if (parseAbsoluteExpression(MaxBytesToFill))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002444 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002445
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002446 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002447 return TokError("unexpected token in directive");
2448 }
2449 }
2450
Sean Callanan79ed1a82010-01-19 20:22:31 +00002451 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002452
Daniel Dunbar648ac512010-05-17 21:54:30 +00002453 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002454 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002455
2456 // Compute alignment in bytes.
2457 if (IsPow2) {
2458 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002459 if (Alignment >= 32) {
2460 Error(AlignmentLoc, "invalid alignment value");
2461 Alignment = 31;
2462 }
2463
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002464 Alignment = 1ULL << Alignment;
Benjamin Kramer8a89cf22013-02-16 15:00:16 +00002465 } else {
2466 // Reject alignments that aren't a power of two, for gas compatibility.
2467 if (!isPowerOf2_64(Alignment))
2468 Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002469 }
2470
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002471 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002472 if (MaxBytesLoc.isValid()) {
2473 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002474 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2475 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002476 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002477 }
2478
2479 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002480 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2481 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002482 MaxBytesToFill = 0;
2483 }
2484 }
2485
Daniel Dunbar648ac512010-05-17 21:54:30 +00002486 // Check whether we should use optimal code alignment for this .align
2487 // directive.
Peter Collingbournedf39be62013-04-17 21:18:16 +00002488 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002489 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2490 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002491 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002492 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002493 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002494 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2495 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002496 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002497
2498 return false;
2499}
2500
Eli Bendersky6ee13082013-01-15 22:59:42 +00002501/// ParseDirectiveFile
2502/// ::= .file [number] filename
2503/// ::= .file number directory filename
2504bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2505 // FIXME: I'm not sure what this is.
2506 int64_t FileNumber = -1;
2507 SMLoc FileNumberLoc = getLexer().getLoc();
2508 if (getLexer().is(AsmToken::Integer)) {
2509 FileNumber = getTok().getIntVal();
2510 Lex();
2511
2512 if (FileNumber < 1)
2513 return TokError("file number less than one");
2514 }
2515
2516 if (getLexer().isNot(AsmToken::String))
2517 return TokError("unexpected token in '.file' directive");
2518
2519 // Usually the directory and filename together, otherwise just the directory.
2520 StringRef Path = getTok().getString();
2521 Path = Path.substr(1, Path.size()-2);
2522 Lex();
2523
2524 StringRef Directory;
2525 StringRef Filename;
2526 if (getLexer().is(AsmToken::String)) {
2527 if (FileNumber == -1)
2528 return TokError("explicit path specified, but no file number");
2529 Filename = getTok().getString();
2530 Filename = Filename.substr(1, Filename.size()-2);
2531 Directory = Path;
2532 Lex();
2533 } else {
2534 Filename = Path;
2535 }
2536
2537 if (getLexer().isNot(AsmToken::EndOfStatement))
2538 return TokError("unexpected token in '.file' directive");
2539
2540 if (FileNumber == -1)
2541 getStreamer().EmitFileDirective(Filename);
2542 else {
2543 if (getContext().getGenDwarfForAssembly() == true)
2544 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2545 "used to generate dwarf debug info for assembly code");
2546
2547 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2548 Error(FileNumberLoc, "file number already allocated");
2549 }
2550
2551 return false;
2552}
2553
2554/// ParseDirectiveLine
2555/// ::= .line [number]
2556bool AsmParser::ParseDirectiveLine() {
2557 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2558 if (getLexer().isNot(AsmToken::Integer))
2559 return TokError("unexpected token in '.line' directive");
2560
2561 int64_t LineNumber = getTok().getIntVal();
2562 (void) LineNumber;
2563 Lex();
2564
2565 // FIXME: Do something with the .line.
2566 }
2567
2568 if (getLexer().isNot(AsmToken::EndOfStatement))
2569 return TokError("unexpected token in '.line' directive");
2570
2571 return false;
2572}
2573
2574/// ParseDirectiveLoc
2575/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2576/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2577/// The first number is a file number, must have been previously assigned with
2578/// a .file directive, the second number is the line number and optionally the
2579/// third number is a column position (zero if not specified). The remaining
2580/// optional items are .loc sub-directives.
2581bool AsmParser::ParseDirectiveLoc() {
2582 if (getLexer().isNot(AsmToken::Integer))
2583 return TokError("unexpected token in '.loc' directive");
2584 int64_t FileNumber = getTok().getIntVal();
2585 if (FileNumber < 1)
2586 return TokError("file number less than one in '.loc' directive");
2587 if (!getContext().isValidDwarfFileNumber(FileNumber))
2588 return TokError("unassigned file number in '.loc' directive");
2589 Lex();
2590
2591 int64_t LineNumber = 0;
2592 if (getLexer().is(AsmToken::Integer)) {
2593 LineNumber = getTok().getIntVal();
2594 if (LineNumber < 1)
2595 return TokError("line number less than one in '.loc' directive");
2596 Lex();
2597 }
2598
2599 int64_t ColumnPos = 0;
2600 if (getLexer().is(AsmToken::Integer)) {
2601 ColumnPos = getTok().getIntVal();
2602 if (ColumnPos < 0)
2603 return TokError("column position less than zero in '.loc' directive");
2604 Lex();
2605 }
2606
2607 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2608 unsigned Isa = 0;
2609 int64_t Discriminator = 0;
2610 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2611 for (;;) {
2612 if (getLexer().is(AsmToken::EndOfStatement))
2613 break;
2614
2615 StringRef Name;
2616 SMLoc Loc = getTok().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002617 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002618 return TokError("unexpected token in '.loc' directive");
2619
2620 if (Name == "basic_block")
2621 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2622 else if (Name == "prologue_end")
2623 Flags |= DWARF2_FLAG_PROLOGUE_END;
2624 else if (Name == "epilogue_begin")
2625 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2626 else if (Name == "is_stmt") {
2627 Loc = getTok().getLoc();
2628 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002629 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002630 return true;
2631 // The expression must be the constant 0 or 1.
2632 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2633 int Value = MCE->getValue();
2634 if (Value == 0)
2635 Flags &= ~DWARF2_FLAG_IS_STMT;
2636 else if (Value == 1)
2637 Flags |= DWARF2_FLAG_IS_STMT;
2638 else
2639 return Error(Loc, "is_stmt value not 0 or 1");
2640 }
2641 else {
2642 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2643 }
2644 }
2645 else if (Name == "isa") {
2646 Loc = getTok().getLoc();
2647 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002648 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002649 return true;
2650 // The expression must be a constant greater or equal to 0.
2651 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2652 int Value = MCE->getValue();
2653 if (Value < 0)
2654 return Error(Loc, "isa number less than zero");
2655 Isa = Value;
2656 }
2657 else {
2658 return Error(Loc, "isa number not a constant value");
2659 }
2660 }
2661 else if (Name == "discriminator") {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002662 if (parseAbsoluteExpression(Discriminator))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002663 return true;
2664 }
2665 else {
2666 return Error(Loc, "unknown sub-directive in '.loc' directive");
2667 }
2668
2669 if (getLexer().is(AsmToken::EndOfStatement))
2670 break;
2671 }
2672 }
2673
2674 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2675 Isa, Discriminator, StringRef());
2676
2677 return false;
2678}
2679
2680/// ParseDirectiveStabs
2681/// ::= .stabs string, number, number, number
2682bool AsmParser::ParseDirectiveStabs() {
2683 return TokError("unsupported directive '.stabs'");
2684}
2685
2686/// ParseDirectiveCFISections
2687/// ::= .cfi_sections section [, section]
2688bool AsmParser::ParseDirectiveCFISections() {
2689 StringRef Name;
2690 bool EH = false;
2691 bool Debug = false;
2692
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002693 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002694 return TokError("Expected an identifier");
2695
2696 if (Name == ".eh_frame")
2697 EH = true;
2698 else if (Name == ".debug_frame")
2699 Debug = true;
2700
2701 if (getLexer().is(AsmToken::Comma)) {
2702 Lex();
2703
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002704 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002705 return TokError("Expected an identifier");
2706
2707 if (Name == ".eh_frame")
2708 EH = true;
2709 else if (Name == ".debug_frame")
2710 Debug = true;
2711 }
2712
2713 getStreamer().EmitCFISections(EH, Debug);
2714 return false;
2715}
2716
2717/// ParseDirectiveCFIStartProc
2718/// ::= .cfi_startproc
2719bool AsmParser::ParseDirectiveCFIStartProc() {
2720 getStreamer().EmitCFIStartProc();
2721 return false;
2722}
2723
2724/// ParseDirectiveCFIEndProc
2725/// ::= .cfi_endproc
2726bool AsmParser::ParseDirectiveCFIEndProc() {
2727 getStreamer().EmitCFIEndProc();
2728 return false;
2729}
2730
2731/// ParseRegisterOrRegisterNumber - parse register name or number.
2732bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2733 SMLoc DirectiveLoc) {
2734 unsigned RegNo;
2735
2736 if (getLexer().isNot(AsmToken::Integer)) {
2737 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2738 return true;
2739 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2740 } else
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002741 return parseAbsoluteExpression(Register);
Eli Bendersky6ee13082013-01-15 22:59:42 +00002742
2743 return false;
2744}
2745
2746/// ParseDirectiveCFIDefCfa
2747/// ::= .cfi_def_cfa register, offset
2748bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2749 int64_t Register = 0;
2750 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2751 return true;
2752
2753 if (getLexer().isNot(AsmToken::Comma))
2754 return TokError("unexpected token in directive");
2755 Lex();
2756
2757 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002758 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002759 return true;
2760
2761 getStreamer().EmitCFIDefCfa(Register, Offset);
2762 return false;
2763}
2764
2765/// ParseDirectiveCFIDefCfaOffset
2766/// ::= .cfi_def_cfa_offset offset
2767bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
2768 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002769 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002770 return true;
2771
2772 getStreamer().EmitCFIDefCfaOffset(Offset);
2773 return false;
2774}
2775
2776/// ParseDirectiveCFIRegister
2777/// ::= .cfi_register register, register
2778bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2779 int64_t Register1 = 0;
2780 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2781 return true;
2782
2783 if (getLexer().isNot(AsmToken::Comma))
2784 return TokError("unexpected token in directive");
2785 Lex();
2786
2787 int64_t Register2 = 0;
2788 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2789 return true;
2790
2791 getStreamer().EmitCFIRegister(Register1, Register2);
2792 return false;
2793}
2794
2795/// ParseDirectiveCFIAdjustCfaOffset
2796/// ::= .cfi_adjust_cfa_offset adjustment
2797bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
2798 int64_t Adjustment = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002799 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002800 return true;
2801
2802 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2803 return false;
2804}
2805
2806/// ParseDirectiveCFIDefCfaRegister
2807/// ::= .cfi_def_cfa_register register
2808bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2809 int64_t Register = 0;
2810 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2811 return true;
2812
2813 getStreamer().EmitCFIDefCfaRegister(Register);
2814 return false;
2815}
2816
2817/// ParseDirectiveCFIOffset
2818/// ::= .cfi_offset register, offset
2819bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2820 int64_t Register = 0;
2821 int64_t Offset = 0;
2822
2823 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2824 return true;
2825
2826 if (getLexer().isNot(AsmToken::Comma))
2827 return TokError("unexpected token in directive");
2828 Lex();
2829
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002830 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002831 return true;
2832
2833 getStreamer().EmitCFIOffset(Register, Offset);
2834 return false;
2835}
2836
2837/// ParseDirectiveCFIRelOffset
2838/// ::= .cfi_rel_offset register, offset
2839bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2840 int64_t Register = 0;
2841
2842 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2843 return true;
2844
2845 if (getLexer().isNot(AsmToken::Comma))
2846 return TokError("unexpected token in directive");
2847 Lex();
2848
2849 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002850 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002851 return true;
2852
2853 getStreamer().EmitCFIRelOffset(Register, Offset);
2854 return false;
2855}
2856
2857static bool isValidEncoding(int64_t Encoding) {
2858 if (Encoding & ~0xff)
2859 return false;
2860
2861 if (Encoding == dwarf::DW_EH_PE_omit)
2862 return true;
2863
2864 const unsigned Format = Encoding & 0xf;
2865 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2866 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2867 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2868 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2869 return false;
2870
2871 const unsigned Application = Encoding & 0x70;
2872 if (Application != dwarf::DW_EH_PE_absptr &&
2873 Application != dwarf::DW_EH_PE_pcrel)
2874 return false;
2875
2876 return true;
2877}
2878
2879/// ParseDirectiveCFIPersonalityOrLsda
2880/// IsPersonality true for cfi_personality, false for cfi_lsda
2881/// ::= .cfi_personality encoding, [symbol_name]
2882/// ::= .cfi_lsda encoding, [symbol_name]
2883bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2884 int64_t Encoding = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002885 if (parseAbsoluteExpression(Encoding))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002886 return true;
2887 if (Encoding == dwarf::DW_EH_PE_omit)
2888 return false;
2889
2890 if (!isValidEncoding(Encoding))
2891 return TokError("unsupported encoding.");
2892
2893 if (getLexer().isNot(AsmToken::Comma))
2894 return TokError("unexpected token in directive");
2895 Lex();
2896
2897 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002898 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002899 return TokError("expected identifier in directive");
2900
2901 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2902
2903 if (IsPersonality)
2904 getStreamer().EmitCFIPersonality(Sym, Encoding);
2905 else
2906 getStreamer().EmitCFILsda(Sym, Encoding);
2907 return false;
2908}
2909
2910/// ParseDirectiveCFIRememberState
2911/// ::= .cfi_remember_state
2912bool AsmParser::ParseDirectiveCFIRememberState() {
2913 getStreamer().EmitCFIRememberState();
2914 return false;
2915}
2916
2917/// ParseDirectiveCFIRestoreState
2918/// ::= .cfi_remember_state
2919bool AsmParser::ParseDirectiveCFIRestoreState() {
2920 getStreamer().EmitCFIRestoreState();
2921 return false;
2922}
2923
2924/// ParseDirectiveCFISameValue
2925/// ::= .cfi_same_value register
2926bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2927 int64_t Register = 0;
2928
2929 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2930 return true;
2931
2932 getStreamer().EmitCFISameValue(Register);
2933 return false;
2934}
2935
2936/// ParseDirectiveCFIRestore
2937/// ::= .cfi_restore register
2938bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2939 int64_t Register = 0;
2940 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2941 return true;
2942
2943 getStreamer().EmitCFIRestore(Register);
2944 return false;
2945}
2946
2947/// ParseDirectiveCFIEscape
2948/// ::= .cfi_escape expression[,...]
2949bool AsmParser::ParseDirectiveCFIEscape() {
2950 std::string Values;
2951 int64_t CurrValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002952 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002953 return true;
2954
2955 Values.push_back((uint8_t)CurrValue);
2956
2957 while (getLexer().is(AsmToken::Comma)) {
2958 Lex();
2959
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002960 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002961 return true;
2962
2963 Values.push_back((uint8_t)CurrValue);
2964 }
2965
2966 getStreamer().EmitCFIEscape(Values);
2967 return false;
2968}
2969
2970/// ParseDirectiveCFISignalFrame
2971/// ::= .cfi_signal_frame
2972bool AsmParser::ParseDirectiveCFISignalFrame() {
2973 if (getLexer().isNot(AsmToken::EndOfStatement))
2974 return Error(getLexer().getLoc(),
2975 "unexpected token in '.cfi_signal_frame'");
2976
2977 getStreamer().EmitCFISignalFrame();
2978 return false;
2979}
2980
2981/// ParseDirectiveCFIUndefined
2982/// ::= .cfi_undefined register
2983bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
2984 int64_t Register = 0;
2985
2986 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2987 return true;
2988
2989 getStreamer().EmitCFIUndefined(Register);
2990 return false;
2991}
2992
2993/// ParseDirectiveMacrosOnOff
2994/// ::= .macros_on
2995/// ::= .macros_off
2996bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
2997 if (getLexer().isNot(AsmToken::EndOfStatement))
2998 return Error(getLexer().getLoc(),
2999 "unexpected token in '" + Directive + "' directive");
3000
3001 SetMacrosEnabled(Directive == ".macros_on");
3002 return false;
3003}
3004
3005/// ParseDirectiveMacro
3006/// ::= .macro name [parameters]
3007bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
3008 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003009 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003010 return TokError("expected identifier in '.macro' directive");
3011
3012 MCAsmMacroParameters Parameters;
3013 // Argument delimiter is initially unknown. It will be set by
3014 // ParseMacroArgument()
3015 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3016 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3017 for (;;) {
3018 MCAsmMacroParameter Parameter;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003019 if (parseIdentifier(Parameter.first))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003020 return TokError("expected identifier in '.macro' directive");
3021
3022 if (getLexer().is(AsmToken::Equal)) {
3023 Lex();
3024 if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3025 return true;
3026 }
3027
3028 Parameters.push_back(Parameter);
3029
3030 if (getLexer().is(AsmToken::Comma))
3031 Lex();
3032 else if (getLexer().is(AsmToken::EndOfStatement))
3033 break;
3034 }
3035 }
3036
3037 // Eat the end of statement.
3038 Lex();
3039
3040 AsmToken EndToken, StartToken = getTok();
3041
3042 // Lex the macro definition.
3043 for (;;) {
3044 // Check whether we have reached the end of the file.
3045 if (getLexer().is(AsmToken::Eof))
3046 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3047
3048 // Otherwise, check whether we have reach the .endmacro.
3049 if (getLexer().is(AsmToken::Identifier) &&
3050 (getTok().getIdentifier() == ".endm" ||
3051 getTok().getIdentifier() == ".endmacro")) {
3052 EndToken = getTok();
3053 Lex();
3054 if (getLexer().isNot(AsmToken::EndOfStatement))
3055 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3056 "' directive");
3057 break;
3058 }
3059
3060 // Otherwise, scan til the end of the statement.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003061 eatToEndOfStatement();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003062 }
3063
3064 if (LookupMacro(Name)) {
3065 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3066 }
3067
3068 const char *BodyStart = StartToken.getLoc().getPointer();
3069 const char *BodyEnd = EndToken.getLoc().getPointer();
3070 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Kevin Enderby221514e2013-01-22 21:44:53 +00003071 CheckForBadMacro(DirectiveLoc, Name, Body, Parameters);
Eli Bendersky6ee13082013-01-15 22:59:42 +00003072 DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3073 return false;
3074}
3075
Kevin Enderby221514e2013-01-22 21:44:53 +00003076/// CheckForBadMacro
3077///
3078/// With the support added for named parameters there may be code out there that
3079/// is transitioning from positional parameters. In versions of gas that did
3080/// not support named parameters they would be ignored on the macro defintion.
3081/// But to support both styles of parameters this is not possible so if a macro
3082/// defintion has named parameters but does not use them and has what appears
3083/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3084/// warning that the positional parameter found in body which have no effect.
3085/// Hoping the developer will either remove the named parameters from the macro
3086/// definiton so the positional parameters get used if that was what was
3087/// intended or change the macro to use the named parameters. It is possible
3088/// this warning will trigger when the none of the named parameters are used
3089/// and the strings like $1 are infact to simply to be passed trough unchanged.
3090void AsmParser::CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3091 StringRef Body,
3092 MCAsmMacroParameters Parameters) {
3093 // If this macro is not defined with named parameters the warning we are
3094 // checking for here doesn't apply.
3095 unsigned NParameters = Parameters.size();
3096 if (NParameters == 0)
3097 return;
3098
3099 bool NamedParametersFound = false;
3100 bool PositionalParametersFound = false;
3101
3102 // Look at the body of the macro for use of both the named parameters and what
3103 // are likely to be positional parameters. This is what expandMacro() is
3104 // doing when it finds the parameters in the body.
3105 while (!Body.empty()) {
3106 // Scan for the next possible parameter.
3107 std::size_t End = Body.size(), Pos = 0;
3108 for (; Pos != End; ++Pos) {
3109 // Check for a substitution or escape.
3110 // This macro is defined with parameters, look for \foo, \bar, etc.
3111 if (Body[Pos] == '\\' && Pos + 1 != End)
3112 break;
3113
3114 // This macro should have parameters, but look for $0, $1, ..., $n too.
3115 if (Body[Pos] != '$' || Pos + 1 == End)
3116 continue;
3117 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00003118 if (Next == '$' || Next == 'n' ||
3119 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby221514e2013-01-22 21:44:53 +00003120 break;
3121 }
3122
3123 // Check if we reached the end.
3124 if (Pos == End)
3125 break;
3126
3127 if (Body[Pos] == '$') {
3128 switch (Body[Pos+1]) {
3129 // $$ => $
3130 case '$':
3131 break;
3132
3133 // $n => number of arguments
3134 case 'n':
3135 PositionalParametersFound = true;
3136 break;
3137
3138 // $[0-9] => argument
3139 default: {
3140 PositionalParametersFound = true;
3141 break;
3142 }
3143 }
3144 Pos += 2;
3145 } else {
3146 unsigned I = Pos + 1;
3147 while (isIdentifierChar(Body[I]) && I + 1 != End)
3148 ++I;
3149
3150 const char *Begin = Body.data() + Pos +1;
3151 StringRef Argument(Begin, I - (Pos +1));
3152 unsigned Index = 0;
3153 for (; Index < NParameters; ++Index)
3154 if (Parameters[Index].first == Argument)
3155 break;
3156
3157 if (Index == NParameters) {
3158 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
3159 Pos += 3;
3160 else {
3161 Pos = I;
3162 }
3163 } else {
3164 NamedParametersFound = true;
3165 Pos += 1 + Argument.size();
3166 }
3167 }
3168 // Update the scan point.
3169 Body = Body.substr(Pos);
3170 }
3171
3172 if (!NamedParametersFound && PositionalParametersFound)
3173 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3174 "used in macro body, possible positional parameter "
3175 "found in body which will have no effect");
3176}
3177
Eli Bendersky6ee13082013-01-15 22:59:42 +00003178/// ParseDirectiveEndMacro
3179/// ::= .endm
3180/// ::= .endmacro
3181bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
3182 if (getLexer().isNot(AsmToken::EndOfStatement))
3183 return TokError("unexpected token in '" + Directive + "' directive");
3184
3185 // If we are inside a macro instantiation, terminate the current
3186 // instantiation.
3187 if (InsideMacroInstantiation()) {
3188 HandleMacroExit();
3189 return false;
3190 }
3191
3192 // Otherwise, this .endmacro is a stray entry in the file; well formed
3193 // .endmacro directives are handled during the macro definition parsing.
3194 return TokError("unexpected '" + Directive + "' in file, "
3195 "no current macro definition");
3196}
3197
3198/// ParseDirectivePurgeMacro
3199/// ::= .purgem
3200bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3201 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003202 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003203 return TokError("expected identifier in '.purgem' directive");
3204
3205 if (getLexer().isNot(AsmToken::EndOfStatement))
3206 return TokError("unexpected token in '.purgem' directive");
3207
3208 if (!LookupMacro(Name))
3209 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3210
3211 UndefineMacro(Name);
3212 return false;
3213}
Eli Bendersky4766ef42012-12-20 19:05:53 +00003214
3215/// ParseDirectiveBundleAlignMode
3216/// ::= {.bundle_align_mode} expression
3217bool AsmParser::ParseDirectiveBundleAlignMode() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003218 checkForValidSection();
Eli Bendersky4766ef42012-12-20 19:05:53 +00003219
3220 // Expect a single argument: an expression that evaluates to a constant
3221 // in the inclusive range 0-30.
3222 SMLoc ExprLoc = getLexer().getLoc();
3223 int64_t AlignSizePow2;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003224 if (parseAbsoluteExpression(AlignSizePow2))
Eli Bendersky4766ef42012-12-20 19:05:53 +00003225 return true;
3226 else if (getLexer().isNot(AsmToken::EndOfStatement))
3227 return TokError("unexpected token after expression in"
3228 " '.bundle_align_mode' directive");
3229 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3230 return Error(ExprLoc,
3231 "invalid bundle alignment size (expected between 0 and 30)");
3232
3233 Lex();
3234
3235 // Because of AlignSizePow2's verified range we can safely truncate it to
3236 // unsigned.
3237 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3238 return false;
3239}
3240
3241/// ParseDirectiveBundleLock
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003242/// ::= {.bundle_lock} [align_to_end]
Eli Bendersky4766ef42012-12-20 19:05:53 +00003243bool AsmParser::ParseDirectiveBundleLock() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003244 checkForValidSection();
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003245 bool AlignToEnd = false;
Eli Bendersky4766ef42012-12-20 19:05:53 +00003246
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003247 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3248 StringRef Option;
3249 SMLoc Loc = getTok().getLoc();
3250 const char *kInvalidOptionError =
3251 "invalid option for '.bundle_lock' directive";
3252
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003253 if (parseIdentifier(Option))
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003254 return Error(Loc, kInvalidOptionError);
3255
3256 if (Option != "align_to_end")
3257 return Error(Loc, kInvalidOptionError);
3258 else if (getLexer().isNot(AsmToken::EndOfStatement))
3259 return Error(Loc,
3260 "unexpected token after '.bundle_lock' directive option");
3261 AlignToEnd = true;
3262 }
3263
Eli Bendersky4766ef42012-12-20 19:05:53 +00003264 Lex();
3265
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003266 getStreamer().EmitBundleLock(AlignToEnd);
Eli Bendersky4766ef42012-12-20 19:05:53 +00003267 return false;
3268}
3269
3270/// ParseDirectiveBundleLock
3271/// ::= {.bundle_lock}
3272bool AsmParser::ParseDirectiveBundleUnlock() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003273 checkForValidSection();
Eli Bendersky4766ef42012-12-20 19:05:53 +00003274
3275 if (getLexer().isNot(AsmToken::EndOfStatement))
3276 return TokError("unexpected token in '.bundle_unlock' directive");
3277 Lex();
3278
3279 getStreamer().EmitBundleUnlock();
3280 return false;
3281}
3282
Eli Bendersky6ee13082013-01-15 22:59:42 +00003283/// ParseDirectiveSpace
3284/// ::= (.skip | .space) expression [ , expression ]
3285bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003286 checkForValidSection();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003287
3288 int64_t NumBytes;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003289 if (parseAbsoluteExpression(NumBytes))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003290 return true;
3291
3292 int64_t FillExpr = 0;
3293 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3294 if (getLexer().isNot(AsmToken::Comma))
3295 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3296 Lex();
3297
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003298 if (parseAbsoluteExpression(FillExpr))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003299 return true;
3300
3301 if (getLexer().isNot(AsmToken::EndOfStatement))
3302 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3303 }
3304
3305 Lex();
3306
3307 if (NumBytes <= 0)
3308 return TokError("invalid number of bytes in '" +
3309 Twine(IDVal) + "' directive");
3310
3311 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3312 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
3313
3314 return false;
3315}
3316
3317/// ParseDirectiveLEB128
3318/// ::= (.sleb128 | .uleb128) expression
3319bool AsmParser::ParseDirectiveLEB128(bool Signed) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003320 checkForValidSection();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003321 const MCExpr *Value;
3322
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003323 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003324 return true;
3325
3326 if (getLexer().isNot(AsmToken::EndOfStatement))
3327 return TokError("unexpected token in directive");
3328
3329 if (Signed)
3330 getStreamer().EmitSLEB128Value(Value);
3331 else
3332 getStreamer().EmitULEB128Value(Value);
3333
3334 return false;
3335}
3336
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003337/// ParseDirectiveSymbolAttribute
3338/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00003339bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003340 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003341 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003342 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00003343 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003344
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003345 if (parseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00003346 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003347
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003348 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003349
Jim Grosbach10ec6502011-09-15 17:56:49 +00003350 // Assembler local symbols don't make any sense here. Complain loudly.
3351 if (Sym->isTemporary())
3352 return Error(Loc, "non-local symbol required in directive");
3353
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003354 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003355
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003356 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003357 break;
3358
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003359 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003360 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003361 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003362 }
3363 }
3364
Sean Callanan79ed1a82010-01-19 20:22:31 +00003365 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00003366 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003367}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003368
3369/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00003370/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3371bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003372 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00003373
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003374 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003375 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003376 if (parseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003377 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003378
Daniel Dunbar76c4d762009-07-31 21:55:09 +00003379 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003380 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003381
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003382 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003383 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003384 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003385
3386 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003387 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003388 if (parseAbsoluteExpression(Size))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003389 return true;
3390
3391 int64_t Pow2Alignment = 0;
3392 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003393 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00003394 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003395 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003396 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003397 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003398
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003399 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3400 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00003401 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3402
Chris Lattner258281d2010-01-19 06:22:22 +00003403 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003404 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3405 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00003406 if (!isPowerOf2_64(Pow2Alignment))
3407 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3408 Pow2Alignment = Log2_64(Pow2Alignment);
3409 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003410 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003411
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003412 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00003413 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003414
Sean Callanan79ed1a82010-01-19 20:22:31 +00003415 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003416
Chris Lattner1fc3d752009-07-09 17:25:12 +00003417 // NOTE: a size of zero for a .comm should create a undefined symbol
3418 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003419 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003420 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3421 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003422
Eric Christopherc260a3e2010-05-14 01:38:54 +00003423 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003424 // may internally end up wanting an alignment in bytes.
3425 // FIXME: Diagnose overflow.
3426 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003427 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3428 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003429
Daniel Dunbar8906ff12009-08-22 07:22:36 +00003430 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003431 return Error(IDLoc, "invalid symbol redefinition");
3432
Chris Lattner1fc3d752009-07-09 17:25:12 +00003433 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003434 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00003435 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003436 return false;
3437 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003438
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003439 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003440 return false;
3441}
Chris Lattner9be3fee2009-07-10 22:20:30 +00003442
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003443/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003444/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003445bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003446 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003447 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003448
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003449 StringRef Str = parseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003450 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003451 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003452
Sean Callanan79ed1a82010-01-19 20:22:31 +00003453 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003454
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003455 if (Str.empty())
3456 Error(Loc, ".abort detected. Assembly stopping.");
3457 else
3458 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003459 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003460
3461 return false;
3462}
Kevin Enderby71148242009-07-14 21:35:03 +00003463
Kevin Enderby1f049b22009-07-14 23:21:55 +00003464/// ParseDirectiveInclude
3465/// ::= .include "filename"
3466bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003467 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003468 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003469
Sean Callanan18b83232010-01-19 21:44:56 +00003470 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003471 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00003472 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00003473
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003474 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003475 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003476
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003477 // Strip the quotes.
3478 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003479
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003480 // Attempt to switch the lexer to the included file before consuming the end
3481 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00003482 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00003483 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003484 return true;
3485 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00003486
3487 return false;
3488}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00003489
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003490/// ParseDirectiveIncbin
3491/// ::= .incbin "filename"
3492bool AsmParser::ParseDirectiveIncbin() {
3493 if (getLexer().isNot(AsmToken::String))
3494 return TokError("expected string in '.incbin' directive");
3495
3496 std::string Filename = getTok().getString();
3497 SMLoc IncbinLoc = getLexer().getLoc();
3498 Lex();
3499
3500 if (getLexer().isNot(AsmToken::EndOfStatement))
3501 return TokError("unexpected token in '.incbin' directive");
3502
3503 // Strip the quotes.
3504 Filename = Filename.substr(1, Filename.size()-2);
3505
3506 // Attempt to process the included file.
3507 if (ProcessIncbinFile(Filename)) {
3508 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3509 return true;
3510 }
3511
3512 return false;
3513}
3514
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003515/// ParseDirectiveIf
3516/// ::= .if expression
3517bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003518 TheCondStack.push_back(TheCondState);
3519 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00003520 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003521 eatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00003522 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003523 int64_t ExprValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003524 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003525 return true;
3526
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003527 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003528 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003529
Sean Callanan79ed1a82010-01-19 20:22:31 +00003530 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003531
3532 TheCondState.CondMet = ExprValue;
3533 TheCondState.Ignore = !TheCondState.CondMet;
3534 }
3535
3536 return false;
3537}
3538
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003539/// ParseDirectiveIfb
3540/// ::= .ifb string
3541bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3542 TheCondStack.push_back(TheCondState);
3543 TheCondState.TheCond = AsmCond::IfCond;
3544
Benjamin Kramer29739e72012-05-12 16:52:21 +00003545 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003546 eatToEndOfStatement();
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003547 } else {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003548 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003549
3550 if (getLexer().isNot(AsmToken::EndOfStatement))
3551 return TokError("unexpected token in '.ifb' directive");
3552
3553 Lex();
3554
3555 TheCondState.CondMet = ExpectBlank == Str.empty();
3556 TheCondState.Ignore = !TheCondState.CondMet;
3557 }
3558
3559 return false;
3560}
3561
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003562/// ParseDirectiveIfc
3563/// ::= .ifc string1, string2
3564bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3565 TheCondStack.push_back(TheCondState);
3566 TheCondState.TheCond = AsmCond::IfCond;
3567
Benjamin Kramer29739e72012-05-12 16:52:21 +00003568 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003569 eatToEndOfStatement();
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003570 } else {
3571 StringRef Str1 = ParseStringToComma();
3572
3573 if (getLexer().isNot(AsmToken::Comma))
3574 return TokError("unexpected token in '.ifc' directive");
3575
3576 Lex();
3577
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003578 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003579
3580 if (getLexer().isNot(AsmToken::EndOfStatement))
3581 return TokError("unexpected token in '.ifc' directive");
3582
3583 Lex();
3584
3585 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3586 TheCondState.Ignore = !TheCondState.CondMet;
3587 }
3588
3589 return false;
3590}
3591
3592/// ParseDirectiveIfdef
3593/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003594bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3595 StringRef Name;
3596 TheCondStack.push_back(TheCondState);
3597 TheCondState.TheCond = AsmCond::IfCond;
3598
3599 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003600 eatToEndOfStatement();
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003601 } else {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003602 if (parseIdentifier(Name))
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003603 return TokError("expected identifier after '.ifdef'");
3604
3605 Lex();
3606
3607 MCSymbol *Sym = getContext().LookupSymbol(Name);
3608
3609 if (expect_defined)
3610 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3611 else
3612 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3613 TheCondState.Ignore = !TheCondState.CondMet;
3614 }
3615
3616 return false;
3617}
3618
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003619/// ParseDirectiveElseIf
3620/// ::= .elseif expression
3621bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
3622 if (TheCondState.TheCond != AsmCond::IfCond &&
3623 TheCondState.TheCond != AsmCond::ElseIfCond)
3624 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3625 " an .elseif");
3626 TheCondState.TheCond = AsmCond::ElseIfCond;
3627
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003628 bool LastIgnoreState = false;
3629 if (!TheCondStack.empty())
3630 LastIgnoreState = TheCondStack.back().Ignore;
3631 if (LastIgnoreState || TheCondState.CondMet) {
3632 TheCondState.Ignore = true;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003633 eatToEndOfStatement();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003634 }
3635 else {
3636 int64_t ExprValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003637 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003638 return true;
3639
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003640 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003641 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003642
Sean Callanan79ed1a82010-01-19 20:22:31 +00003643 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003644 TheCondState.CondMet = ExprValue;
3645 TheCondState.Ignore = !TheCondState.CondMet;
3646 }
3647
3648 return false;
3649}
3650
3651/// ParseDirectiveElse
3652/// ::= .else
3653bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003654 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003655 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003656
Sean Callanan79ed1a82010-01-19 20:22:31 +00003657 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003658
3659 if (TheCondState.TheCond != AsmCond::IfCond &&
3660 TheCondState.TheCond != AsmCond::ElseIfCond)
3661 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3662 ".elseif");
3663 TheCondState.TheCond = AsmCond::ElseCond;
3664 bool LastIgnoreState = false;
3665 if (!TheCondStack.empty())
3666 LastIgnoreState = TheCondStack.back().Ignore;
3667 if (LastIgnoreState || TheCondState.CondMet)
3668 TheCondState.Ignore = true;
3669 else
3670 TheCondState.Ignore = false;
3671
3672 return false;
3673}
3674
3675/// ParseDirectiveEndIf
3676/// ::= .endif
3677bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003678 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003679 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003680
Sean Callanan79ed1a82010-01-19 20:22:31 +00003681 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003682
3683 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3684 TheCondStack.empty())
3685 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3686 ".else");
3687 if (!TheCondStack.empty()) {
3688 TheCondState = TheCondStack.back();
3689 TheCondStack.pop_back();
3690 }
3691
3692 return false;
3693}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003694
Eli Bendersky6ee13082013-01-15 22:59:42 +00003695void AsmParser::initializeDirectiveKindMap() {
3696 DirectiveKindMap[".set"] = DK_SET;
3697 DirectiveKindMap[".equ"] = DK_EQU;
3698 DirectiveKindMap[".equiv"] = DK_EQUIV;
3699 DirectiveKindMap[".ascii"] = DK_ASCII;
3700 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3701 DirectiveKindMap[".string"] = DK_STRING;
3702 DirectiveKindMap[".byte"] = DK_BYTE;
3703 DirectiveKindMap[".short"] = DK_SHORT;
3704 DirectiveKindMap[".value"] = DK_VALUE;
3705 DirectiveKindMap[".2byte"] = DK_2BYTE;
3706 DirectiveKindMap[".long"] = DK_LONG;
3707 DirectiveKindMap[".int"] = DK_INT;
3708 DirectiveKindMap[".4byte"] = DK_4BYTE;
3709 DirectiveKindMap[".quad"] = DK_QUAD;
3710 DirectiveKindMap[".8byte"] = DK_8BYTE;
3711 DirectiveKindMap[".single"] = DK_SINGLE;
3712 DirectiveKindMap[".float"] = DK_FLOAT;
3713 DirectiveKindMap[".double"] = DK_DOUBLE;
3714 DirectiveKindMap[".align"] = DK_ALIGN;
3715 DirectiveKindMap[".align32"] = DK_ALIGN32;
3716 DirectiveKindMap[".balign"] = DK_BALIGN;
3717 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3718 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3719 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3720 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3721 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3722 DirectiveKindMap[".org"] = DK_ORG;
3723 DirectiveKindMap[".fill"] = DK_FILL;
3724 DirectiveKindMap[".zero"] = DK_ZERO;
3725 DirectiveKindMap[".extern"] = DK_EXTERN;
3726 DirectiveKindMap[".globl"] = DK_GLOBL;
3727 DirectiveKindMap[".global"] = DK_GLOBAL;
3728 DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
3729 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3730 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3731 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3732 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3733 DirectiveKindMap[".reference"] = DK_REFERENCE;
3734 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3735 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3736 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3737 DirectiveKindMap[".comm"] = DK_COMM;
3738 DirectiveKindMap[".common"] = DK_COMMON;
3739 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3740 DirectiveKindMap[".abort"] = DK_ABORT;
3741 DirectiveKindMap[".include"] = DK_INCLUDE;
3742 DirectiveKindMap[".incbin"] = DK_INCBIN;
3743 DirectiveKindMap[".code16"] = DK_CODE16;
3744 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3745 DirectiveKindMap[".rept"] = DK_REPT;
3746 DirectiveKindMap[".irp"] = DK_IRP;
3747 DirectiveKindMap[".irpc"] = DK_IRPC;
3748 DirectiveKindMap[".endr"] = DK_ENDR;
3749 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3750 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3751 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3752 DirectiveKindMap[".if"] = DK_IF;
3753 DirectiveKindMap[".ifb"] = DK_IFB;
3754 DirectiveKindMap[".ifnb"] = DK_IFNB;
3755 DirectiveKindMap[".ifc"] = DK_IFC;
3756 DirectiveKindMap[".ifnc"] = DK_IFNC;
3757 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3758 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3759 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3760 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3761 DirectiveKindMap[".else"] = DK_ELSE;
3762 DirectiveKindMap[".endif"] = DK_ENDIF;
3763 DirectiveKindMap[".skip"] = DK_SKIP;
3764 DirectiveKindMap[".space"] = DK_SPACE;
3765 DirectiveKindMap[".file"] = DK_FILE;
3766 DirectiveKindMap[".line"] = DK_LINE;
3767 DirectiveKindMap[".loc"] = DK_LOC;
3768 DirectiveKindMap[".stabs"] = DK_STABS;
3769 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3770 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3771 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3772 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3773 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3774 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3775 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3776 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3777 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3778 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3779 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3780 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3781 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3782 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3783 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3784 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3785 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3786 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3787 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3788 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3789 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3790 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3791 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3792 DirectiveKindMap[".macro"] = DK_MACRO;
3793 DirectiveKindMap[".endm"] = DK_ENDM;
3794 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3795 DirectiveKindMap[".purgem"] = DK_PURGEM;
Eli Bendersky5d0f0612013-01-10 22:44:57 +00003796}
3797
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003798
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003799MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003800 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003801
Rafael Espindola761cb062012-06-03 23:57:14 +00003802 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003803 for (;;) {
3804 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003805 if (getLexer().is(AsmToken::Eof)) {
3806 Error(DirectiveLoc, "no matching '.endr' in definition");
3807 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003808 }
3809
Rafael Espindola761cb062012-06-03 23:57:14 +00003810 if (Lexer.is(AsmToken::Identifier) &&
3811 (getTok().getIdentifier() == ".rept")) {
3812 ++NestLevel;
3813 }
3814
3815 // Otherwise, check whether we have reached the .endr.
3816 if (Lexer.is(AsmToken::Identifier) &&
3817 getTok().getIdentifier() == ".endr") {
3818 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003819 EndToken = getTok();
3820 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003821 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3822 TokError("unexpected token in '.endr' directive");
3823 return 0;
3824 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003825 break;
3826 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003827 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003828 }
3829
Rafael Espindola761cb062012-06-03 23:57:14 +00003830 // Otherwise, scan till the end of the statement.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003831 eatToEndOfStatement();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003832 }
3833
3834 const char *BodyStart = StartToken.getLoc().getPointer();
3835 const char *BodyEnd = EndToken.getLoc().getPointer();
3836 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3837
Rafael Espindola761cb062012-06-03 23:57:14 +00003838 // We Are Anonymous.
3839 StringRef Name;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003840 MCAsmMacroParameters Parameters;
3841 return new MCAsmMacro(Name, Body, Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +00003842}
3843
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003844void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +00003845 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003846 OS << ".endr\n";
3847
3848 MemoryBuffer *Instantiation =
3849 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3850
Rafael Espindola761cb062012-06-03 23:57:14 +00003851 // Create the macro instantiation object and add to the current macro
3852 // instantiation stack.
3853 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003854 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003855 getTok().getLoc(),
3856 Instantiation);
3857 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003858
Rafael Espindola761cb062012-06-03 23:57:14 +00003859 // Jump to the macro instantiation and prime the lexer.
3860 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3861 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3862 Lex();
3863}
3864
3865bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3866 int64_t Count;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003867 if (parseAbsoluteExpression(Count))
Rafael Espindola761cb062012-06-03 23:57:14 +00003868 return TokError("unexpected token in '.rept' directive");
3869
3870 if (Count < 0)
3871 return TokError("Count is negative");
3872
3873 if (Lexer.isNot(AsmToken::EndOfStatement))
3874 return TokError("unexpected token in '.rept' directive");
3875
3876 // Eat the end of statement.
3877 Lex();
3878
3879 // Lex the rept definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003880 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindola761cb062012-06-03 23:57:14 +00003881 if (!M)
3882 return true;
3883
3884 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3885 // to hold the macro body with substitutions.
3886 SmallString<256> Buf;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003887 MCAsmMacroParameters Parameters;
3888 MCAsmMacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003889 raw_svector_ostream OS(Buf);
3890 while (Count--) {
3891 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3892 return true;
3893 }
3894 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003895
3896 return false;
3897}
3898
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003899/// ParseDirectiveIrp
3900/// ::= .irp symbol,values
3901bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003902 MCAsmMacroParameters Parameters;
3903 MCAsmMacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003904
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003905 if (parseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003906 return TokError("expected identifier in '.irp' directive");
3907
3908 Parameters.push_back(Parameter);
3909
3910 if (Lexer.isNot(AsmToken::Comma))
3911 return TokError("expected comma in '.irp' directive");
3912
3913 Lex();
3914
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003915 MCAsmMacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003916 if (ParseMacroArguments(0, A))
3917 return true;
3918
3919 // Eat the end of statement.
3920 Lex();
3921
3922 // Lex the irp definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003923 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003924 if (!M)
3925 return true;
3926
3927 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3928 // to hold the macro body with substitutions.
3929 SmallString<256> Buf;
3930 raw_svector_ostream OS(Buf);
3931
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003932 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3933 MCAsmMacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003934 Args.push_back(*i);
3935
3936 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3937 return true;
3938 }
3939
3940 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3941
3942 return false;
3943}
3944
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003945/// ParseDirectiveIrpc
3946/// ::= .irpc symbol,values
3947bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003948 MCAsmMacroParameters Parameters;
3949 MCAsmMacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003950
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003951 if (parseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003952 return TokError("expected identifier in '.irpc' directive");
3953
3954 Parameters.push_back(Parameter);
3955
3956 if (Lexer.isNot(AsmToken::Comma))
3957 return TokError("expected comma in '.irpc' directive");
3958
3959 Lex();
3960
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003961 MCAsmMacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003962 if (ParseMacroArguments(0, A))
3963 return true;
3964
3965 if (A.size() != 1 || A.front().size() != 1)
3966 return TokError("unexpected token in '.irpc' directive");
3967
3968 // Eat the end of statement.
3969 Lex();
3970
3971 // Lex the irpc definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003972 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003973 if (!M)
3974 return true;
3975
3976 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3977 // to hold the macro body with substitutions.
3978 SmallString<256> Buf;
3979 raw_svector_ostream OS(Buf);
3980
3981 StringRef Values = A.front().front().getString();
3982 std::size_t I, End = Values.size();
3983 for (I = 0; I < End; ++I) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00003984 MCAsmMacroArgument Arg;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003985 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3986
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003987 MCAsmMacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003988 Args.push_back(Arg);
3989
3990 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3991 return true;
3992 }
3993
3994 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3995
3996 return false;
3997}
3998
Rafael Espindola761cb062012-06-03 23:57:14 +00003999bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
4000 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00004001 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004002
4003 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00004004 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004005 assert(getLexer().is(AsmToken::EndOfStatement));
4006
Rafael Espindola761cb062012-06-03 23:57:14 +00004007 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004008 return false;
4009}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00004010
Benjamin Kramer75234372013-02-15 20:37:21 +00004011bool AsmParser::ParseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4012 size_t Len) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004013 const MCExpr *Value;
4014 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004015 if (parseExpression(Value))
Eli Friedman2128aae2012-10-22 23:58:19 +00004016 return true;
4017 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4018 if (!MCE)
4019 return Error(ExprLoc, "unexpected expression in _emit");
4020 uint64_t IntValue = MCE->getValue();
4021 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4022 return Error(ExprLoc, "literal value out of range for directive");
4023
Chad Rosier469b1442013-02-12 21:33:51 +00004024 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4025 return false;
4026}
4027
4028bool AsmParser::ParseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4029 const MCExpr *Value;
4030 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004031 if (parseExpression(Value))
Chad Rosier469b1442013-02-12 21:33:51 +00004032 return true;
4033 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4034 if (!MCE)
4035 return Error(ExprLoc, "unexpected expression in align");
4036 uint64_t IntValue = MCE->getValue();
4037 if (!isPowerOf2_64(IntValue))
4038 return Error(ExprLoc, "literal value not a power of two greater then zero");
4039
Benjamin Kramer75234372013-02-15 20:37:21 +00004040 Info.AsmRewrites->push_back(AsmRewrite(AOK_Align, IDLoc, 5,
4041 Log2_64(IntValue)));
Eli Friedman2128aae2012-10-22 23:58:19 +00004042 return false;
4043}
4044
Chad Rosier19aa3e32013-02-13 21:27:17 +00004045// We are comparing pointers, but the pointers are relative to a single string.
4046// Thus, this should always be deterministic.
Benjamin Kramer75234372013-02-15 20:37:21 +00004047static int RewritesSort(const void *A, const void *B) {
4048 const AsmRewrite *AsmRewriteA = static_cast<const AsmRewrite *>(A);
4049 const AsmRewrite *AsmRewriteB = static_cast<const AsmRewrite *>(B);
Chad Rosierabde6752013-02-13 18:38:58 +00004050 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4051 return -1;
4052 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4053 return 1;
Chad Rosierb54562b2013-02-15 22:54:16 +00004054
Chad Rosier6b369ce2013-04-08 17:43:47 +00004055 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4056 // rewrite to the same location. Make sure the SizeDirective rewrite is
4057 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4058 // ensures the sort algorithm is stable.
4059 if (AsmRewritePrecedence [AsmRewriteA->Kind] >
4060 AsmRewritePrecedence [AsmRewriteB->Kind])
Chad Rosierb54562b2013-02-15 22:54:16 +00004061 return -1;
Chad Rosier6b369ce2013-04-08 17:43:47 +00004062
4063 if (AsmRewritePrecedence [AsmRewriteA->Kind] <
4064 AsmRewritePrecedence [AsmRewriteB->Kind])
Chad Rosierb54562b2013-02-15 22:54:16 +00004065 return 1;
Chad Rosierb54562b2013-02-15 22:54:16 +00004066 llvm_unreachable ("Unstable rewrite sort.");
Chad Rosierb1953982013-02-13 01:03:13 +00004067}
4068
Benjamin Kramer75234372013-02-15 20:37:21 +00004069bool
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004070AsmParser::parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Benjamin Kramer75234372013-02-15 20:37:21 +00004071 unsigned &NumOutputs, unsigned &NumInputs,
4072 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4073 SmallVectorImpl<std::string> &Constraints,
4074 SmallVectorImpl<std::string> &Clobbers,
4075 const MCInstrInfo *MII,
4076 const MCInstPrinter *IP,
4077 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004078 SmallVector<void *, 4> InputDecls;
4079 SmallVector<void *, 4> OutputDecls;
Chad Rosierc1ec2072013-01-10 22:10:27 +00004080 SmallVector<bool, 4> InputDeclsAddressOf;
4081 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004082 SmallVector<std::string, 4> InputConstraints;
4083 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer75234372013-02-15 20:37:21 +00004084 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004085
Benjamin Kramer75234372013-02-15 20:37:21 +00004086 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004087
4088 // Prime the lexer.
4089 Lex();
4090
4091 // While we have input, parse each statement.
4092 unsigned InputIdx = 0;
4093 unsigned OutputIdx = 0;
4094 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004095 ParseStatementInfo Info(&AsmStrRewrites);
4096 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00004097 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004098
Chad Rosier57498012012-12-12 22:45:52 +00004099 if (Info.ParseError)
4100 return true;
4101
Benjamin Kramer75234372013-02-15 20:37:21 +00004102 if (Info.Opcode == ~0U)
4103 continue;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004104
Benjamin Kramer75234372013-02-15 20:37:21 +00004105 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004106
Benjamin Kramer75234372013-02-15 20:37:21 +00004107 // Build the list of clobbers, outputs and inputs.
4108 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4109 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004110
Benjamin Kramer75234372013-02-15 20:37:21 +00004111 // Immediate.
Chad Rosier811ddf62013-03-19 21:58:18 +00004112 if (Operand->isImm())
Benjamin Kramer75234372013-02-15 20:37:21 +00004113 continue;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004114
Benjamin Kramer75234372013-02-15 20:37:21 +00004115 // Register operand.
4116 if (Operand->isReg() && !Operand->needAddressOf()) {
4117 unsigned NumDefs = Desc.getNumDefs();
4118 // Clobber.
4119 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4120 ClobberRegs.push_back(Operand->getReg());
4121 continue;
4122 }
4123
4124 // Expr/Input or Output.
4125 bool IsVarDecl;
4126 unsigned Length, Size, Type;
Chad Rosierb976e402013-04-09 17:53:49 +00004127 StringRef SymName = Operand->getSymName();
4128 if (SymName.empty())
4129 continue;
4130
4131 void *OpDecl = SI.LookupInlineAsmIdentifier(SymName, AsmLoc,
Benjamin Kramer75234372013-02-15 20:37:21 +00004132 Length, Size, Type,
4133 IsVarDecl);
4134 if (!OpDecl)
4135 continue;
4136
4137 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierb976e402013-04-09 17:53:49 +00004138 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer75234372013-02-15 20:37:21 +00004139 if (isOutput) {
4140 ++InputIdx;
4141 OutputDecls.push_back(OpDecl);
4142 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4143 OutputConstraints.push_back('=' + Operand->getConstraint().str());
Chad Rosierb976e402013-04-09 17:53:49 +00004144 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
Benjamin Kramer75234372013-02-15 20:37:21 +00004145 } else {
4146 InputDecls.push_back(OpDecl);
4147 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4148 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosierb976e402013-04-09 17:53:49 +00004149 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00004150 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004151 }
4152 }
4153
4154 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004155 NumOutputs = OutputDecls.size();
4156 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00004157
4158 // Set the unique clobbers.
Benjamin Kramer75234372013-02-15 20:37:21 +00004159 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4160 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4161 ClobberRegs.end());
4162 Clobbers.assign(ClobberRegs.size(), std::string());
4163 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4164 raw_string_ostream OS(Clobbers[I]);
4165 IP->printRegName(OS, ClobberRegs[I]);
4166 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004167
4168 // Merge the various outputs and inputs. Output are expected first.
4169 if (NumOutputs || NumInputs) {
4170 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004171 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004172 Constraints.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004173 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004174 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004175 Constraints[i] = OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004176 }
4177 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004178 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004179 Constraints[j] = InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004180 }
4181 }
4182
4183 // Build the IR assembly string.
4184 std::string AsmStringIR;
4185 raw_string_ostream OS(AsmStringIR);
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004186 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4187 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
Benjamin Kramer75234372013-02-15 20:37:21 +00004188 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), RewritesSort);
4189 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4190 E = AsmStrRewrites.end();
4191 I != E; ++I) {
Chad Rosierdda4b6b2013-04-12 16:26:42 +00004192 AsmRewriteKind Kind = (*I).Kind;
4193 if (Kind == AOK_Delete)
4194 continue;
4195
Chad Rosierb1f8c132012-10-18 15:49:34 +00004196 const char *Loc = (*I).Loc.getPointer();
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004197 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier96d58e62012-10-19 20:57:14 +00004198
Chad Rosier023c8802013-03-19 17:32:17 +00004199 // Emit everything up to the immediate/expression.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004200 unsigned Len = Loc - AsmStart;
Chad Rosierf06cc982013-04-11 21:49:30 +00004201 if (Len)
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004202 OS << StringRef(AsmStart, Len);
Chad Rosier96d58e62012-10-19 20:57:14 +00004203
Chad Rosier5a719fc2012-10-23 17:43:43 +00004204 // Skip the original expression.
4205 if (Kind == AOK_Skip) {
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004206 AsmStart = Loc + (*I).Len;
Chad Rosier5a719fc2012-10-23 17:43:43 +00004207 continue;
4208 }
4209
Chad Rosierdda4b6b2013-04-12 16:26:42 +00004210 unsigned AdditionalSkip = 0;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004211 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00004212 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004213 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004214 case AOK_Imm:
Benjamin Kramer75234372013-02-15 20:37:21 +00004215 OS << "$$" << (*I).Val;
Chad Rosierefcb3d92012-10-26 18:04:20 +00004216 break;
4217 case AOK_ImmPrefix:
Benjamin Kramer75234372013-02-15 20:37:21 +00004218 OS << "$$";
Chad Rosierb1f8c132012-10-18 15:49:34 +00004219 break;
4220 case AOK_Input:
Benjamin Kramer75234372013-02-15 20:37:21 +00004221 OS << '$' << InputIdx++;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004222 break;
4223 case AOK_Output:
Benjamin Kramer75234372013-02-15 20:37:21 +00004224 OS << '$' << OutputIdx++;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004225 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00004226 case AOK_SizeDirective:
Benjamin Kramer75234372013-02-15 20:37:21 +00004227 switch ((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00004228 default: break;
4229 case 8: OS << "byte ptr "; break;
4230 case 16: OS << "word ptr "; break;
4231 case 32: OS << "dword ptr "; break;
4232 case 64: OS << "qword ptr "; break;
4233 case 80: OS << "xword ptr "; break;
4234 case 128: OS << "xmmword ptr "; break;
4235 case 256: OS << "ymmword ptr "; break;
4236 }
Eli Friedman2128aae2012-10-22 23:58:19 +00004237 break;
4238 case AOK_Emit:
4239 OS << ".byte";
4240 break;
Chad Rosier469b1442013-02-12 21:33:51 +00004241 case AOK_Align: {
4242 unsigned Val = (*I).Val;
4243 OS << ".align " << Val;
4244
4245 // Skip the original immediate.
Benjamin Kramer75234372013-02-15 20:37:21 +00004246 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosier469b1442013-02-12 21:33:51 +00004247 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4248 break;
4249 }
Chad Rosier6a020a72012-10-25 20:41:34 +00004250 case AOK_DotOperator:
4251 OS << (*I).Val;
4252 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004253 }
Chad Rosier96d58e62012-10-19 20:57:14 +00004254
Chad Rosierb1f8c132012-10-18 15:49:34 +00004255 // Skip the original expression.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004256 AsmStart = Loc + (*I).Len + AdditionalSkip;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004257 }
4258
4259 // Emit the remainder of the asm string.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004260 if (AsmStart != AsmEnd)
4261 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004262
4263 AsmString = OS.str();
4264 return false;
4265}
4266
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004267/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004268MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004269 MCContext &C, MCStreamer &Out,
4270 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004271 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004272}