blob: fb4bea10de4a772d01e1092a4f30c27b5a8d8ded [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 Enderbya8959492013-06-21 20:51:39 +0000163 /// When generating dwarf for assembly source files we need to calculate the
164 /// logical line number based on the last parsed cpp hash file line comment
165 /// and current line. Since this is slow and messes up the SourceMgr's
166 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
167 SMLoc LastQueryIDLoc;
168 int LastQueryBuffer;
169 unsigned LastQueryLine;
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000170
Devang Patel0db58bf2012-01-31 18:14:05 +0000171 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
172 unsigned AssemblerDialect;
173
Preston Gurd7b6f2032012-09-19 20:36:12 +0000174 /// IsDarwin - is Darwin compatibility enabled?
175 bool IsDarwin;
176
Chad Rosier8f138d12012-10-15 17:19:13 +0000177 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000178 bool ParsingInlineAsm;
179
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000180public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000181 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000182 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000183 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000184
185 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
186
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000187 virtual void addDirectiveHandler(StringRef Directive,
Eli Bendersky171192f2013-01-16 00:50:52 +0000188 ExtensionDirectiveHandler Handler) {
189 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000190 }
191
192public:
193 /// @name MCAsmParser Interface
194 /// {
195
196 virtual SourceMgr &getSourceManager() { return SrcMgr; }
197 virtual MCAsmLexer &getLexer() { return Lexer; }
198 virtual MCContext &getContext() { return Ctx; }
199 virtual MCStreamer &getStreamer() { return Out; }
Eric Christopher2318ba12012-12-18 00:30:54 +0000200 virtual unsigned getAssemblerDialect() {
Devang Patel0db58bf2012-01-31 18:14:05 +0000201 if (AssemblerDialect == ~0U)
Eric Christopher2318ba12012-12-18 00:30:54 +0000202 return MAI.getAssemblerDialect();
Devang Patel0db58bf2012-01-31 18:14:05 +0000203 else
204 return AssemblerDialect;
205 }
206 virtual void setAssemblerDialect(unsigned i) {
207 AssemblerDialect = i;
208 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000209
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000210 virtual bool Warning(SMLoc L, const Twine &Msg,
Dmitri Gribenko5c332db2013-05-05 00:40:33 +0000211 ArrayRef<SMRange> Ranges = None);
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000212 virtual bool Error(SMLoc L, const Twine &Msg,
Dmitri Gribenko5c332db2013-05-05 00:40:33 +0000213 ArrayRef<SMRange> Ranges = None);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000214
Craig Topper345d16d2012-08-29 05:48:09 +0000215 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000216
Chad Rosier84125ca2012-10-13 00:26:04 +0000217 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosierc5ac87d2012-10-16 20:16:20 +0000218 bool isParsingInlineAsm() { return ParsingInlineAsm; }
Chad Rosierb1f8c132012-10-18 15:49:34 +0000219
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000220 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000221 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +0000222 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000223 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000224 SmallVectorImpl<std::string> &Clobbers,
225 const MCInstrInfo *MII,
226 const MCInstPrinter *IP,
227 MCAsmParserSemaCallback &SI);
Chad Rosier84125ca2012-10-13 00:26:04 +0000228
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000229 bool parseExpression(const MCExpr *&Res);
230 virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc);
Chad Rosierba69b362013-04-10 17:35:30 +0000231 virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000232 virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
233 virtual bool parseAbsoluteExpression(int64_t &Res);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000234
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000235 /// parseIdentifier - Parse an identifier or string (as a quoted identifier)
Eli Benderskybf706b32013-01-12 00:05:00 +0000236 /// and set \p Res to the identifier contents.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000237 virtual bool parseIdentifier(StringRef &Res);
238 virtual void eatToEndOfStatement();
Eli Benderskybf706b32013-01-12 00:05:00 +0000239
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000240 virtual void checkForValidSection();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000241 /// }
242
243private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000244
Eli Friedman2128aae2012-10-22 23:58:19 +0000245 bool ParseStatement(ParseStatementInfo &Info);
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000246 void EatToEndOfLine();
247 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000248
Kevin Enderby221514e2013-01-22 21:44:53 +0000249 void CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
250 MCAsmMacroParameters Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +0000251 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000252 const MCAsmMacroParameters &Parameters,
253 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000254 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000255
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000256 /// \brief Are macros enabled in the parser?
257 bool MacrosEnabled() {return MacrosEnabledFlag;}
258
259 /// \brief Control a flag in the parser that enables or disables macros.
260 void SetMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
261
262 /// \brief Lookup a previously defined macro.
263 /// \param Name Macro name.
264 /// \returns Pointer to macro. NULL if no such macro was defined.
265 const MCAsmMacro* LookupMacro(StringRef Name);
266
267 /// \brief Define a new macro with the given name and information.
268 void DefineMacro(StringRef Name, const MCAsmMacro& Macro);
269
270 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
271 void UndefineMacro(StringRef Name);
272
273 /// \brief Are we inside a macro instantiation?
274 bool InsideMacroInstantiation() {return !ActiveMacros.empty();}
275
276 /// \brief Handle entry to macro instantiation.
277 ///
278 /// \param M The macro.
279 /// \param NameLoc Instantiation location.
280 bool HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
281
282 /// \brief Handle exit from macro instantiation.
283 void HandleMacroExit();
284
285 /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
286 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
287 /// correct delimiter by the method.
288 bool ParseMacroArgument(MCAsmMacroArgument &MA,
289 AsmToken::TokenKind &ArgumentDelimiter);
290
291 /// \brief Parse all macro arguments for a given macro.
292 bool ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
293
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000294 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000295 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Dmitri Gribenko5c332db2013-05-05 00:40:33 +0000296 ArrayRef<SMRange> Ranges = None) const {
Chris Lattner462b43c2011-10-16 05:47:55 +0000297 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000298 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000299 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000300
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000301 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
302 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000303 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
304 /// This returns true on failure.
305 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000306
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000307 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000308 /// current token is not set; clients should ensure Lex() is called
309 /// subsequently.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000310 ///
311 /// \param InBuffer If not -1, should be the known buffer id that contains the
312 /// location.
313 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000314
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000315 /// \brief Parse up to the end of statement and a return the contents from the
316 /// current token until the end of the statement; the current token on exit
317 /// will be either the EndOfStatement or EOF.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000318 virtual StringRef parseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000319
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000320 /// \brief Parse until the end of a statement or a comma is encountered,
321 /// return the contents from the current token up to the end or comma.
322 StringRef ParseStringToComma();
323
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000324 bool ParseAssignment(StringRef Name, bool allow_redef,
325 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000326
327 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
328 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
329 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000330 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000331
Eli Bendersky6ee13082013-01-15 22:59:42 +0000332 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola787c3372010-10-28 20:02:27 +0000333
Eli Bendersky6ee13082013-01-15 22:59:42 +0000334 // Generic (target and platform independent) directive parsing.
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000335 enum DirectiveKind {
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000336 DK_NO_DIRECTIVE, // Placeholder
337 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
338 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
339 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky9b1bb052013-01-11 22:55:28 +0000340 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000341 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
342 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
343 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
344 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
345 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
346 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
347 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
Eli Bendersky6ee13082013-01-15 22:59:42 +0000348 DK_ELSEIF, DK_ELSE, DK_ENDIF,
349 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
350 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
351 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
352 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
353 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
354 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
355 DK_CFI_REGISTER,
356 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
357 DK_SLEB128, DK_ULEB128
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000358 };
359
Eli Bendersky6ee13082013-01-15 22:59:42 +0000360 /// DirectiveKindMap - Maps directive name --> DirectiveKind enum, for
361 /// directives parsed by this class.
362 StringMap<DirectiveKind> DirectiveKindMap;
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000363
364 // ".ascii", ".asciz", ".string"
Rafael Espindola787c3372010-10-28 20:02:27 +0000365 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000366 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000367 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000368 bool ParseDirectiveFill(); // ".fill"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000369 bool ParseDirectiveZero(); // ".zero"
Eric Christopher2318ba12012-12-18 00:30:54 +0000370 // ".set", ".equ", ".equiv"
371 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000372 bool ParseDirectiveOrg(); // ".org"
373 // ".align{,32}", ".p2align{,w,l}"
374 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
375
Eli Bendersky6ee13082013-01-15 22:59:42 +0000376 // ".file", ".line", ".loc", ".stabs"
377 bool ParseDirectiveFile(SMLoc DirectiveLoc);
378 bool ParseDirectiveLine();
379 bool ParseDirectiveLoc();
380 bool ParseDirectiveStabs();
381
382 // .cfi directives
383 bool ParseDirectiveCFIRegister(SMLoc DirectiveLoc);
384 bool ParseDirectiveCFISections();
385 bool ParseDirectiveCFIStartProc();
386 bool ParseDirectiveCFIEndProc();
387 bool ParseDirectiveCFIDefCfaOffset();
388 bool ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
389 bool ParseDirectiveCFIAdjustCfaOffset();
390 bool ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
391 bool ParseDirectiveCFIOffset(SMLoc DirectiveLoc);
392 bool ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
393 bool ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
394 bool ParseDirectiveCFIRememberState();
395 bool ParseDirectiveCFIRestoreState();
396 bool ParseDirectiveCFISameValue(SMLoc DirectiveLoc);
397 bool ParseDirectiveCFIRestore(SMLoc DirectiveLoc);
398 bool ParseDirectiveCFIEscape();
399 bool ParseDirectiveCFISignalFrame();
400 bool ParseDirectiveCFIUndefined(SMLoc DirectiveLoc);
401
402 // macro directives
403 bool ParseDirectivePurgeMacro(SMLoc DirectiveLoc);
404 bool ParseDirectiveEndMacro(StringRef Directive);
405 bool ParseDirectiveMacro(SMLoc DirectiveLoc);
406 bool ParseDirectiveMacrosOnOff(StringRef Directive);
407
Eli Bendersky4766ef42012-12-20 19:05:53 +0000408 // ".bundle_align_mode"
409 bool ParseDirectiveBundleAlignMode();
410 // ".bundle_lock"
411 bool ParseDirectiveBundleLock();
412 // ".bundle_unlock"
413 bool ParseDirectiveBundleUnlock();
414
Eli Bendersky6ee13082013-01-15 22:59:42 +0000415 // ".space", ".skip"
416 bool ParseDirectiveSpace(StringRef IDVal);
417
418 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
419 bool ParseDirectiveLEB128(bool Signed);
420
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000421 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
422 /// accepts a single symbol (which should be a label or an external).
423 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000424
425 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
426
427 bool ParseDirectiveAbort(); // ".abort"
428 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000429 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000430
431 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000432 // ".ifb" or ".ifnb", depending on ExpectBlank.
433 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000434 // ".ifc" or ".ifnc", depending on ExpectEqual.
435 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000436 // ".ifdef" or ".ifndef", depending on expect_defined
437 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000438 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
439 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
440 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000441 virtual bool parseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000442
443 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
444 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000445
Rafael Espindola761cb062012-06-03 23:57:14 +0000446 // Macro-like directives
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000447 MCAsmMacro *ParseMacroLikeBody(SMLoc DirectiveLoc);
448 void InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +0000449 raw_svector_ostream &OS);
450 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000451 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000452 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000453 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000454
Chad Rosier469b1442013-02-12 21:33:51 +0000455 // "_emit" or "__emit"
456 bool ParseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
457 size_t Len);
458
459 // "align"
460 bool ParseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000461
Eli Bendersky6ee13082013-01-15 22:59:42 +0000462 void initializeDirectiveKindMap();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000463};
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000464}
465
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000466namespace llvm {
467
468extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000469extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000470extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000471
472}
473
Chris Lattneraaec2052010-01-19 19:46:13 +0000474enum { DEFAULT_ADDRSPACE = 0 };
475
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000476AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000477 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000478 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Eli Bendersky6ee13082013-01-15 22:59:42 +0000479 PlatformParser(0),
Eli Bendersky733c3362013-01-14 18:08:41 +0000480 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000481 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000482 // Save the old handler.
483 SavedDiagHandler = SrcMgr.getDiagHandler();
484 SavedDiagContext = SrcMgr.getDiagContext();
485 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000486 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000487 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000488
Daniel Dunbare4749702010-07-12 18:12:02 +0000489 // Initialize the platform / file format parser.
490 //
491 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
492 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000493 if (_MAI.hasMicrosoftFastStdCallMangling()) {
494 PlatformParser = createCOFFAsmParser();
495 PlatformParser->Initialize(*this);
496 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000497 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000498 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000499 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000500 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000501 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000502 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000503 }
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000504
Eli Bendersky6ee13082013-01-15 22:59:42 +0000505 initializeDirectiveKindMap();
Chris Lattnerebb89b42009-09-27 21:16:52 +0000506}
507
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000508AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000509 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
510
511 // Destroy any macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000512 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
Daniel Dunbar56491302010-07-29 01:51:55 +0000513 ie = MacroMap.end(); it != ie; ++it)
514 delete it->getValue();
515
Daniel Dunbare4749702010-07-12 18:12:02 +0000516 delete PlatformParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000517}
518
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000519void AsmParser::PrintMacroInstantiations() {
520 // Print the active macro instantiation stack.
521 for (std::vector<MacroInstantiation*>::const_reverse_iterator
522 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000523 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
524 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000525}
526
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000527bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000528 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000529 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000530 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000531 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000532 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000533}
534
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000535bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000536 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000537 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000538 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000539 return true;
540}
541
Sean Callananfd0b0282010-01-21 00:19:58 +0000542bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000543 std::string IncludedFile;
544 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000545 if (NewBuf == -1)
546 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000547
Sean Callananfd0b0282010-01-21 00:19:58 +0000548 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000549
Sean Callananfd0b0282010-01-21 00:19:58 +0000550 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000551
Sean Callananfd0b0282010-01-21 00:19:58 +0000552 return false;
553}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000554
Sylvestre Ledruda2ed452013-05-14 23:36:24 +0000555/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000556/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000557/// returns true on failure.
558bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
559 std::string IncludedFile;
560 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
561 if (NewBuf == -1)
562 return true;
563
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000564 // Pick up the bytes from the file and emit them.
Rafael Espindolaa3863ea2013-07-02 15:49:13 +0000565 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000566 return false;
567}
568
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000569void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
570 if (InBuffer != -1) {
571 CurBuffer = InBuffer;
572 } else {
573 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
574 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000575 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
576}
577
Sean Callananfd0b0282010-01-21 00:19:58 +0000578const AsmToken &AsmParser::Lex() {
579 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000580
Sean Callananfd0b0282010-01-21 00:19:58 +0000581 if (tok->is(AsmToken::Eof)) {
582 // If this is the end of an included file, pop the parent file off the
583 // include stack.
584 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
585 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000586 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000587 tok = &Lexer.Lex();
588 }
589 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000590
Sean Callananfd0b0282010-01-21 00:19:58 +0000591 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000592 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000593
Sean Callananfd0b0282010-01-21 00:19:58 +0000594 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000595}
596
Chris Lattner79180e22010-04-05 23:15:42 +0000597bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000598 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000599 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000600 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000601
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000602 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000603 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000604
605 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000606 AsmCond StartingCondState = TheCondState;
607
Kevin Enderby613b7572011-11-01 22:27:22 +0000608 // If we are generating dwarf for assembly source files save the initial text
609 // section and generate a .file directive.
610 if (getContext().getGenDwarfForAssembly()) {
Peter Collingbournedf39be62013-04-17 21:18:16 +0000611 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
Kevin Enderby94c2e852011-12-09 18:09:40 +0000612 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
613 getStreamer().EmitLabel(SectionStartSym);
614 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000615 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
Eric Christopher6c583142012-12-18 00:31:01 +0000616 StringRef(),
617 getContext().getMainFileName());
Kevin Enderby613b7572011-11-01 22:27:22 +0000618 }
619
Chris Lattnerb717fb02009-07-02 21:53:43 +0000620 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000621 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000622 ParseStatementInfo Info;
623 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000624
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000625 // We had an error, validate that one was emitted and recover by skipping to
626 // the next line.
627 assert(HadError && "Parse statement returned an error, but none emitted!");
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000628 eatToEndOfStatement();
Chris Lattnerb717fb02009-07-02 21:53:43 +0000629 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000630
631 if (TheCondState.TheCond != StartingCondState.TheCond ||
632 TheCondState.Ignore != StartingCondState.Ignore)
633 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000634
635 // Check to see there are no empty DwarfFile slots.
Manman Ren9e999ad2013-03-12 20:17:00 +0000636 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000637 getContext().getMCDwarfFiles();
638 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000639 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000640 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000641 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000642
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000643 // Check to see that all assembler local symbols were actually defined.
644 // Targets that don't do subsections via symbols may not want this, though,
645 // so conservatively exclude them. Only do this if we're finalizing, though,
646 // as otherwise we won't necessarilly have seen everything yet.
647 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
648 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
649 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
650 e = Symbols.end();
651 i != e; ++i) {
652 MCSymbol *Sym = i->getValue();
653 // Variable symbols may not be marked as defined, so check those
654 // explicitly. If we know it's a variable, we have a definition for
655 // the purposes of this check.
656 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
657 // FIXME: We would really like to refer back to where the symbol was
658 // first referenced for a source location. We need to add something
659 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000660 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
661 "assembler local symbol '" + Sym->getName() +
662 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000663 }
664 }
665
666
Chris Lattner79180e22010-04-05 23:15:42 +0000667 // Finalize the output stream if there are no errors and if the client wants
668 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000669 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000670 Out.Finish();
671
Chris Lattnerb717fb02009-07-02 21:53:43 +0000672 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000673}
674
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000675void AsmParser::checkForValidSection() {
Peter Collingbournedf39be62013-04-17 21:18:16 +0000676 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000677 TokError("expected section directive before assembly directive");
Eli Bendersky030f63a2013-01-14 19:04:57 +0000678 Out.InitToTextSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000679 }
680}
681
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000682/// eatToEndOfStatement - Throw away the rest of the line for testing purposes.
683void AsmParser::eatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000684 while (Lexer.isNot(AsmToken::EndOfStatement) &&
685 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000686 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000687
Chris Lattner2cf5f142009-06-22 01:29:09 +0000688 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000689 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000690 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000691}
692
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000693StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000694 const char *Start = getTok().getLoc().getPointer();
695
696 while (Lexer.isNot(AsmToken::EndOfStatement) &&
697 Lexer.isNot(AsmToken::Eof))
698 Lex();
699
700 const char *End = getTok().getLoc().getPointer();
701 return StringRef(Start, End - Start);
702}
Chris Lattnerc4193832009-06-22 05:51:26 +0000703
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000704StringRef AsmParser::ParseStringToComma() {
705 const char *Start = getTok().getLoc().getPointer();
706
707 while (Lexer.isNot(AsmToken::EndOfStatement) &&
708 Lexer.isNot(AsmToken::Comma) &&
709 Lexer.isNot(AsmToken::Eof))
710 Lex();
711
712 const char *End = getTok().getLoc().getPointer();
713 return StringRef(Start, End - Start);
714}
715
Chris Lattner74ec1a32009-06-22 06:32:03 +0000716/// ParseParenExpr - Parse a paren expression and return it.
717/// NOTE: This assumes the leading '(' has already been consumed.
718///
719/// parenexpr ::= expr)
720///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000721bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000722 if (parseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000723 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000724 return TokError("expected ')' in parentheses expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000725 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000726 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000727 return false;
728}
Chris Lattnerc4193832009-06-22 05:51:26 +0000729
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000730/// ParseBracketExpr - Parse a bracket expression and return it.
731/// NOTE: This assumes the leading '[' has already been consumed.
732///
733/// bracketexpr ::= expr]
734///
735bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000736 if (parseExpression(Res)) return true;
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000737 if (Lexer.isNot(AsmToken::RBrac))
738 return TokError("expected ']' in brackets expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000739 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000740 Lex();
741 return false;
742}
743
Chris Lattner74ec1a32009-06-22 06:32:03 +0000744/// ParsePrimaryExpr - Parse a primary expression and return it.
745/// primaryexpr ::= (parenexpr
746/// primaryexpr ::= symbol
747/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000748/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000749/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000750bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby5de048e2013-01-22 21:09:20 +0000751 SMLoc FirstTokenLoc = getLexer().getLoc();
752 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
753 switch (FirstTokenKind) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000754 default:
755 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000756 // If we have an error assume that we've already handled it.
757 case AsmToken::Error:
758 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000759 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000760 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000761 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000762 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000763 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000764 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000765 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000766 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000767 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000768 StringRef Identifier;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000769 if (parseIdentifier(Identifier)) {
Kevin Enderby5de048e2013-01-22 21:09:20 +0000770 if (FirstTokenKind == AsmToken::Dollar)
771 return Error(FirstTokenLoc, "invalid token in expression");
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000772 return true;
Kevin Enderby5de048e2013-01-22 21:09:20 +0000773 }
Daniel Dunbare17edff2010-08-24 19:13:42 +0000774
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000775 EndLoc = SMLoc::getFromPointer(Identifier.end());
776
Daniel Dunbarfffff912009-10-16 01:34:54 +0000777 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000778 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000779 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000780
781 // Lookup the symbol variant if used.
782 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000783 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000784 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000785 if (Variant == MCSymbolRefExpr::VK_Invalid) {
786 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000787 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000788 }
789 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000790
Daniel Dunbarfffff912009-10-16 01:34:54 +0000791 // If this is an absolute variable reference, substitute it now to preserve
792 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000793 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000794 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000795 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000796
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000797 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000798 return false;
799 }
800
801 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000802 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000803 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000804 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000805 case AsmToken::Integer: {
806 SMLoc Loc = getTok().getLoc();
807 int64_t IntVal = getTok().getIntVal();
808 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000809 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000810 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000811 // Look for 'b' or 'f' following an Integer as a directional label
812 if (Lexer.getKind() == AsmToken::Identifier) {
813 StringRef IDVal = getTok().getString();
Ulrich Weigand151ad372013-06-20 16:24:17 +0000814 // Lookup the symbol variant if used.
815 std::pair<StringRef, StringRef> Split = IDVal.split('@');
816 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
817 if (Split.first.size() != IDVal.size()) {
818 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
819 if (Variant == MCSymbolRefExpr::VK_Invalid) {
820 Variant = MCSymbolRefExpr::VK_None;
821 return TokError("invalid variant '" + Split.second + "'");
822 }
823 IDVal = Split.first;
824 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000825 if (IDVal == "f" || IDVal == "b"){
826 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
827 IDVal == "f" ? 1 : 0);
Ulrich Weigand151ad372013-06-20 16:24:17 +0000828 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000829 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000830 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000831 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000832 Lex(); // Eat identifier.
833 }
834 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000835 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000836 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000837 case AsmToken::Real: {
838 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000839 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000840 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000841 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000842 Lex(); // Eat token.
843 return false;
844 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000845 case AsmToken::Dot: {
846 // This is a '.' reference, which references the current PC. Emit a
847 // temporary label to the streamer and refer to it.
848 MCSymbol *Sym = Ctx.CreateTempSymbol();
849 Out.EmitLabel(Sym);
850 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000851 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattnerd3050352010-04-14 04:40:28 +0000852 Lex(); // Eat identifier.
853 return false;
854 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000855 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000856 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000857 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000858 case AsmToken::LBrac:
859 if (!PlatformParser->HasBracketExpressions())
860 return TokError("brackets expression not supported on this target");
861 Lex(); // Eat the '['.
862 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000863 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000864 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000865 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000866 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000867 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000868 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000869 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000870 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000871 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000872 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000873 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000874 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000875 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000876 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000877 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000878 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000879 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000880 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000881 }
882}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000883
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000884bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000885 SMLoc EndLoc;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000886 return parseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000887}
888
Chad Rosierba69b362013-04-10 17:35:30 +0000889bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
890 return ParsePrimaryExpr(Res, EndLoc);
891}
892
Daniel Dunbarcceba832010-09-17 02:47:07 +0000893const MCExpr *
894AsmParser::ApplyModifierToExpr(const MCExpr *E,
895 MCSymbolRefExpr::VariantKind Variant) {
896 // Recurse over the given expression, rebuilding it to apply the given variant
897 // if there is exactly one symbol.
898 switch (E->getKind()) {
899 case MCExpr::Target:
900 case MCExpr::Constant:
901 return 0;
902
903 case MCExpr::SymbolRef: {
904 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
905
906 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
907 TokError("invalid variant on expression '" +
908 getTok().getIdentifier() + "' (already modified)");
909 return E;
910 }
911
912 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
913 }
914
915 case MCExpr::Unary: {
916 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
917 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
918 if (!Sub)
919 return 0;
920 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
921 }
922
923 case MCExpr::Binary: {
924 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
925 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
926 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
927
928 if (!LHS && !RHS)
929 return 0;
930
931 if (!LHS) LHS = BE->getLHS();
932 if (!RHS) RHS = BE->getRHS();
933
934 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
935 }
936 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000937
Craig Topper85814382012-02-07 05:05:23 +0000938 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000939}
940
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000941/// parseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000942///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000943/// expr ::= expr &&,|| expr -> lowest.
944/// expr ::= expr |,^,&,! expr
945/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
946/// expr ::= expr <<,>> expr
947/// expr ::= expr +,- expr
948/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000949/// expr ::= primaryexpr
950///
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000951bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000952 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000953 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000954 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
955 return true;
956
Daniel Dunbarcceba832010-09-17 02:47:07 +0000957 // As a special case, we support 'a op b @ modifier' by rewriting the
958 // expression to include the modifier. This is inefficient, but in general we
959 // expect users to use 'a@modifier op b'.
960 if (Lexer.getKind() == AsmToken::At) {
961 Lex();
962
963 if (Lexer.isNot(AsmToken::Identifier))
964 return TokError("unexpected symbol modifier following '@'");
965
966 MCSymbolRefExpr::VariantKind Variant =
967 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
968 if (Variant == MCSymbolRefExpr::VK_Invalid)
969 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
970
971 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
972 if (!ModifiedRes) {
973 return TokError("invalid modifier '" + getTok().getIdentifier() +
974 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000975 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000976
Daniel Dunbarcceba832010-09-17 02:47:07 +0000977 Res = ModifiedRes;
978 Lex();
979 }
980
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000981 // Try to constant fold it up front, if possible.
982 int64_t Value;
983 if (Res->EvaluateAsAbsolute(Value))
984 Res = MCConstantExpr::Create(Value, getContext());
985
986 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000987}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000988
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000989bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000990 Res = 0;
991 return ParseParenExpr(Res, EndLoc) ||
992 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000993}
994
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000995bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000996 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000997
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000998 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000999 if (parseExpression(Expr))
Daniel Dunbar475839e2009-06-29 20:37:27 +00001000 return true;
1001
Daniel Dunbare00b0112009-10-16 01:57:52 +00001002 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00001003 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +00001004
1005 return false;
1006}
1007
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001008static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001009 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001010 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001011 default:
1012 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +00001013
Jim Grosbachfbe16812011-08-20 16:24:13 +00001014 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +00001015 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001016 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001017 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001018 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001019 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001020 return 1;
1021
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001022
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001023 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +00001024 //
1025 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +00001026 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001027 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001028 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001029 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001030 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001031 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001032 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001033 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001034 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001035
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001036 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001037 case AsmToken::EqualEqual:
1038 Kind = MCBinaryExpr::EQ;
1039 return 3;
1040 case AsmToken::ExclaimEqual:
1041 case AsmToken::LessGreater:
1042 Kind = MCBinaryExpr::NE;
1043 return 3;
1044 case AsmToken::Less:
1045 Kind = MCBinaryExpr::LT;
1046 return 3;
1047 case AsmToken::LessEqual:
1048 Kind = MCBinaryExpr::LTE;
1049 return 3;
1050 case AsmToken::Greater:
1051 Kind = MCBinaryExpr::GT;
1052 return 3;
1053 case AsmToken::GreaterEqual:
1054 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001055 return 3;
1056
Jim Grosbachfbe16812011-08-20 16:24:13 +00001057 // Intermediate Precedence: <<, >>
1058 case AsmToken::LessLess:
1059 Kind = MCBinaryExpr::Shl;
1060 return 4;
1061 case AsmToken::GreaterGreater:
1062 Kind = MCBinaryExpr::Shr;
1063 return 4;
1064
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001065 // High Intermediate Precedence: +, -
1066 case AsmToken::Plus:
1067 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001068 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001069 case AsmToken::Minus:
1070 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001071 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001072
Jim Grosbachfbe16812011-08-20 16:24:13 +00001073 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001074 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001075 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001076 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001077 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001078 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001079 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001080 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001081 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001082 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001083 }
1084}
1085
1086
1087/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1088/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001089bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1090 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001091 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001092 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001093 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001094
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001095 // If the next token is lower precedence than we are allowed to eat, return
1096 // successfully with what we ate already.
1097 if (TokPrec < Precedence)
1098 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001099
Sean Callanan79ed1a82010-01-19 20:22:31 +00001100 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001101
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001102 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001103 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001104 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001105
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001106 // If BinOp binds less tightly with RHS than the operator after RHS, let
1107 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001108 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001109 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001110 if (TokPrec < NextTokPrec) {
Kevin Enderby88535dd2013-05-07 21:40:58 +00001111 if (ParseBinOpRHS(TokPrec+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001112 }
1113
Daniel Dunbar475839e2009-06-29 20:37:27 +00001114 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001115 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001116 }
1117}
1118
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001119/// ParseStatement:
1120/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001121/// ::= Label* Directive ...Operands... EndOfStatement
1122/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001123bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001124 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001125 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001126 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001127 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001128 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001129
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001130 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001131 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001132 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001133 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001134 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001135 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001136 if (Lexer.is(AsmToken::Hash))
1137 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001138
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001139 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001140 if (Lexer.is(AsmToken::Integer)) {
1141 LocalLabelVal = getTok().getIntVal();
1142 if (LocalLabelVal < 0) {
1143 if (!TheCondState.Ignore)
1144 return TokError("unexpected token at start of statement");
1145 IDVal = "";
Eli Benderskyed5df012013-01-16 19:32:36 +00001146 } else {
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001147 IDVal = getTok().getString();
1148 Lex(); // Consume the integer token to be used as an identifier token.
1149 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001150 if (!TheCondState.Ignore)
1151 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001152 }
1153 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001154 } else if (Lexer.is(AsmToken::Dot)) {
1155 // Treat '.' as a valid identifier in this context.
1156 Lex();
1157 IDVal = ".";
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001158 } else if (parseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001159 if (!TheCondState.Ignore)
1160 return TokError("unexpected token at start of statement");
1161 IDVal = "";
1162 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001163
Chris Lattner7834fac2010-04-17 18:14:27 +00001164 // Handle conditional assembly here before checking for skipping. We
1165 // have to do this so that .endif isn't skipped in a ".if 0" block for
1166 // example.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001167 StringMap<DirectiveKind>::const_iterator DirKindIt =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001168 DirectiveKindMap.find(IDVal);
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001169 DirectiveKind DirKind =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001170 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1171 DirKindIt->getValue();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001172 switch (DirKind) {
1173 default:
1174 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001175 case DK_IF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001176 return ParseDirectiveIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001177 case DK_IFB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001178 return ParseDirectiveIfb(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001179 case DK_IFNB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001180 return ParseDirectiveIfb(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001181 case DK_IFC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001182 return ParseDirectiveIfc(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001183 case DK_IFNC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001184 return ParseDirectiveIfc(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001185 case DK_IFDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001186 return ParseDirectiveIfdef(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001187 case DK_IFNDEF:
1188 case DK_IFNOTDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001189 return ParseDirectiveIfdef(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001190 case DK_ELSEIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001191 return ParseDirectiveElseIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001192 case DK_ELSE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001193 return ParseDirectiveElse(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001194 case DK_ENDIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001195 return ParseDirectiveEndIf(IDLoc);
1196 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001197
Eli Benderskyed5df012013-01-16 19:32:36 +00001198 // Ignore the statement if in the middle of inactive conditional
1199 // (e.g. ".if 0").
Chad Rosier17feeec2012-10-20 00:47:08 +00001200 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001201 eatToEndOfStatement();
Chris Lattner7834fac2010-04-17 18:14:27 +00001202 return false;
1203 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001204
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001205 // FIXME: Recurse on local labels?
1206
1207 // See what kind of statement we have.
1208 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001209 case AsmToken::Colon: {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001210 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001211
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001212 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001213 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001214
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001215 // Diagnose attempt to use '.' as a label.
1216 if (IDVal == ".")
1217 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1218
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001219 // Diagnose attempt to use a variable as a label.
1220 //
1221 // FIXME: Diagnostics. Note the location of the definition as a label.
1222 // FIXME: This doesn't diagnose assignment to a symbol which has been
1223 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001224 MCSymbol *Sym;
1225 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001226 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001227 else
1228 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001229 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001230 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001231
Daniel Dunbar959fd882009-08-26 22:13:22 +00001232 // Emit the label.
Chad Rosierdeb1bab2013-01-07 20:34:12 +00001233 if (!ParsingInlineAsm)
1234 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001235
Kevin Enderby94c2e852011-12-09 18:09:40 +00001236 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001237 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001238 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001239 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1240 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001241
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001242 // Consume any end of statement token, if present, to avoid spurious
1243 // AddBlankLine calls().
1244 if (Lexer.is(AsmToken::EndOfStatement)) {
1245 Lex();
1246 if (Lexer.is(AsmToken::Eof))
1247 return false;
1248 }
1249
Eli Friedman2128aae2012-10-22 23:58:19 +00001250 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001251 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001252
Daniel Dunbar3f872332009-07-28 16:08:33 +00001253 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001254 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001255 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001256
Nico Weber4c4c7322011-01-28 03:04:41 +00001257 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001258
1259 default: // Normal instruction or directive.
1260 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001261 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001262
1263 // If macros are enabled, check to see if this is a macro instantiation.
Eli Bendersky733c3362013-01-14 18:08:41 +00001264 if (MacrosEnabled())
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001265 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1266 return HandleMacroEntry(M, IDLoc);
1267 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001268
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001269 // Otherwise, we have a normal instruction or directive.
Eli Bendersky6ee13082013-01-15 22:59:42 +00001270
1271 // Directives start with "."
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001272 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00001273 // There are several entities interested in parsing directives:
1274 //
1275 // 1. The target-specific assembly parser. Some directives are target
1276 // specific or may potentially behave differently on certain targets.
1277 // 2. Asm parser extensions. For example, platform-specific parsers
1278 // (like the ELF parser) register themselves as extensions.
1279 // 3. The generic directive parser implemented by this class. These are
1280 // all the directives that behave in a target and platform independent
1281 // manner, or at least have a default behavior that's shared between
1282 // all targets and platforms.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001283
Eli Bendersky6ee13082013-01-15 22:59:42 +00001284 // First query the target-specific parser. It will return 'true' if it
1285 // isn't interested in this directive.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001286 if (!getTargetParser().ParseDirective(ID))
1287 return false;
1288
Eli Bendersky6ee13082013-01-15 22:59:42 +00001289 // Next, check the extention directive map to see if any extension has
1290 // registered itself to parse this directive.
1291 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1292 ExtensionDirectiveMap.lookup(IDVal);
1293 if (Handler.first)
1294 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1295
1296 // Finally, if no one else is interested in this directive, it must be
1297 // generic and familiar to this class.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001298 switch (DirKind) {
1299 default:
1300 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001301 case DK_SET:
1302 case DK_EQU:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001303 return ParseDirectiveSet(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001304 case DK_EQUIV:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001305 return ParseDirectiveSet(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001306 case DK_ASCII:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001307 return ParseDirectiveAscii(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001308 case DK_ASCIZ:
1309 case DK_STRING:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001310 return ParseDirectiveAscii(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001311 case DK_BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001312 return ParseDirectiveValue(1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001313 case DK_SHORT:
1314 case DK_VALUE:
1315 case DK_2BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001316 return ParseDirectiveValue(2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001317 case DK_LONG:
1318 case DK_INT:
1319 case DK_4BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001320 return ParseDirectiveValue(4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001321 case DK_QUAD:
1322 case DK_8BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001323 return ParseDirectiveValue(8);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001324 case DK_SINGLE:
1325 case DK_FLOAT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001326 return ParseDirectiveRealValue(APFloat::IEEEsingle);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001327 case DK_DOUBLE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001328 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001329 case DK_ALIGN: {
Bill Wendling99cb6222013-06-18 07:20:20 +00001330 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001331 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1332 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001333 case DK_ALIGN32: {
Bill Wendling99cb6222013-06-18 07:20:20 +00001334 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001335 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1336 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001337 case DK_BALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001338 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001339 case DK_BALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001340 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001341 case DK_BALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001342 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001343 case DK_P2ALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001344 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001345 case DK_P2ALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001346 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001347 case DK_P2ALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001348 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001349 case DK_ORG:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001350 return ParseDirectiveOrg();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001351 case DK_FILL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001352 return ParseDirectiveFill();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001353 case DK_ZERO:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001354 return ParseDirectiveZero();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001355 case DK_EXTERN:
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001356 eatToEndOfStatement(); // .extern is the default, ignore it.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001357 return false;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001358 case DK_GLOBL:
1359 case DK_GLOBAL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001360 return ParseDirectiveSymbolAttribute(MCSA_Global);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001361 case DK_INDIRECT_SYMBOL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001362 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001363 case DK_LAZY_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001364 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001365 case DK_NO_DEAD_STRIP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001366 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001367 case DK_SYMBOL_RESOLVER:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001368 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001369 case DK_PRIVATE_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001370 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001371 case DK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001372 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001373 case DK_WEAK_DEFINITION:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001374 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001375 case DK_WEAK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001376 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001377 case DK_WEAK_DEF_CAN_BE_HIDDEN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001378 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001379 case DK_COMM:
1380 case DK_COMMON:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001381 return ParseDirectiveComm(/*IsLocal=*/false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001382 case DK_LCOMM:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001383 return ParseDirectiveComm(/*IsLocal=*/true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001384 case DK_ABORT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001385 return ParseDirectiveAbort();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001386 case DK_INCLUDE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001387 return ParseDirectiveInclude();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001388 case DK_INCBIN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001389 return ParseDirectiveIncbin();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001390 case DK_CODE16:
1391 case DK_CODE16GCC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001392 return TokError(Twine(IDVal) + " not supported yet");
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001393 case DK_REPT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001394 return ParseDirectiveRept(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001395 case DK_IRP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001396 return ParseDirectiveIrp(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001397 case DK_IRPC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001398 return ParseDirectiveIrpc(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001399 case DK_ENDR:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001400 return ParseDirectiveEndr(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001401 case DK_BUNDLE_ALIGN_MODE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001402 return ParseDirectiveBundleAlignMode();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001403 case DK_BUNDLE_LOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001404 return ParseDirectiveBundleLock();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001405 case DK_BUNDLE_UNLOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001406 return ParseDirectiveBundleUnlock();
Eli Bendersky6ee13082013-01-15 22:59:42 +00001407 case DK_SLEB128:
1408 return ParseDirectiveLEB128(true);
1409 case DK_ULEB128:
1410 return ParseDirectiveLEB128(false);
1411 case DK_SPACE:
1412 case DK_SKIP:
1413 return ParseDirectiveSpace(IDVal);
1414 case DK_FILE:
1415 return ParseDirectiveFile(IDLoc);
1416 case DK_LINE:
1417 return ParseDirectiveLine();
1418 case DK_LOC:
1419 return ParseDirectiveLoc();
1420 case DK_STABS:
1421 return ParseDirectiveStabs();
1422 case DK_CFI_SECTIONS:
1423 return ParseDirectiveCFISections();
1424 case DK_CFI_STARTPROC:
1425 return ParseDirectiveCFIStartProc();
1426 case DK_CFI_ENDPROC:
1427 return ParseDirectiveCFIEndProc();
1428 case DK_CFI_DEF_CFA:
1429 return ParseDirectiveCFIDefCfa(IDLoc);
1430 case DK_CFI_DEF_CFA_OFFSET:
1431 return ParseDirectiveCFIDefCfaOffset();
1432 case DK_CFI_ADJUST_CFA_OFFSET:
1433 return ParseDirectiveCFIAdjustCfaOffset();
1434 case DK_CFI_DEF_CFA_REGISTER:
1435 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1436 case DK_CFI_OFFSET:
1437 return ParseDirectiveCFIOffset(IDLoc);
1438 case DK_CFI_REL_OFFSET:
1439 return ParseDirectiveCFIRelOffset(IDLoc);
1440 case DK_CFI_PERSONALITY:
1441 return ParseDirectiveCFIPersonalityOrLsda(true);
1442 case DK_CFI_LSDA:
1443 return ParseDirectiveCFIPersonalityOrLsda(false);
1444 case DK_CFI_REMEMBER_STATE:
1445 return ParseDirectiveCFIRememberState();
1446 case DK_CFI_RESTORE_STATE:
1447 return ParseDirectiveCFIRestoreState();
1448 case DK_CFI_SAME_VALUE:
1449 return ParseDirectiveCFISameValue(IDLoc);
1450 case DK_CFI_RESTORE:
1451 return ParseDirectiveCFIRestore(IDLoc);
1452 case DK_CFI_ESCAPE:
1453 return ParseDirectiveCFIEscape();
1454 case DK_CFI_SIGNAL_FRAME:
1455 return ParseDirectiveCFISignalFrame();
1456 case DK_CFI_UNDEFINED:
1457 return ParseDirectiveCFIUndefined(IDLoc);
1458 case DK_CFI_REGISTER:
1459 return ParseDirectiveCFIRegister(IDLoc);
1460 case DK_MACROS_ON:
1461 case DK_MACROS_OFF:
1462 return ParseDirectiveMacrosOnOff(IDVal);
1463 case DK_MACRO:
1464 return ParseDirectiveMacro(IDLoc);
1465 case DK_ENDM:
1466 case DK_ENDMACRO:
1467 return ParseDirectiveEndMacro(IDVal);
1468 case DK_PURGEM:
1469 return ParseDirectivePurgeMacro(IDLoc);
Eli Friedman5d68ec22010-07-19 04:17:25 +00001470 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001471
Jim Grosbach686c0182012-05-01 18:38:27 +00001472 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001473 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001474
Chad Rosier469b1442013-02-12 21:33:51 +00001475 // __asm _emit or __asm __emit
1476 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1477 IDVal == "_EMIT" || IDVal == "__EMIT"))
1478 return ParseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1479
1480 // __asm align
1481 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1482 return ParseDirectiveMSAlign(IDLoc, Info);
Eli Friedman2128aae2012-10-22 23:58:19 +00001483
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001484 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001485
Chris Lattnera7f13542010-05-19 23:34:33 +00001486 // Canonicalize the opcode to lower case.
Eli Benderskyed5df012013-01-16 19:32:36 +00001487 std::string OpcodeStr = IDVal.lower();
Chad Rosier6a020a72012-10-25 20:41:34 +00001488 ParseInstructionInfo IInfo(Info.AsmRewrites);
Eli Benderskyed5df012013-01-16 19:32:36 +00001489 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr,
1490 IDLoc, Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001491 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001492
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001493 // Dump the parsed representation, if requested.
1494 if (getShowParsedOperands()) {
1495 SmallString<256> Str;
1496 raw_svector_ostream OS(Str);
1497 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001498 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001499 if (i != 0)
1500 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001501 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001502 }
1503 OS << "]";
1504
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001505 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001506 }
1507
Kevin Enderby613b7572011-11-01 22:27:22 +00001508 // If we are generating dwarf for assembly source files and the current
1509 // section is the initial text section then generate a .loc directive for
1510 // the instruction.
1511 if (!HadError && getContext().getGenDwarfForAssembly() &&
Peter Collingbournedf39be62013-04-17 21:18:16 +00001512 getContext().getGenDwarfSection() ==
1513 getStreamer().getCurrentSection().first) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001514
Eli Benderskyed5df012013-01-16 19:32:36 +00001515 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
Kevin Enderby938482f2012-11-01 17:31:35 +00001516
Eli Benderskyed5df012013-01-16 19:32:36 +00001517 // If we previously parsed a cpp hash file line comment then make sure the
1518 // current Dwarf File is for the CppHashFilename if not then emit the
1519 // Dwarf File table for it and adjust the line number for the .loc.
Manman Ren9e999ad2013-03-12 20:17:00 +00001520 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
Eli Benderskyed5df012013-01-16 19:32:36 +00001521 getContext().getMCDwarfFiles();
1522 if (CppHashFilename.size() != 0) {
1523 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
Kevin Enderby938482f2012-11-01 17:31:35 +00001524 CppHashFilename)
Eli Benderskyed5df012013-01-16 19:32:36 +00001525 getStreamer().EmitDwarfFileDirective(
1526 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001527
Kevin Enderbya8959492013-06-21 20:51:39 +00001528 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1529 // cache with the different Loc from the call above we save the last
1530 // info we queried here with SrcMgr.FindLineNumber().
1531 unsigned CppHashLocLineNo;
1532 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1533 CppHashLocLineNo = LastQueryLine;
1534 else {
1535 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1536 LastQueryLine = CppHashLocLineNo;
1537 LastQueryIDLoc = CppHashLoc;
1538 LastQueryBuffer = CppHashBuf;
1539 }
Kevin Enderby938482f2012-11-01 17:31:35 +00001540 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
Eli Benderskyed5df012013-01-16 19:32:36 +00001541 }
Kevin Enderby938482f2012-11-01 17:31:35 +00001542
Kevin Enderby613b7572011-11-01 22:27:22 +00001543 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001544 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001545 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001546 StringRef());
1547 }
1548
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001549 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001550 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001551 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001552 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1553 Info.ParsedOperands,
1554 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001555 ParsingInlineAsm);
1556 }
Chris Lattner98986712010-01-14 22:21:20 +00001557
Chris Lattnercbf8a982010-09-11 16:18:25 +00001558 // Don't skip the rest of the line, the instruction parser is responsible for
1559 // that.
1560 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001561}
Chris Lattner9a023f72009-06-24 04:43:34 +00001562
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001563/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1564/// since they may not be able to be tokenized to get to the end of line token.
1565void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001566 if (!Lexer.is(AsmToken::EndOfStatement))
1567 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001568 // Eat EOL.
1569 Lex();
1570}
1571
1572/// ParseCppHashLineFilenameComment as this:
1573/// ::= # number "filename"
1574/// or just as a full line comment if it doesn't have a number and a string.
1575bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1576 Lex(); // Eat the hash token.
1577
1578 if (getLexer().isNot(AsmToken::Integer)) {
1579 // Consume the line since in cases it is not a well-formed line directive,
1580 // as if were simply a full line comment.
1581 EatToEndOfLine();
1582 return false;
1583 }
1584
1585 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001586 Lex();
1587
1588 if (getLexer().isNot(AsmToken::String)) {
1589 EatToEndOfLine();
1590 return false;
1591 }
1592
1593 StringRef Filename = getTok().getString();
1594 // Get rid of the enclosing quotes.
1595 Filename = Filename.substr(1, Filename.size()-2);
1596
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001597 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1598 CppHashLoc = L;
1599 CppHashFilename = Filename;
1600 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001601 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001602
1603 // Ignore any trailing characters, they're just comment.
1604 EatToEndOfLine();
1605 return false;
1606}
1607
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001608/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001609/// for the Filename and LineNo if any in the diagnostic.
1610void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1611 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1612 raw_ostream &OS = errs();
1613
1614 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1615 const SMLoc &DiagLoc = Diag.getLoc();
1616 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1617 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1618
1619 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1620 // before printing the message.
1621 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001622 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001623 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1624 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1625 }
1626
Eric Christopher2318ba12012-12-18 00:30:54 +00001627 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001628 // manager changed or buffer changed (like in a nested include) then just
1629 // print the normal diagnostic using its Filename and LineNo.
1630 if (!Parser->CppHashLineNumber ||
1631 &DiagSrcMgr != &Parser->SrcMgr ||
1632 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001633 if (Parser->SavedDiagHandler)
1634 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1635 else
1636 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001637 return;
1638 }
1639
Eric Christopher2318ba12012-12-18 00:30:54 +00001640 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001641 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1642 // the diagnostic.
1643 const std::string Filename = Parser->CppHashFilename;
1644
1645 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1646 int CppHashLocLineNo =
1647 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1648 int LineNo = Parser->CppHashLineNumber - 1 +
1649 (DiagLocLineNo - CppHashLocLineNo);
1650
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001651 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1652 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001653 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001654 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001655
Benjamin Kramer04a04262011-10-16 10:48:29 +00001656 if (Parser->SavedDiagHandler)
1657 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1658 else
1659 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001660}
1661
Rafael Espindola799aacf2012-08-21 18:29:30 +00001662// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1663// difference being that that function accepts '@' as part of identifiers and
1664// we can't do that. AsmLexer.cpp should probably be changed to handle
1665// '@' as a special case when needed.
1666static bool isIdentifierChar(char c) {
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001667 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1668 c == '.';
Rafael Espindola799aacf2012-08-21 18:29:30 +00001669}
1670
Rafael Espindola761cb062012-06-03 23:57:14 +00001671bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001672 const MCAsmMacroParameters &Parameters,
1673 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001674 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001675 unsigned NParameters = Parameters.size();
1676 if (NParameters != 0 && NParameters != A.size())
1677 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001678
Preston Gurd7b6f2032012-09-19 20:36:12 +00001679 // A macro without parameters is handled differently on Darwin:
1680 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001681 while (!Body.empty()) {
1682 // Scan for the next substitution.
1683 std::size_t End = Body.size(), Pos = 0;
1684 for (; Pos != End; ++Pos) {
1685 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001686 if (!NParameters) {
1687 // This macro has no parameters, look for $0, $1, etc.
1688 if (Body[Pos] != '$' || Pos + 1 == End)
1689 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001690
Rafael Espindola65366442011-06-05 02:43:45 +00001691 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001692 if (Next == '$' || Next == 'n' ||
1693 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola65366442011-06-05 02:43:45 +00001694 break;
1695 } else {
1696 // This macro has parameters, look for \foo, \bar, etc.
1697 if (Body[Pos] == '\\' && Pos + 1 != End)
1698 break;
1699 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001700 }
1701
1702 // Add the prefix.
1703 OS << Body.slice(0, Pos);
1704
1705 // Check if we reached the end.
1706 if (Pos == End)
1707 break;
1708
Rafael Espindola65366442011-06-05 02:43:45 +00001709 if (!NParameters) {
1710 switch (Body[Pos+1]) {
1711 // $$ => $
1712 case '$':
1713 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001714 break;
1715
Rafael Espindola65366442011-06-05 02:43:45 +00001716 // $n => number of arguments
1717 case 'n':
1718 OS << A.size();
1719 break;
1720
1721 // $[0-9] => argument
1722 default: {
1723 // Missing arguments are ignored.
1724 unsigned Index = Body[Pos+1] - '0';
1725 if (Index >= A.size())
1726 break;
1727
1728 // Otherwise substitute with the token values, with spaces eliminated.
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001729 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001730 ie = A[Index].end(); it != ie; ++it)
1731 OS << it->getString();
1732 break;
1733 }
1734 }
1735 Pos += 2;
1736 } else {
1737 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001738 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001739 ++I;
1740
1741 const char *Begin = Body.data() + Pos +1;
1742 StringRef Argument(Begin, I - (Pos +1));
1743 unsigned Index = 0;
1744 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001745 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001746 break;
1747
Preston Gurd7b6f2032012-09-19 20:36:12 +00001748 if (Index == NParameters) {
1749 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1750 Pos += 3;
1751 else {
1752 OS << '\\' << Argument;
1753 Pos = I;
1754 }
1755 } else {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001756 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Preston Gurd7b6f2032012-09-19 20:36:12 +00001757 ie = A[Index].end(); it != ie; ++it)
1758 if (it->getKind() == AsmToken::String)
1759 OS << it->getStringContents();
1760 else
1761 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001762
Preston Gurd7b6f2032012-09-19 20:36:12 +00001763 Pos += 1 + Argument.size();
1764 }
Rafael Espindola65366442011-06-05 02:43:45 +00001765 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001766 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001767 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001768 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001769
Rafael Espindola65366442011-06-05 02:43:45 +00001770 return false;
1771}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001772
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001773MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001774 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001775 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001776 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1777 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001778{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001779}
1780
Preston Gurd7b6f2032012-09-19 20:36:12 +00001781static bool IsOperator(AsmToken::TokenKind kind)
1782{
1783 switch (kind)
1784 {
1785 default:
1786 return false;
1787 case AsmToken::Plus:
1788 case AsmToken::Minus:
1789 case AsmToken::Tilde:
1790 case AsmToken::Slash:
1791 case AsmToken::Star:
1792 case AsmToken::Dot:
1793 case AsmToken::Equal:
1794 case AsmToken::EqualEqual:
1795 case AsmToken::Pipe:
1796 case AsmToken::PipePipe:
1797 case AsmToken::Caret:
1798 case AsmToken::Amp:
1799 case AsmToken::AmpAmp:
1800 case AsmToken::Exclaim:
1801 case AsmToken::ExclaimEqual:
1802 case AsmToken::Percent:
1803 case AsmToken::Less:
1804 case AsmToken::LessEqual:
1805 case AsmToken::LessLess:
1806 case AsmToken::LessGreater:
1807 case AsmToken::Greater:
1808 case AsmToken::GreaterEqual:
1809 case AsmToken::GreaterGreater:
1810 return true;
1811 }
1812}
1813
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001814bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
Preston Gurd7b6f2032012-09-19 20:36:12 +00001815 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001816 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001817 unsigned AddTokens = 0;
1818
1819 // gas accepts arguments separated by whitespace, except on Darwin
1820 if (!IsDarwin)
1821 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001822
1823 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001824 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1825 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001826 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001827 }
1828
1829 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1830 // Spaces and commas cannot be mixed to delimit parameters
1831 if (ArgumentDelimiter == AsmToken::Eof)
1832 ArgumentDelimiter = AsmToken::Comma;
1833 else if (ArgumentDelimiter != AsmToken::Comma) {
1834 Lexer.setSkipSpace(true);
1835 return TokError("expected ' ' for macro argument separator");
1836 }
1837 break;
1838 }
1839
1840 if (Lexer.is(AsmToken::Space)) {
1841 Lex(); // Eat spaces
1842
1843 // Spaces can delimit parameters, but could also be part an expression.
1844 // If the token after a space is an operator, add the token and the next
1845 // one into this argument
1846 if (ArgumentDelimiter == AsmToken::Space ||
1847 ArgumentDelimiter == AsmToken::Eof) {
1848 if (IsOperator(Lexer.getKind())) {
1849 // Check to see whether the token is used as an operator,
1850 // or part of an identifier
Jordan Rose3ebe59c2013-01-07 19:00:49 +00001851 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd7b6f2032012-09-19 20:36:12 +00001852 if (*NextChar == ' ')
1853 AddTokens = 2;
1854 }
1855
1856 if (!AddTokens && ParenLevel == 0) {
1857 if (ArgumentDelimiter == AsmToken::Eof &&
1858 !IsOperator(Lexer.getKind()))
1859 ArgumentDelimiter = AsmToken::Space;
1860 break;
1861 }
1862 }
1863 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001864
1865 // HandleMacroEntry relies on not advancing the lexer here
1866 // to be able to fill in the remaining default parameter values
1867 if (Lexer.is(AsmToken::EndOfStatement))
1868 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001869
1870 // Adjust the current parentheses level.
1871 if (Lexer.is(AsmToken::LParen))
1872 ++ParenLevel;
1873 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1874 --ParenLevel;
1875
1876 // Append the token to the current argument list.
1877 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001878 if (AddTokens)
1879 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001880 Lex();
1881 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001882
1883 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001884 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001885 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001886 return false;
1887}
1888
1889// Parse the macro instantiation arguments.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001890bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001891 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001892 // Argument delimiter is initially unknown. It will be set by
1893 // ParseMacroArgument()
1894 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001895
1896 // Parse two kinds of macro invocations:
1897 // - macros defined without any parameters accept an arbitrary number of them
1898 // - macros defined with parameters accept at most that many of them
1899 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1900 ++Parameter) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001901 MCAsmMacroArgument MA;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001902
Preston Gurd7b6f2032012-09-19 20:36:12 +00001903 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001904 return true;
1905
Preston Gurd6c9176a2012-09-19 20:29:04 +00001906 if (!MA.empty() || !NParameters)
1907 A.push_back(MA);
1908 else if (NParameters) {
1909 if (!M->Parameters[Parameter].second.empty())
1910 A.push_back(M->Parameters[Parameter].second);
1911 }
Jim Grosbach97146442012-07-30 22:44:17 +00001912
Preston Gurd6c9176a2012-09-19 20:29:04 +00001913 // At the end of the statement, fill in remaining arguments that have
1914 // default values. If there aren't any, then the next argument is
1915 // required but missing
1916 if (Lexer.is(AsmToken::EndOfStatement)) {
1917 if (NParameters && Parameter < NParameters - 1) {
1918 if (M->Parameters[Parameter + 1].second.empty())
1919 return TokError("macro argument '" +
1920 Twine(M->Parameters[Parameter + 1].first) +
1921 "' is missing");
1922 else
1923 continue;
1924 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001925 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001926 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001927
1928 if (Lexer.is(AsmToken::Comma))
1929 Lex();
1930 }
1931 return TokError("Too many arguments");
1932}
1933
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001934const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1935 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1936 return (I == MacroMap.end()) ? NULL : I->getValue();
1937}
1938
1939void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1940 MacroMap[Name] = new MCAsmMacro(Macro);
1941}
1942
1943void AsmParser::UndefineMacro(StringRef Name) {
1944 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1945 if (I != MacroMap.end()) {
1946 delete I->getValue();
1947 MacroMap.erase(I);
1948 }
1949}
1950
1951bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001952 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1953 // this, although we should protect against infinite loops.
1954 if (ActiveMacros.size() == 20)
1955 return TokError("macros cannot be nested more than 20 levels deep");
1956
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001957 MCAsmMacroArguments A;
Rafael Espindola8a403d32012-08-08 14:51:03 +00001958 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001959 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001960
Jim Grosbach97146442012-07-30 22:44:17 +00001961 // Remove any trailing empty arguments. Do this after-the-fact as we have
1962 // to keep empty arguments in the middle of the list or positionality
1963 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001964 while (!A.empty() && A.back().empty())
1965 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001966
Rafael Espindola65366442011-06-05 02:43:45 +00001967 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1968 // to hold the macro body with substitutions.
1969 SmallString<256> Buf;
1970 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001971 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001972
Rafael Espindola8a403d32012-08-08 14:51:03 +00001973 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001974 return true;
1975
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001976 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola761cb062012-06-03 23:57:14 +00001977 // instantiation.
1978 OS << ".endmacro\n";
1979
Rafael Espindola65366442011-06-05 02:43:45 +00001980 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001981 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001982
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001983 // Create the macro instantiation object and add to the current macro
1984 // instantiation stack.
1985 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001986 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001987 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001988 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001989 ActiveMacros.push_back(MI);
1990
1991 // Jump to the macro instantiation and prime the lexer.
1992 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1993 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1994 Lex();
1995
1996 return false;
1997}
1998
1999void AsmParser::HandleMacroExit() {
2000 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00002001 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00002002 Lex();
2003
2004 // Pop the instantiation entry.
2005 delete ActiveMacros.back();
2006 ActiveMacros.pop_back();
2007}
2008
Rafael Espindolae71cc862012-01-28 05:57:00 +00002009static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002010 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00002011 case MCExpr::Binary: {
2012 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
2013 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002014 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00002015 case MCExpr::Target:
2016 case MCExpr::Constant:
2017 return false;
2018 case MCExpr::SymbolRef: {
2019 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00002020 if (S.isVariable())
2021 return IsUsedIn(Sym, S.getVariableValue());
2022 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00002023 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002024 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00002025 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002026 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00002027
2028 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002029}
2030
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002031bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
2032 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002033 // FIXME: Use better location, we should use proper tokens.
2034 SMLoc EqualLoc = Lexer.getLoc();
2035
Daniel Dunbar821e3332009-08-31 08:09:28 +00002036 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002037 if (parseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002038 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002039
Rafael Espindolae71cc862012-01-28 05:57:00 +00002040 // Note: we don't count b as used in "a = b". This is to allow
2041 // a = b
2042 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002043
Daniel Dunbar3f872332009-07-28 16:08:33 +00002044 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002045 return TokError("unexpected token in assignment");
2046
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00002047 // Error on assignment to '.'.
2048 if (Name == ".") {
2049 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2050 "(use '.space' or '.org').)"));
2051 }
2052
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002053 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00002054 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002055
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002056 // Validate that the LHS is allowed to be a variable (either it has not been
2057 // used as a symbol, or it is an absolute symbol).
2058 MCSymbol *Sym = getContext().LookupSymbol(Name);
2059 if (Sym) {
2060 // Diagnose assignment to a label.
2061 //
2062 // FIXME: Diagnostics. Note the location of the definition as a label.
2063 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00002064 if (IsUsedIn(Sym, Value))
2065 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2066 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00002067 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00002068 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2069 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00002070 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002071 return Error(EqualLoc, "redefinition of '" + Name + "'");
2072 else if (!Sym->isVariable())
2073 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00002074 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002075 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2076 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002077
2078 // Don't count these checks as uses.
2079 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002080 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002081 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002082
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002083 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002084
2085 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00002086 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002087 if (NoDeadStrip)
2088 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2089
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002090
2091 return false;
2092}
2093
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002094/// parseIdentifier:
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002095/// ::= identifier
2096/// ::= string
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002097bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00002098 // The assembler has relaxed rules for accepting identifiers, in particular we
2099 // allow things like '.globl $foo', which would normally be separate
2100 // tokens. At this level, we have already lexed so we cannot (currently)
2101 // handle this as a context dependent token, instead we detect adjacent tokens
2102 // and return the combined identifier.
2103 if (Lexer.is(AsmToken::Dollar)) {
2104 SMLoc DollarLoc = getLexer().getLoc();
2105
2106 // Consume the dollar sign, and check for a following identifier.
2107 Lex();
2108 if (Lexer.isNot(AsmToken::Identifier))
2109 return true;
2110
2111 // We have a '$' followed by an identifier, make sure they are adjacent.
2112 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2113 return true;
2114
2115 // Construct the joined identifier and consume the token.
2116 Res = StringRef(DollarLoc.getPointer(),
2117 getTok().getIdentifier().size() + 1);
2118 Lex();
2119 return false;
2120 }
2121
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002122 if (Lexer.isNot(AsmToken::Identifier) &&
2123 Lexer.isNot(AsmToken::String))
2124 return true;
2125
Sean Callanan18b83232010-01-19 21:44:56 +00002126 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002127
Sean Callanan79ed1a82010-01-19 20:22:31 +00002128 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002129
2130 return false;
2131}
2132
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002133/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002134/// ::= .equ identifier ',' expression
2135/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002136/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002137bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002138 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002139
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002140 if (parseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002141 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002142
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002143 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002144 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002145 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002146
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002147 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002148}
2149
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002150bool AsmParser::parseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002151 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002152
2153 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002154 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002155 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2156 if (Str[i] != '\\') {
2157 Data += Str[i];
2158 continue;
2159 }
2160
2161 // Recognize escaped characters. Note that this escape semantics currently
2162 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2163 ++i;
2164 if (i == e)
2165 return TokError("unexpected backslash at end of string");
2166
2167 // Recognize octal sequences.
2168 if ((unsigned) (Str[i] - '0') <= 7) {
2169 // Consume up to three octal characters.
2170 unsigned Value = Str[i] - '0';
2171
2172 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2173 ++i;
2174 Value = Value * 8 + (Str[i] - '0');
2175
2176 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2177 ++i;
2178 Value = Value * 8 + (Str[i] - '0');
2179 }
2180 }
2181
2182 if (Value > 255)
2183 return TokError("invalid octal escape sequence (out of range)");
2184
2185 Data += (unsigned char) Value;
2186 continue;
2187 }
2188
2189 // Otherwise recognize individual escapes.
2190 switch (Str[i]) {
2191 default:
2192 // Just reject invalid escape sequences for now.
2193 return TokError("invalid escape sequence (unrecognized character)");
2194
2195 case 'b': Data += '\b'; break;
2196 case 'f': Data += '\f'; break;
2197 case 'n': Data += '\n'; break;
2198 case 'r': Data += '\r'; break;
2199 case 't': Data += '\t'; break;
2200 case '"': Data += '"'; break;
2201 case '\\': Data += '\\'; break;
2202 }
2203 }
2204
2205 return false;
2206}
2207
Daniel Dunbara0d14262009-06-24 23:30:00 +00002208/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002209/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2210bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002211 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002212 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002213
Daniel Dunbara0d14262009-06-24 23:30:00 +00002214 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002215 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002216 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002217
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002218 std::string Data;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002219 if (parseEscapedString(Data))
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002220 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002221
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002222 getStreamer().EmitBytes(Data);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002223 if (ZeroTerminated)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002224 getStreamer().EmitBytes(StringRef("\0", 1));
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002225
Sean Callanan79ed1a82010-01-19 20:22:31 +00002226 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002227
2228 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002229 break;
2230
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002231 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002232 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002233 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002234 }
2235 }
2236
Sean Callanan79ed1a82010-01-19 20:22:31 +00002237 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002238 return false;
2239}
2240
2241/// ParseDirectiveValue
2242/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2243bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002244 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002245 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002246
Daniel Dunbara0d14262009-06-24 23:30:00 +00002247 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002248 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002249 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002250 if (parseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002251 return true;
2252
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002253 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002254 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2255 assert(Size <= 8 && "Invalid size");
2256 uint64_t IntValue = MCE->getValue();
2257 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2258 return Error(ExprLoc, "literal value out of range for directive");
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002259 getStreamer().EmitIntValue(IntValue, Size);
Jim Grosbach254cf032011-06-29 16:05:14 +00002260 } else
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002261 getStreamer().EmitValue(Value, Size);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002262
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002263 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002264 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002265
Daniel Dunbara0d14262009-06-24 23:30:00 +00002266 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002267 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002268 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002269 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002270 }
2271 }
2272
Sean Callanan79ed1a82010-01-19 20:22:31 +00002273 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002274 return false;
2275}
2276
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002277/// ParseDirectiveRealValue
2278/// ::= (.single | .double) [ expression (, expression)* ]
2279bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2280 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002281 checkForValidSection();
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002282
2283 for (;;) {
2284 // We don't truly support arithmetic on floating point expressions, so we
2285 // have to manually parse unary prefixes.
2286 bool IsNeg = false;
2287 if (getLexer().is(AsmToken::Minus)) {
2288 Lex();
2289 IsNeg = true;
2290 } else if (getLexer().is(AsmToken::Plus))
2291 Lex();
2292
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002293 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002294 getLexer().isNot(AsmToken::Real) &&
2295 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002296 return TokError("unexpected token in directive");
2297
2298 // Convert to an APFloat.
2299 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002300 StringRef IDVal = getTok().getString();
2301 if (getLexer().is(AsmToken::Identifier)) {
2302 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2303 Value = APFloat::getInf(Semantics);
2304 else if (!IDVal.compare_lower("nan"))
2305 Value = APFloat::getNaN(Semantics, false, ~0);
2306 else
2307 return TokError("invalid floating point literal");
2308 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002309 APFloat::opInvalidOp)
2310 return TokError("invalid floating point literal");
2311 if (IsNeg)
2312 Value.changeSign();
2313
2314 // Consume the numeric token.
2315 Lex();
2316
2317 // Emit the value as an integer.
2318 APInt AsInt = Value.bitcastToAPInt();
2319 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002320 AsInt.getBitWidth() / 8);
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002321
2322 if (getLexer().is(AsmToken::EndOfStatement))
2323 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002324
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002325 if (getLexer().isNot(AsmToken::Comma))
2326 return TokError("unexpected token in directive");
2327 Lex();
2328 }
2329 }
2330
2331 Lex();
2332 return false;
2333}
2334
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002335/// ParseDirectiveZero
2336/// ::= .zero expression
2337bool AsmParser::ParseDirectiveZero() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002338 checkForValidSection();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002339
2340 int64_t NumBytes;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002341 if (parseAbsoluteExpression(NumBytes))
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002342 return true;
2343
Rafael Espindolae452b172010-10-05 19:42:57 +00002344 int64_t Val = 0;
2345 if (getLexer().is(AsmToken::Comma)) {
2346 Lex();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002347 if (parseAbsoluteExpression(Val))
Rafael Espindolae452b172010-10-05 19:42:57 +00002348 return true;
2349 }
2350
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002351 if (getLexer().isNot(AsmToken::EndOfStatement))
2352 return TokError("unexpected token in '.zero' directive");
2353
2354 Lex();
2355
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002356 getStreamer().EmitFill(NumBytes, Val);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002357
2358 return false;
2359}
2360
Daniel Dunbara0d14262009-06-24 23:30:00 +00002361/// ParseDirectiveFill
2362/// ::= .fill expression , expression , expression
2363bool AsmParser::ParseDirectiveFill() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002364 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002365
Daniel Dunbara0d14262009-06-24 23:30:00 +00002366 int64_t NumValues;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002367 if (parseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002368 return true;
2369
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002370 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002371 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002372 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002373
Daniel Dunbara0d14262009-06-24 23:30:00 +00002374 int64_t FillSize;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002375 if (parseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002376 return true;
2377
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002378 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002379 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002380 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002381
Daniel Dunbara0d14262009-06-24 23:30:00 +00002382 int64_t FillExpr;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002383 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002384 return true;
2385
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002386 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002387 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002388
Sean Callanan79ed1a82010-01-19 20:22:31 +00002389 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002390
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002391 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2392 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002393
2394 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00002395 getStreamer().EmitIntValue(FillExpr, FillSize);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002396
2397 return false;
2398}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002399
2400/// ParseDirectiveOrg
2401/// ::= .org expression [ , expression ]
2402bool AsmParser::ParseDirectiveOrg() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002403 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002404
Daniel Dunbar821e3332009-08-31 08:09:28 +00002405 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002406 SMLoc Loc = getTok().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002407 if (parseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002408 return true;
2409
2410 // Parse optional fill expression.
2411 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002412 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2413 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002414 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002415 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002416
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002417 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002418 return true;
2419
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002420 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002421 return TokError("unexpected token in '.org' directive");
2422 }
2423
Sean Callanan79ed1a82010-01-19 20:22:31 +00002424 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002425
Jim Grosbachebd4c052012-01-27 00:37:08 +00002426 // Only limited forms of relocatable expressions are accepted here, it
2427 // has to be relative to the current section. The streamer will return
2428 // 'true' if the expression wasn't evaluatable.
2429 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2430 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002431
2432 return false;
2433}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002434
2435/// ParseDirectiveAlign
2436/// ::= {.align, ...} expression [ , expression [ , expression ]]
2437bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002438 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002439
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002440 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002441 int64_t Alignment;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002442 if (parseAbsoluteExpression(Alignment))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002443 return true;
2444
2445 SMLoc MaxBytesLoc;
2446 bool HasFillExpr = false;
2447 int64_t FillExpr = 0;
2448 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002449 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2450 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002451 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002452 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002453
2454 // The fill expression can be omitted while specifying a maximum number of
2455 // alignment bytes, e.g:
2456 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002457 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002458 HasFillExpr = true;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002459 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002460 return true;
2461 }
2462
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002463 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2464 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002465 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002466 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002467
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002468 MaxBytesLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002469 if (parseAbsoluteExpression(MaxBytesToFill))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002470 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002471
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002472 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002473 return TokError("unexpected token in directive");
2474 }
2475 }
2476
Sean Callanan79ed1a82010-01-19 20:22:31 +00002477 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002478
Daniel Dunbar648ac512010-05-17 21:54:30 +00002479 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002480 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002481
2482 // Compute alignment in bytes.
2483 if (IsPow2) {
2484 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002485 if (Alignment >= 32) {
2486 Error(AlignmentLoc, "invalid alignment value");
2487 Alignment = 31;
2488 }
2489
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002490 Alignment = 1ULL << Alignment;
Benjamin Kramer8a89cf22013-02-16 15:00:16 +00002491 } else {
2492 // Reject alignments that aren't a power of two, for gas compatibility.
2493 if (!isPowerOf2_64(Alignment))
2494 Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002495 }
2496
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002497 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002498 if (MaxBytesLoc.isValid()) {
2499 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002500 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2501 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002502 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002503 }
2504
2505 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002506 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2507 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002508 MaxBytesToFill = 0;
2509 }
2510 }
2511
Daniel Dunbar648ac512010-05-17 21:54:30 +00002512 // Check whether we should use optimal code alignment for this .align
2513 // directive.
Peter Collingbournedf39be62013-04-17 21:18:16 +00002514 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002515 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2516 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002517 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002518 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002519 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002520 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2521 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002522 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002523
2524 return false;
2525}
2526
Eli Bendersky6ee13082013-01-15 22:59:42 +00002527/// ParseDirectiveFile
2528/// ::= .file [number] filename
2529/// ::= .file number directory filename
2530bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2531 // FIXME: I'm not sure what this is.
2532 int64_t FileNumber = -1;
2533 SMLoc FileNumberLoc = getLexer().getLoc();
2534 if (getLexer().is(AsmToken::Integer)) {
2535 FileNumber = getTok().getIntVal();
2536 Lex();
2537
2538 if (FileNumber < 1)
2539 return TokError("file number less than one");
2540 }
2541
2542 if (getLexer().isNot(AsmToken::String))
2543 return TokError("unexpected token in '.file' directive");
2544
2545 // Usually the directory and filename together, otherwise just the directory.
2546 StringRef Path = getTok().getString();
2547 Path = Path.substr(1, Path.size()-2);
2548 Lex();
2549
2550 StringRef Directory;
2551 StringRef Filename;
2552 if (getLexer().is(AsmToken::String)) {
2553 if (FileNumber == -1)
2554 return TokError("explicit path specified, but no file number");
2555 Filename = getTok().getString();
2556 Filename = Filename.substr(1, Filename.size()-2);
2557 Directory = Path;
2558 Lex();
2559 } else {
2560 Filename = Path;
2561 }
2562
2563 if (getLexer().isNot(AsmToken::EndOfStatement))
2564 return TokError("unexpected token in '.file' directive");
2565
2566 if (FileNumber == -1)
2567 getStreamer().EmitFileDirective(Filename);
2568 else {
2569 if (getContext().getGenDwarfForAssembly() == true)
2570 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2571 "used to generate dwarf debug info for assembly code");
2572
2573 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2574 Error(FileNumberLoc, "file number already allocated");
2575 }
2576
2577 return false;
2578}
2579
2580/// ParseDirectiveLine
2581/// ::= .line [number]
2582bool AsmParser::ParseDirectiveLine() {
2583 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2584 if (getLexer().isNot(AsmToken::Integer))
2585 return TokError("unexpected token in '.line' directive");
2586
2587 int64_t LineNumber = getTok().getIntVal();
2588 (void) LineNumber;
2589 Lex();
2590
2591 // FIXME: Do something with the .line.
2592 }
2593
2594 if (getLexer().isNot(AsmToken::EndOfStatement))
2595 return TokError("unexpected token in '.line' directive");
2596
2597 return false;
2598}
2599
2600/// ParseDirectiveLoc
2601/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2602/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2603/// The first number is a file number, must have been previously assigned with
2604/// a .file directive, the second number is the line number and optionally the
2605/// third number is a column position (zero if not specified). The remaining
2606/// optional items are .loc sub-directives.
2607bool AsmParser::ParseDirectiveLoc() {
2608 if (getLexer().isNot(AsmToken::Integer))
2609 return TokError("unexpected token in '.loc' directive");
2610 int64_t FileNumber = getTok().getIntVal();
2611 if (FileNumber < 1)
2612 return TokError("file number less than one in '.loc' directive");
2613 if (!getContext().isValidDwarfFileNumber(FileNumber))
2614 return TokError("unassigned file number in '.loc' directive");
2615 Lex();
2616
2617 int64_t LineNumber = 0;
2618 if (getLexer().is(AsmToken::Integer)) {
2619 LineNumber = getTok().getIntVal();
2620 if (LineNumber < 1)
2621 return TokError("line number less than one in '.loc' directive");
2622 Lex();
2623 }
2624
2625 int64_t ColumnPos = 0;
2626 if (getLexer().is(AsmToken::Integer)) {
2627 ColumnPos = getTok().getIntVal();
2628 if (ColumnPos < 0)
2629 return TokError("column position less than zero in '.loc' directive");
2630 Lex();
2631 }
2632
2633 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2634 unsigned Isa = 0;
2635 int64_t Discriminator = 0;
2636 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2637 for (;;) {
2638 if (getLexer().is(AsmToken::EndOfStatement))
2639 break;
2640
2641 StringRef Name;
2642 SMLoc Loc = getTok().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002643 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002644 return TokError("unexpected token in '.loc' directive");
2645
2646 if (Name == "basic_block")
2647 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2648 else if (Name == "prologue_end")
2649 Flags |= DWARF2_FLAG_PROLOGUE_END;
2650 else if (Name == "epilogue_begin")
2651 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2652 else if (Name == "is_stmt") {
2653 Loc = getTok().getLoc();
2654 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002655 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002656 return true;
2657 // The expression must be the constant 0 or 1.
2658 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2659 int Value = MCE->getValue();
2660 if (Value == 0)
2661 Flags &= ~DWARF2_FLAG_IS_STMT;
2662 else if (Value == 1)
2663 Flags |= DWARF2_FLAG_IS_STMT;
2664 else
2665 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperefa703d2013-04-22 04:22:40 +00002666 } else {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002667 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2668 }
Craig Topperefa703d2013-04-22 04:22:40 +00002669 } else if (Name == "isa") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002670 Loc = getTok().getLoc();
2671 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002672 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002673 return true;
2674 // The expression must be a constant greater or equal to 0.
2675 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2676 int Value = MCE->getValue();
2677 if (Value < 0)
2678 return Error(Loc, "isa number less than zero");
2679 Isa = Value;
Craig Topperefa703d2013-04-22 04:22:40 +00002680 } else {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002681 return Error(Loc, "isa number not a constant value");
2682 }
Craig Topperefa703d2013-04-22 04:22:40 +00002683 } else if (Name == "discriminator") {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002684 if (parseAbsoluteExpression(Discriminator))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002685 return true;
Craig Topperefa703d2013-04-22 04:22:40 +00002686 } else {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002687 return Error(Loc, "unknown sub-directive in '.loc' directive");
2688 }
2689
2690 if (getLexer().is(AsmToken::EndOfStatement))
2691 break;
2692 }
2693 }
2694
2695 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2696 Isa, Discriminator, StringRef());
2697
2698 return false;
2699}
2700
2701/// ParseDirectiveStabs
2702/// ::= .stabs string, number, number, number
2703bool AsmParser::ParseDirectiveStabs() {
2704 return TokError("unsupported directive '.stabs'");
2705}
2706
2707/// ParseDirectiveCFISections
2708/// ::= .cfi_sections section [, section]
2709bool AsmParser::ParseDirectiveCFISections() {
2710 StringRef Name;
2711 bool EH = false;
2712 bool Debug = false;
2713
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002714 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002715 return TokError("Expected an identifier");
2716
2717 if (Name == ".eh_frame")
2718 EH = true;
2719 else if (Name == ".debug_frame")
2720 Debug = true;
2721
2722 if (getLexer().is(AsmToken::Comma)) {
2723 Lex();
2724
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002725 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002726 return TokError("Expected an identifier");
2727
2728 if (Name == ".eh_frame")
2729 EH = true;
2730 else if (Name == ".debug_frame")
2731 Debug = true;
2732 }
2733
2734 getStreamer().EmitCFISections(EH, Debug);
2735 return false;
2736}
2737
2738/// ParseDirectiveCFIStartProc
2739/// ::= .cfi_startproc
2740bool AsmParser::ParseDirectiveCFIStartProc() {
2741 getStreamer().EmitCFIStartProc();
2742 return false;
2743}
2744
2745/// ParseDirectiveCFIEndProc
2746/// ::= .cfi_endproc
2747bool AsmParser::ParseDirectiveCFIEndProc() {
2748 getStreamer().EmitCFIEndProc();
2749 return false;
2750}
2751
2752/// ParseRegisterOrRegisterNumber - parse register name or number.
2753bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2754 SMLoc DirectiveLoc) {
2755 unsigned RegNo;
2756
2757 if (getLexer().isNot(AsmToken::Integer)) {
2758 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2759 return true;
Bill Wendling99cb6222013-06-18 07:20:20 +00002760 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky6ee13082013-01-15 22:59:42 +00002761 } else
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002762 return parseAbsoluteExpression(Register);
Eli Bendersky6ee13082013-01-15 22:59:42 +00002763
2764 return false;
2765}
2766
2767/// ParseDirectiveCFIDefCfa
2768/// ::= .cfi_def_cfa register, offset
2769bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2770 int64_t Register = 0;
2771 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2772 return true;
2773
2774 if (getLexer().isNot(AsmToken::Comma))
2775 return TokError("unexpected token in directive");
2776 Lex();
2777
2778 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002779 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002780 return true;
2781
2782 getStreamer().EmitCFIDefCfa(Register, Offset);
2783 return false;
2784}
2785
2786/// ParseDirectiveCFIDefCfaOffset
2787/// ::= .cfi_def_cfa_offset offset
2788bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
2789 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002790 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002791 return true;
2792
2793 getStreamer().EmitCFIDefCfaOffset(Offset);
2794 return false;
2795}
2796
2797/// ParseDirectiveCFIRegister
2798/// ::= .cfi_register register, register
2799bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2800 int64_t Register1 = 0;
2801 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2802 return true;
2803
2804 if (getLexer().isNot(AsmToken::Comma))
2805 return TokError("unexpected token in directive");
2806 Lex();
2807
2808 int64_t Register2 = 0;
2809 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2810 return true;
2811
2812 getStreamer().EmitCFIRegister(Register1, Register2);
2813 return false;
2814}
2815
2816/// ParseDirectiveCFIAdjustCfaOffset
2817/// ::= .cfi_adjust_cfa_offset adjustment
2818bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
2819 int64_t Adjustment = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002820 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002821 return true;
2822
2823 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2824 return false;
2825}
2826
2827/// ParseDirectiveCFIDefCfaRegister
2828/// ::= .cfi_def_cfa_register register
2829bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2830 int64_t Register = 0;
2831 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2832 return true;
2833
2834 getStreamer().EmitCFIDefCfaRegister(Register);
2835 return false;
2836}
2837
2838/// ParseDirectiveCFIOffset
2839/// ::= .cfi_offset register, offset
2840bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2841 int64_t Register = 0;
2842 int64_t Offset = 0;
2843
2844 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2845 return true;
2846
2847 if (getLexer().isNot(AsmToken::Comma))
2848 return TokError("unexpected token in directive");
2849 Lex();
2850
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002851 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002852 return true;
2853
2854 getStreamer().EmitCFIOffset(Register, Offset);
2855 return false;
2856}
2857
2858/// ParseDirectiveCFIRelOffset
2859/// ::= .cfi_rel_offset register, offset
2860bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2861 int64_t Register = 0;
2862
2863 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2864 return true;
2865
2866 if (getLexer().isNot(AsmToken::Comma))
2867 return TokError("unexpected token in directive");
2868 Lex();
2869
2870 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002871 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002872 return true;
2873
2874 getStreamer().EmitCFIRelOffset(Register, Offset);
2875 return false;
2876}
2877
2878static bool isValidEncoding(int64_t Encoding) {
2879 if (Encoding & ~0xff)
2880 return false;
2881
2882 if (Encoding == dwarf::DW_EH_PE_omit)
2883 return true;
2884
2885 const unsigned Format = Encoding & 0xf;
2886 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2887 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2888 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2889 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2890 return false;
2891
2892 const unsigned Application = Encoding & 0x70;
2893 if (Application != dwarf::DW_EH_PE_absptr &&
2894 Application != dwarf::DW_EH_PE_pcrel)
2895 return false;
2896
2897 return true;
2898}
2899
2900/// ParseDirectiveCFIPersonalityOrLsda
2901/// IsPersonality true for cfi_personality, false for cfi_lsda
2902/// ::= .cfi_personality encoding, [symbol_name]
2903/// ::= .cfi_lsda encoding, [symbol_name]
2904bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2905 int64_t Encoding = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002906 if (parseAbsoluteExpression(Encoding))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002907 return true;
2908 if (Encoding == dwarf::DW_EH_PE_omit)
2909 return false;
2910
2911 if (!isValidEncoding(Encoding))
2912 return TokError("unsupported encoding.");
2913
2914 if (getLexer().isNot(AsmToken::Comma))
2915 return TokError("unexpected token in directive");
2916 Lex();
2917
2918 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002919 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002920 return TokError("expected identifier in directive");
2921
2922 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2923
2924 if (IsPersonality)
2925 getStreamer().EmitCFIPersonality(Sym, Encoding);
2926 else
2927 getStreamer().EmitCFILsda(Sym, Encoding);
2928 return false;
2929}
2930
2931/// ParseDirectiveCFIRememberState
2932/// ::= .cfi_remember_state
2933bool AsmParser::ParseDirectiveCFIRememberState() {
2934 getStreamer().EmitCFIRememberState();
2935 return false;
2936}
2937
2938/// ParseDirectiveCFIRestoreState
2939/// ::= .cfi_remember_state
2940bool AsmParser::ParseDirectiveCFIRestoreState() {
2941 getStreamer().EmitCFIRestoreState();
2942 return false;
2943}
2944
2945/// ParseDirectiveCFISameValue
2946/// ::= .cfi_same_value register
2947bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2948 int64_t Register = 0;
2949
2950 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2951 return true;
2952
2953 getStreamer().EmitCFISameValue(Register);
2954 return false;
2955}
2956
2957/// ParseDirectiveCFIRestore
2958/// ::= .cfi_restore register
2959bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2960 int64_t Register = 0;
2961 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2962 return true;
2963
2964 getStreamer().EmitCFIRestore(Register);
2965 return false;
2966}
2967
2968/// ParseDirectiveCFIEscape
2969/// ::= .cfi_escape expression[,...]
2970bool AsmParser::ParseDirectiveCFIEscape() {
2971 std::string Values;
2972 int64_t CurrValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002973 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002974 return true;
2975
2976 Values.push_back((uint8_t)CurrValue);
2977
2978 while (getLexer().is(AsmToken::Comma)) {
2979 Lex();
2980
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002981 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002982 return true;
2983
2984 Values.push_back((uint8_t)CurrValue);
2985 }
2986
2987 getStreamer().EmitCFIEscape(Values);
2988 return false;
2989}
2990
2991/// ParseDirectiveCFISignalFrame
2992/// ::= .cfi_signal_frame
2993bool AsmParser::ParseDirectiveCFISignalFrame() {
2994 if (getLexer().isNot(AsmToken::EndOfStatement))
2995 return Error(getLexer().getLoc(),
2996 "unexpected token in '.cfi_signal_frame'");
2997
2998 getStreamer().EmitCFISignalFrame();
2999 return false;
3000}
3001
3002/// ParseDirectiveCFIUndefined
3003/// ::= .cfi_undefined register
3004bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3005 int64_t Register = 0;
3006
3007 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3008 return true;
3009
3010 getStreamer().EmitCFIUndefined(Register);
3011 return false;
3012}
3013
3014/// ParseDirectiveMacrosOnOff
3015/// ::= .macros_on
3016/// ::= .macros_off
3017bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
3018 if (getLexer().isNot(AsmToken::EndOfStatement))
3019 return Error(getLexer().getLoc(),
3020 "unexpected token in '" + Directive + "' directive");
3021
3022 SetMacrosEnabled(Directive == ".macros_on");
3023 return false;
3024}
3025
3026/// ParseDirectiveMacro
3027/// ::= .macro name [parameters]
3028bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
3029 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003030 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003031 return TokError("expected identifier in '.macro' directive");
3032
3033 MCAsmMacroParameters Parameters;
3034 // Argument delimiter is initially unknown. It will be set by
3035 // ParseMacroArgument()
3036 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3037 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3038 for (;;) {
3039 MCAsmMacroParameter Parameter;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003040 if (parseIdentifier(Parameter.first))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003041 return TokError("expected identifier in '.macro' directive");
3042
3043 if (getLexer().is(AsmToken::Equal)) {
3044 Lex();
3045 if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3046 return true;
3047 }
3048
3049 Parameters.push_back(Parameter);
3050
3051 if (getLexer().is(AsmToken::Comma))
3052 Lex();
3053 else if (getLexer().is(AsmToken::EndOfStatement))
3054 break;
3055 }
3056 }
3057
3058 // Eat the end of statement.
3059 Lex();
3060
3061 AsmToken EndToken, StartToken = getTok();
3062
3063 // Lex the macro definition.
3064 for (;;) {
3065 // Check whether we have reached the end of the file.
3066 if (getLexer().is(AsmToken::Eof))
3067 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3068
3069 // Otherwise, check whether we have reach the .endmacro.
3070 if (getLexer().is(AsmToken::Identifier) &&
3071 (getTok().getIdentifier() == ".endm" ||
3072 getTok().getIdentifier() == ".endmacro")) {
3073 EndToken = getTok();
3074 Lex();
3075 if (getLexer().isNot(AsmToken::EndOfStatement))
3076 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3077 "' directive");
3078 break;
3079 }
3080
3081 // Otherwise, scan til the end of the statement.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003082 eatToEndOfStatement();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003083 }
3084
3085 if (LookupMacro(Name)) {
3086 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3087 }
3088
3089 const char *BodyStart = StartToken.getLoc().getPointer();
3090 const char *BodyEnd = EndToken.getLoc().getPointer();
3091 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Kevin Enderby221514e2013-01-22 21:44:53 +00003092 CheckForBadMacro(DirectiveLoc, Name, Body, Parameters);
Eli Bendersky6ee13082013-01-15 22:59:42 +00003093 DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3094 return false;
3095}
3096
Kevin Enderby221514e2013-01-22 21:44:53 +00003097/// CheckForBadMacro
3098///
3099/// With the support added for named parameters there may be code out there that
3100/// is transitioning from positional parameters. In versions of gas that did
3101/// not support named parameters they would be ignored on the macro defintion.
3102/// But to support both styles of parameters this is not possible so if a macro
3103/// defintion has named parameters but does not use them and has what appears
3104/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3105/// warning that the positional parameter found in body which have no effect.
3106/// Hoping the developer will either remove the named parameters from the macro
3107/// definiton so the positional parameters get used if that was what was
3108/// intended or change the macro to use the named parameters. It is possible
3109/// this warning will trigger when the none of the named parameters are used
3110/// and the strings like $1 are infact to simply to be passed trough unchanged.
3111void AsmParser::CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3112 StringRef Body,
3113 MCAsmMacroParameters Parameters) {
3114 // If this macro is not defined with named parameters the warning we are
3115 // checking for here doesn't apply.
3116 unsigned NParameters = Parameters.size();
3117 if (NParameters == 0)
3118 return;
3119
3120 bool NamedParametersFound = false;
3121 bool PositionalParametersFound = false;
3122
3123 // Look at the body of the macro for use of both the named parameters and what
3124 // are likely to be positional parameters. This is what expandMacro() is
3125 // doing when it finds the parameters in the body.
3126 while (!Body.empty()) {
3127 // Scan for the next possible parameter.
3128 std::size_t End = Body.size(), Pos = 0;
3129 for (; Pos != End; ++Pos) {
3130 // Check for a substitution or escape.
3131 // This macro is defined with parameters, look for \foo, \bar, etc.
3132 if (Body[Pos] == '\\' && Pos + 1 != End)
3133 break;
3134
3135 // This macro should have parameters, but look for $0, $1, ..., $n too.
3136 if (Body[Pos] != '$' || Pos + 1 == End)
3137 continue;
3138 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00003139 if (Next == '$' || Next == 'n' ||
3140 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby221514e2013-01-22 21:44:53 +00003141 break;
3142 }
3143
3144 // Check if we reached the end.
3145 if (Pos == End)
3146 break;
3147
3148 if (Body[Pos] == '$') {
3149 switch (Body[Pos+1]) {
3150 // $$ => $
3151 case '$':
3152 break;
3153
3154 // $n => number of arguments
3155 case 'n':
3156 PositionalParametersFound = true;
3157 break;
3158
3159 // $[0-9] => argument
3160 default: {
3161 PositionalParametersFound = true;
3162 break;
3163 }
3164 }
3165 Pos += 2;
3166 } else {
3167 unsigned I = Pos + 1;
3168 while (isIdentifierChar(Body[I]) && I + 1 != End)
3169 ++I;
3170
3171 const char *Begin = Body.data() + Pos +1;
3172 StringRef Argument(Begin, I - (Pos +1));
3173 unsigned Index = 0;
3174 for (; Index < NParameters; ++Index)
3175 if (Parameters[Index].first == Argument)
3176 break;
3177
3178 if (Index == NParameters) {
3179 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
3180 Pos += 3;
3181 else {
3182 Pos = I;
3183 }
3184 } else {
3185 NamedParametersFound = true;
3186 Pos += 1 + Argument.size();
3187 }
3188 }
3189 // Update the scan point.
3190 Body = Body.substr(Pos);
3191 }
3192
3193 if (!NamedParametersFound && PositionalParametersFound)
3194 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3195 "used in macro body, possible positional parameter "
3196 "found in body which will have no effect");
3197}
3198
Eli Bendersky6ee13082013-01-15 22:59:42 +00003199/// ParseDirectiveEndMacro
3200/// ::= .endm
3201/// ::= .endmacro
3202bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
3203 if (getLexer().isNot(AsmToken::EndOfStatement))
3204 return TokError("unexpected token in '" + Directive + "' directive");
3205
3206 // If we are inside a macro instantiation, terminate the current
3207 // instantiation.
3208 if (InsideMacroInstantiation()) {
3209 HandleMacroExit();
3210 return false;
3211 }
3212
3213 // Otherwise, this .endmacro is a stray entry in the file; well formed
3214 // .endmacro directives are handled during the macro definition parsing.
3215 return TokError("unexpected '" + Directive + "' in file, "
3216 "no current macro definition");
3217}
3218
3219/// ParseDirectivePurgeMacro
3220/// ::= .purgem
3221bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3222 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003223 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003224 return TokError("expected identifier in '.purgem' directive");
3225
3226 if (getLexer().isNot(AsmToken::EndOfStatement))
3227 return TokError("unexpected token in '.purgem' directive");
3228
3229 if (!LookupMacro(Name))
3230 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3231
3232 UndefineMacro(Name);
3233 return false;
3234}
Eli Bendersky4766ef42012-12-20 19:05:53 +00003235
3236/// ParseDirectiveBundleAlignMode
3237/// ::= {.bundle_align_mode} expression
3238bool AsmParser::ParseDirectiveBundleAlignMode() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003239 checkForValidSection();
Eli Bendersky4766ef42012-12-20 19:05:53 +00003240
3241 // Expect a single argument: an expression that evaluates to a constant
3242 // in the inclusive range 0-30.
3243 SMLoc ExprLoc = getLexer().getLoc();
3244 int64_t AlignSizePow2;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003245 if (parseAbsoluteExpression(AlignSizePow2))
Eli Bendersky4766ef42012-12-20 19:05:53 +00003246 return true;
3247 else if (getLexer().isNot(AsmToken::EndOfStatement))
3248 return TokError("unexpected token after expression in"
3249 " '.bundle_align_mode' directive");
3250 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3251 return Error(ExprLoc,
3252 "invalid bundle alignment size (expected between 0 and 30)");
3253
3254 Lex();
3255
3256 // Because of AlignSizePow2's verified range we can safely truncate it to
3257 // unsigned.
3258 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3259 return false;
3260}
3261
3262/// ParseDirectiveBundleLock
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003263/// ::= {.bundle_lock} [align_to_end]
Eli Bendersky4766ef42012-12-20 19:05:53 +00003264bool AsmParser::ParseDirectiveBundleLock() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003265 checkForValidSection();
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003266 bool AlignToEnd = false;
Eli Bendersky4766ef42012-12-20 19:05:53 +00003267
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003268 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3269 StringRef Option;
3270 SMLoc Loc = getTok().getLoc();
3271 const char *kInvalidOptionError =
3272 "invalid option for '.bundle_lock' directive";
3273
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003274 if (parseIdentifier(Option))
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003275 return Error(Loc, kInvalidOptionError);
3276
3277 if (Option != "align_to_end")
3278 return Error(Loc, kInvalidOptionError);
3279 else if (getLexer().isNot(AsmToken::EndOfStatement))
3280 return Error(Loc,
3281 "unexpected token after '.bundle_lock' directive option");
3282 AlignToEnd = true;
3283 }
3284
Eli Bendersky4766ef42012-12-20 19:05:53 +00003285 Lex();
3286
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003287 getStreamer().EmitBundleLock(AlignToEnd);
Eli Bendersky4766ef42012-12-20 19:05:53 +00003288 return false;
3289}
3290
3291/// ParseDirectiveBundleLock
3292/// ::= {.bundle_lock}
3293bool AsmParser::ParseDirectiveBundleUnlock() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003294 checkForValidSection();
Eli Bendersky4766ef42012-12-20 19:05:53 +00003295
3296 if (getLexer().isNot(AsmToken::EndOfStatement))
3297 return TokError("unexpected token in '.bundle_unlock' directive");
3298 Lex();
3299
3300 getStreamer().EmitBundleUnlock();
3301 return false;
3302}
3303
Eli Bendersky6ee13082013-01-15 22:59:42 +00003304/// ParseDirectiveSpace
3305/// ::= (.skip | .space) expression [ , expression ]
3306bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003307 checkForValidSection();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003308
3309 int64_t NumBytes;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003310 if (parseAbsoluteExpression(NumBytes))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003311 return true;
3312
3313 int64_t FillExpr = 0;
3314 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3315 if (getLexer().isNot(AsmToken::Comma))
3316 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3317 Lex();
3318
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003319 if (parseAbsoluteExpression(FillExpr))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003320 return true;
3321
3322 if (getLexer().isNot(AsmToken::EndOfStatement))
3323 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3324 }
3325
3326 Lex();
3327
3328 if (NumBytes <= 0)
3329 return TokError("invalid number of bytes in '" +
3330 Twine(IDVal) + "' directive");
3331
3332 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Rafael Espindolaa3863ea2013-07-02 15:49:13 +00003333 getStreamer().EmitFill(NumBytes, FillExpr);
Eli Bendersky6ee13082013-01-15 22:59:42 +00003334
3335 return false;
3336}
3337
3338/// ParseDirectiveLEB128
3339/// ::= (.sleb128 | .uleb128) expression
3340bool AsmParser::ParseDirectiveLEB128(bool Signed) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003341 checkForValidSection();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003342 const MCExpr *Value;
3343
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003344 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003345 return true;
3346
3347 if (getLexer().isNot(AsmToken::EndOfStatement))
3348 return TokError("unexpected token in directive");
3349
3350 if (Signed)
3351 getStreamer().EmitSLEB128Value(Value);
3352 else
3353 getStreamer().EmitULEB128Value(Value);
3354
3355 return false;
3356}
3357
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003358/// ParseDirectiveSymbolAttribute
3359/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00003360bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003361 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003362 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003363 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00003364 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003365
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003366 if (parseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00003367 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003368
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003369 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003370
Jim Grosbach10ec6502011-09-15 17:56:49 +00003371 // Assembler local symbols don't make any sense here. Complain loudly.
3372 if (Sym->isTemporary())
3373 return Error(Loc, "non-local symbol required in directive");
3374
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003375 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003376
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003377 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003378 break;
3379
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003380 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003381 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003382 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003383 }
3384 }
3385
Sean Callanan79ed1a82010-01-19 20:22:31 +00003386 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00003387 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003388}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003389
3390/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00003391/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3392bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003393 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00003394
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003395 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003396 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003397 if (parseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003398 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003399
Daniel Dunbar76c4d762009-07-31 21:55:09 +00003400 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003401 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003402
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003403 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003404 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003405 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003406
3407 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003408 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003409 if (parseAbsoluteExpression(Size))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003410 return true;
3411
3412 int64_t Pow2Alignment = 0;
3413 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003414 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00003415 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003416 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003417 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003418 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003419
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003420 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3421 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00003422 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3423
Chris Lattner258281d2010-01-19 06:22:22 +00003424 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003425 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3426 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00003427 if (!isPowerOf2_64(Pow2Alignment))
3428 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3429 Pow2Alignment = Log2_64(Pow2Alignment);
3430 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003431 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003432
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003433 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00003434 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003435
Sean Callanan79ed1a82010-01-19 20:22:31 +00003436 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003437
Chris Lattner1fc3d752009-07-09 17:25:12 +00003438 // NOTE: a size of zero for a .comm should create a undefined symbol
3439 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003440 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003441 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3442 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003443
Eric Christopherc260a3e2010-05-14 01:38:54 +00003444 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003445 // may internally end up wanting an alignment in bytes.
3446 // FIXME: Diagnose overflow.
3447 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003448 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3449 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003450
Daniel Dunbar8906ff12009-08-22 07:22:36 +00003451 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003452 return Error(IDLoc, "invalid symbol redefinition");
3453
Chris Lattner1fc3d752009-07-09 17:25:12 +00003454 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003455 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00003456 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003457 return false;
3458 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003459
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003460 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003461 return false;
3462}
Chris Lattner9be3fee2009-07-10 22:20:30 +00003463
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003464/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003465/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003466bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003467 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003468 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003469
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003470 StringRef Str = parseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003471 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003472 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003473
Sean Callanan79ed1a82010-01-19 20:22:31 +00003474 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003475
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003476 if (Str.empty())
3477 Error(Loc, ".abort detected. Assembly stopping.");
3478 else
3479 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003480 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003481
3482 return false;
3483}
Kevin Enderby71148242009-07-14 21:35:03 +00003484
Kevin Enderby1f049b22009-07-14 23:21:55 +00003485/// ParseDirectiveInclude
3486/// ::= .include "filename"
3487bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003488 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003489 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003490
Sean Callanan18b83232010-01-19 21:44:56 +00003491 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003492 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00003493 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00003494
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003495 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003496 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003497
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003498 // Strip the quotes.
3499 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003500
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003501 // Attempt to switch the lexer to the included file before consuming the end
3502 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00003503 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00003504 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003505 return true;
3506 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00003507
3508 return false;
3509}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00003510
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003511/// ParseDirectiveIncbin
3512/// ::= .incbin "filename"
3513bool AsmParser::ParseDirectiveIncbin() {
3514 if (getLexer().isNot(AsmToken::String))
3515 return TokError("expected string in '.incbin' directive");
3516
3517 std::string Filename = getTok().getString();
3518 SMLoc IncbinLoc = getLexer().getLoc();
3519 Lex();
3520
3521 if (getLexer().isNot(AsmToken::EndOfStatement))
3522 return TokError("unexpected token in '.incbin' directive");
3523
3524 // Strip the quotes.
3525 Filename = Filename.substr(1, Filename.size()-2);
3526
3527 // Attempt to process the included file.
3528 if (ProcessIncbinFile(Filename)) {
3529 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3530 return true;
3531 }
3532
3533 return false;
3534}
3535
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003536/// ParseDirectiveIf
3537/// ::= .if expression
3538bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003539 TheCondStack.push_back(TheCondState);
3540 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00003541 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003542 eatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00003543 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003544 int64_t ExprValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003545 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003546 return true;
3547
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003548 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003549 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003550
Sean Callanan79ed1a82010-01-19 20:22:31 +00003551 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003552
3553 TheCondState.CondMet = ExprValue;
3554 TheCondState.Ignore = !TheCondState.CondMet;
3555 }
3556
3557 return false;
3558}
3559
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003560/// ParseDirectiveIfb
3561/// ::= .ifb string
3562bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3563 TheCondStack.push_back(TheCondState);
3564 TheCondState.TheCond = AsmCond::IfCond;
3565
Benjamin Kramer29739e72012-05-12 16:52:21 +00003566 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003567 eatToEndOfStatement();
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003568 } else {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003569 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003570
3571 if (getLexer().isNot(AsmToken::EndOfStatement))
3572 return TokError("unexpected token in '.ifb' directive");
3573
3574 Lex();
3575
3576 TheCondState.CondMet = ExpectBlank == Str.empty();
3577 TheCondState.Ignore = !TheCondState.CondMet;
3578 }
3579
3580 return false;
3581}
3582
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003583/// ParseDirectiveIfc
3584/// ::= .ifc string1, string2
3585bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3586 TheCondStack.push_back(TheCondState);
3587 TheCondState.TheCond = AsmCond::IfCond;
3588
Benjamin Kramer29739e72012-05-12 16:52:21 +00003589 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003590 eatToEndOfStatement();
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003591 } else {
3592 StringRef Str1 = ParseStringToComma();
3593
3594 if (getLexer().isNot(AsmToken::Comma))
3595 return TokError("unexpected token in '.ifc' directive");
3596
3597 Lex();
3598
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003599 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003600
3601 if (getLexer().isNot(AsmToken::EndOfStatement))
3602 return TokError("unexpected token in '.ifc' directive");
3603
3604 Lex();
3605
3606 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3607 TheCondState.Ignore = !TheCondState.CondMet;
3608 }
3609
3610 return false;
3611}
3612
3613/// ParseDirectiveIfdef
3614/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003615bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3616 StringRef Name;
3617 TheCondStack.push_back(TheCondState);
3618 TheCondState.TheCond = AsmCond::IfCond;
3619
3620 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003621 eatToEndOfStatement();
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003622 } else {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003623 if (parseIdentifier(Name))
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003624 return TokError("expected identifier after '.ifdef'");
3625
3626 Lex();
3627
3628 MCSymbol *Sym = getContext().LookupSymbol(Name);
3629
3630 if (expect_defined)
3631 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3632 else
3633 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3634 TheCondState.Ignore = !TheCondState.CondMet;
3635 }
3636
3637 return false;
3638}
3639
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003640/// ParseDirectiveElseIf
3641/// ::= .elseif expression
3642bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
3643 if (TheCondState.TheCond != AsmCond::IfCond &&
3644 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper955d1e92013-04-22 04:24:02 +00003645 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3646 " an .elseif");
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003647 TheCondState.TheCond = AsmCond::ElseIfCond;
3648
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003649 bool LastIgnoreState = false;
3650 if (!TheCondStack.empty())
Craig Topper955d1e92013-04-22 04:24:02 +00003651 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003652 if (LastIgnoreState || TheCondState.CondMet) {
3653 TheCondState.Ignore = true;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003654 eatToEndOfStatement();
Craig Topperefa703d2013-04-22 04:22:40 +00003655 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003656 int64_t ExprValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003657 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003658 return true;
3659
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003660 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003661 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003662
Sean Callanan79ed1a82010-01-19 20:22:31 +00003663 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003664 TheCondState.CondMet = ExprValue;
3665 TheCondState.Ignore = !TheCondState.CondMet;
3666 }
3667
3668 return false;
3669}
3670
3671/// ParseDirectiveElse
3672/// ::= .else
3673bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003674 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003675 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003676
Sean Callanan79ed1a82010-01-19 20:22:31 +00003677 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003678
3679 if (TheCondState.TheCond != AsmCond::IfCond &&
3680 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper955d1e92013-04-22 04:24:02 +00003681 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3682 ".elseif");
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003683 TheCondState.TheCond = AsmCond::ElseCond;
3684 bool LastIgnoreState = false;
3685 if (!TheCondStack.empty())
3686 LastIgnoreState = TheCondStack.back().Ignore;
3687 if (LastIgnoreState || TheCondState.CondMet)
3688 TheCondState.Ignore = true;
3689 else
3690 TheCondState.Ignore = false;
3691
3692 return false;
3693}
3694
3695/// ParseDirectiveEndIf
3696/// ::= .endif
3697bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003698 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003699 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003700
Sean Callanan79ed1a82010-01-19 20:22:31 +00003701 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003702
3703 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3704 TheCondStack.empty())
3705 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3706 ".else");
3707 if (!TheCondStack.empty()) {
3708 TheCondState = TheCondStack.back();
3709 TheCondStack.pop_back();
3710 }
3711
3712 return false;
3713}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003714
Eli Bendersky6ee13082013-01-15 22:59:42 +00003715void AsmParser::initializeDirectiveKindMap() {
3716 DirectiveKindMap[".set"] = DK_SET;
3717 DirectiveKindMap[".equ"] = DK_EQU;
3718 DirectiveKindMap[".equiv"] = DK_EQUIV;
3719 DirectiveKindMap[".ascii"] = DK_ASCII;
3720 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3721 DirectiveKindMap[".string"] = DK_STRING;
3722 DirectiveKindMap[".byte"] = DK_BYTE;
3723 DirectiveKindMap[".short"] = DK_SHORT;
3724 DirectiveKindMap[".value"] = DK_VALUE;
3725 DirectiveKindMap[".2byte"] = DK_2BYTE;
3726 DirectiveKindMap[".long"] = DK_LONG;
3727 DirectiveKindMap[".int"] = DK_INT;
3728 DirectiveKindMap[".4byte"] = DK_4BYTE;
3729 DirectiveKindMap[".quad"] = DK_QUAD;
3730 DirectiveKindMap[".8byte"] = DK_8BYTE;
3731 DirectiveKindMap[".single"] = DK_SINGLE;
3732 DirectiveKindMap[".float"] = DK_FLOAT;
3733 DirectiveKindMap[".double"] = DK_DOUBLE;
3734 DirectiveKindMap[".align"] = DK_ALIGN;
3735 DirectiveKindMap[".align32"] = DK_ALIGN32;
3736 DirectiveKindMap[".balign"] = DK_BALIGN;
3737 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3738 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3739 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3740 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3741 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3742 DirectiveKindMap[".org"] = DK_ORG;
3743 DirectiveKindMap[".fill"] = DK_FILL;
3744 DirectiveKindMap[".zero"] = DK_ZERO;
3745 DirectiveKindMap[".extern"] = DK_EXTERN;
3746 DirectiveKindMap[".globl"] = DK_GLOBL;
3747 DirectiveKindMap[".global"] = DK_GLOBAL;
3748 DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
3749 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3750 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3751 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3752 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3753 DirectiveKindMap[".reference"] = DK_REFERENCE;
3754 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3755 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3756 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3757 DirectiveKindMap[".comm"] = DK_COMM;
3758 DirectiveKindMap[".common"] = DK_COMMON;
3759 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3760 DirectiveKindMap[".abort"] = DK_ABORT;
3761 DirectiveKindMap[".include"] = DK_INCLUDE;
3762 DirectiveKindMap[".incbin"] = DK_INCBIN;
3763 DirectiveKindMap[".code16"] = DK_CODE16;
3764 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3765 DirectiveKindMap[".rept"] = DK_REPT;
3766 DirectiveKindMap[".irp"] = DK_IRP;
3767 DirectiveKindMap[".irpc"] = DK_IRPC;
3768 DirectiveKindMap[".endr"] = DK_ENDR;
3769 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3770 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3771 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3772 DirectiveKindMap[".if"] = DK_IF;
3773 DirectiveKindMap[".ifb"] = DK_IFB;
3774 DirectiveKindMap[".ifnb"] = DK_IFNB;
3775 DirectiveKindMap[".ifc"] = DK_IFC;
3776 DirectiveKindMap[".ifnc"] = DK_IFNC;
3777 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3778 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3779 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3780 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3781 DirectiveKindMap[".else"] = DK_ELSE;
3782 DirectiveKindMap[".endif"] = DK_ENDIF;
3783 DirectiveKindMap[".skip"] = DK_SKIP;
3784 DirectiveKindMap[".space"] = DK_SPACE;
3785 DirectiveKindMap[".file"] = DK_FILE;
3786 DirectiveKindMap[".line"] = DK_LINE;
3787 DirectiveKindMap[".loc"] = DK_LOC;
3788 DirectiveKindMap[".stabs"] = DK_STABS;
3789 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3790 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3791 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3792 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3793 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3794 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3795 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3796 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3797 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3798 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3799 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3800 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3801 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3802 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3803 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3804 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3805 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3806 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3807 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3808 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3809 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3810 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3811 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3812 DirectiveKindMap[".macro"] = DK_MACRO;
3813 DirectiveKindMap[".endm"] = DK_ENDM;
3814 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3815 DirectiveKindMap[".purgem"] = DK_PURGEM;
Eli Bendersky5d0f0612013-01-10 22:44:57 +00003816}
3817
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003818
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003819MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003820 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003821
Rafael Espindola761cb062012-06-03 23:57:14 +00003822 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003823 for (;;) {
3824 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003825 if (getLexer().is(AsmToken::Eof)) {
3826 Error(DirectiveLoc, "no matching '.endr' in definition");
3827 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003828 }
3829
Rafael Espindola761cb062012-06-03 23:57:14 +00003830 if (Lexer.is(AsmToken::Identifier) &&
3831 (getTok().getIdentifier() == ".rept")) {
3832 ++NestLevel;
3833 }
3834
3835 // Otherwise, check whether we have reached the .endr.
3836 if (Lexer.is(AsmToken::Identifier) &&
3837 getTok().getIdentifier() == ".endr") {
3838 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003839 EndToken = getTok();
3840 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003841 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3842 TokError("unexpected token in '.endr' directive");
3843 return 0;
3844 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003845 break;
3846 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003847 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003848 }
3849
Rafael Espindola761cb062012-06-03 23:57:14 +00003850 // Otherwise, scan till the end of the statement.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003851 eatToEndOfStatement();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003852 }
3853
3854 const char *BodyStart = StartToken.getLoc().getPointer();
3855 const char *BodyEnd = EndToken.getLoc().getPointer();
3856 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3857
Rafael Espindola761cb062012-06-03 23:57:14 +00003858 // We Are Anonymous.
3859 StringRef Name;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003860 MCAsmMacroParameters Parameters;
3861 return new MCAsmMacro(Name, Body, Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +00003862}
3863
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003864void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +00003865 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003866 OS << ".endr\n";
3867
3868 MemoryBuffer *Instantiation =
3869 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3870
Rafael Espindola761cb062012-06-03 23:57:14 +00003871 // Create the macro instantiation object and add to the current macro
3872 // instantiation stack.
3873 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003874 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003875 getTok().getLoc(),
3876 Instantiation);
3877 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003878
Rafael Espindola761cb062012-06-03 23:57:14 +00003879 // Jump to the macro instantiation and prime the lexer.
3880 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3881 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3882 Lex();
3883}
3884
3885bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3886 int64_t Count;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003887 if (parseAbsoluteExpression(Count))
Rafael Espindola761cb062012-06-03 23:57:14 +00003888 return TokError("unexpected token in '.rept' directive");
3889
3890 if (Count < 0)
3891 return TokError("Count is negative");
3892
3893 if (Lexer.isNot(AsmToken::EndOfStatement))
3894 return TokError("unexpected token in '.rept' directive");
3895
3896 // Eat the end of statement.
3897 Lex();
3898
3899 // Lex the rept definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003900 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindola761cb062012-06-03 23:57:14 +00003901 if (!M)
3902 return true;
3903
3904 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3905 // to hold the macro body with substitutions.
3906 SmallString<256> Buf;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003907 MCAsmMacroParameters Parameters;
3908 MCAsmMacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003909 raw_svector_ostream OS(Buf);
3910 while (Count--) {
3911 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3912 return true;
3913 }
3914 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003915
3916 return false;
3917}
3918
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003919/// ParseDirectiveIrp
3920/// ::= .irp symbol,values
3921bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003922 MCAsmMacroParameters Parameters;
3923 MCAsmMacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003924
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003925 if (parseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003926 return TokError("expected identifier in '.irp' directive");
3927
3928 Parameters.push_back(Parameter);
3929
3930 if (Lexer.isNot(AsmToken::Comma))
3931 return TokError("expected comma in '.irp' directive");
3932
3933 Lex();
3934
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003935 MCAsmMacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003936 if (ParseMacroArguments(0, A))
3937 return true;
3938
3939 // Eat the end of statement.
3940 Lex();
3941
3942 // Lex the irp definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003943 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003944 if (!M)
3945 return true;
3946
3947 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3948 // to hold the macro body with substitutions.
3949 SmallString<256> Buf;
3950 raw_svector_ostream OS(Buf);
3951
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003952 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3953 MCAsmMacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003954 Args.push_back(*i);
3955
3956 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3957 return true;
3958 }
3959
3960 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3961
3962 return false;
3963}
3964
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003965/// ParseDirectiveIrpc
3966/// ::= .irpc symbol,values
3967bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003968 MCAsmMacroParameters Parameters;
3969 MCAsmMacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003970
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003971 if (parseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003972 return TokError("expected identifier in '.irpc' directive");
3973
3974 Parameters.push_back(Parameter);
3975
3976 if (Lexer.isNot(AsmToken::Comma))
3977 return TokError("expected comma in '.irpc' directive");
3978
3979 Lex();
3980
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003981 MCAsmMacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003982 if (ParseMacroArguments(0, A))
3983 return true;
3984
3985 if (A.size() != 1 || A.front().size() != 1)
3986 return TokError("unexpected token in '.irpc' directive");
3987
3988 // Eat the end of statement.
3989 Lex();
3990
3991 // Lex the irpc definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003992 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003993 if (!M)
3994 return true;
3995
3996 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3997 // to hold the macro body with substitutions.
3998 SmallString<256> Buf;
3999 raw_svector_ostream OS(Buf);
4000
4001 StringRef Values = A.front().front().getString();
4002 std::size_t I, End = Values.size();
4003 for (I = 0; I < End; ++I) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00004004 MCAsmMacroArgument Arg;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00004005 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
4006
Eli Benderskyc0c67b02013-01-14 23:22:36 +00004007 MCAsmMacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00004008 Args.push_back(Arg);
4009
4010 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
4011 return true;
4012 }
4013
4014 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
4015
4016 return false;
4017}
4018
Rafael Espindola761cb062012-06-03 23:57:14 +00004019bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
4020 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00004021 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004022
4023 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00004024 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004025 assert(getLexer().is(AsmToken::EndOfStatement));
4026
Rafael Espindola761cb062012-06-03 23:57:14 +00004027 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004028 return false;
4029}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00004030
Benjamin Kramer75234372013-02-15 20:37:21 +00004031bool AsmParser::ParseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4032 size_t Len) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004033 const MCExpr *Value;
4034 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004035 if (parseExpression(Value))
Eli Friedman2128aae2012-10-22 23:58:19 +00004036 return true;
4037 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4038 if (!MCE)
4039 return Error(ExprLoc, "unexpected expression in _emit");
4040 uint64_t IntValue = MCE->getValue();
4041 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4042 return Error(ExprLoc, "literal value out of range for directive");
4043
Chad Rosier469b1442013-02-12 21:33:51 +00004044 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4045 return false;
4046}
4047
4048bool AsmParser::ParseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4049 const MCExpr *Value;
4050 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004051 if (parseExpression(Value))
Chad Rosier469b1442013-02-12 21:33:51 +00004052 return true;
4053 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4054 if (!MCE)
4055 return Error(ExprLoc, "unexpected expression in align");
4056 uint64_t IntValue = MCE->getValue();
4057 if (!isPowerOf2_64(IntValue))
4058 return Error(ExprLoc, "literal value not a power of two greater then zero");
4059
Benjamin Kramer75234372013-02-15 20:37:21 +00004060 Info.AsmRewrites->push_back(AsmRewrite(AOK_Align, IDLoc, 5,
4061 Log2_64(IntValue)));
Eli Friedman2128aae2012-10-22 23:58:19 +00004062 return false;
4063}
4064
Chad Rosier19aa3e32013-02-13 21:27:17 +00004065// We are comparing pointers, but the pointers are relative to a single string.
4066// Thus, this should always be deterministic.
Benjamin Kramer75234372013-02-15 20:37:21 +00004067static int RewritesSort(const void *A, const void *B) {
4068 const AsmRewrite *AsmRewriteA = static_cast<const AsmRewrite *>(A);
4069 const AsmRewrite *AsmRewriteB = static_cast<const AsmRewrite *>(B);
Chad Rosierabde6752013-02-13 18:38:58 +00004070 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4071 return -1;
4072 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4073 return 1;
Chad Rosierb54562b2013-02-15 22:54:16 +00004074
Chad Rosier6b369ce2013-04-08 17:43:47 +00004075 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4076 // rewrite to the same location. Make sure the SizeDirective rewrite is
4077 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4078 // ensures the sort algorithm is stable.
4079 if (AsmRewritePrecedence [AsmRewriteA->Kind] >
4080 AsmRewritePrecedence [AsmRewriteB->Kind])
Chad Rosierb54562b2013-02-15 22:54:16 +00004081 return -1;
Chad Rosier6b369ce2013-04-08 17:43:47 +00004082
4083 if (AsmRewritePrecedence [AsmRewriteA->Kind] <
4084 AsmRewritePrecedence [AsmRewriteB->Kind])
Chad Rosierb54562b2013-02-15 22:54:16 +00004085 return 1;
Chad Rosierb54562b2013-02-15 22:54:16 +00004086 llvm_unreachable ("Unstable rewrite sort.");
Chad Rosierb1953982013-02-13 01:03:13 +00004087}
4088
Benjamin Kramer75234372013-02-15 20:37:21 +00004089bool
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004090AsmParser::parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Benjamin Kramer75234372013-02-15 20:37:21 +00004091 unsigned &NumOutputs, unsigned &NumInputs,
4092 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4093 SmallVectorImpl<std::string> &Constraints,
4094 SmallVectorImpl<std::string> &Clobbers,
4095 const MCInstrInfo *MII,
4096 const MCInstPrinter *IP,
4097 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004098 SmallVector<void *, 4> InputDecls;
4099 SmallVector<void *, 4> OutputDecls;
Chad Rosierc1ec2072013-01-10 22:10:27 +00004100 SmallVector<bool, 4> InputDeclsAddressOf;
4101 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004102 SmallVector<std::string, 4> InputConstraints;
4103 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer75234372013-02-15 20:37:21 +00004104 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004105
Benjamin Kramer75234372013-02-15 20:37:21 +00004106 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004107
4108 // Prime the lexer.
4109 Lex();
4110
4111 // While we have input, parse each statement.
4112 unsigned InputIdx = 0;
4113 unsigned OutputIdx = 0;
4114 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004115 ParseStatementInfo Info(&AsmStrRewrites);
4116 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00004117 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004118
Chad Rosier57498012012-12-12 22:45:52 +00004119 if (Info.ParseError)
4120 return true;
4121
Benjamin Kramer75234372013-02-15 20:37:21 +00004122 if (Info.Opcode == ~0U)
4123 continue;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004124
Benjamin Kramer75234372013-02-15 20:37:21 +00004125 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004126
Benjamin Kramer75234372013-02-15 20:37:21 +00004127 // Build the list of clobbers, outputs and inputs.
4128 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4129 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004130
Benjamin Kramer75234372013-02-15 20:37:21 +00004131 // Immediate.
Chad Rosier811ddf62013-03-19 21:58:18 +00004132 if (Operand->isImm())
Benjamin Kramer75234372013-02-15 20:37:21 +00004133 continue;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004134
Benjamin Kramer75234372013-02-15 20:37:21 +00004135 // Register operand.
4136 if (Operand->isReg() && !Operand->needAddressOf()) {
4137 unsigned NumDefs = Desc.getNumDefs();
4138 // Clobber.
4139 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4140 ClobberRegs.push_back(Operand->getReg());
4141 continue;
4142 }
4143
4144 // Expr/Input or Output.
Chad Rosierb976e402013-04-09 17:53:49 +00004145 StringRef SymName = Operand->getSymName();
4146 if (SymName.empty())
4147 continue;
4148
Chad Rosier087c3092013-04-22 22:12:12 +00004149 void *OpDecl = Operand->getOpDecl();
Benjamin Kramer75234372013-02-15 20:37:21 +00004150 if (!OpDecl)
4151 continue;
4152
4153 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierb976e402013-04-09 17:53:49 +00004154 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer75234372013-02-15 20:37:21 +00004155 if (isOutput) {
4156 ++InputIdx;
4157 OutputDecls.push_back(OpDecl);
4158 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4159 OutputConstraints.push_back('=' + Operand->getConstraint().str());
Chad Rosierb976e402013-04-09 17:53:49 +00004160 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
Benjamin Kramer75234372013-02-15 20:37:21 +00004161 } else {
4162 InputDecls.push_back(OpDecl);
4163 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4164 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosierb976e402013-04-09 17:53:49 +00004165 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00004166 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004167 }
4168 }
4169
4170 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004171 NumOutputs = OutputDecls.size();
4172 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00004173
4174 // Set the unique clobbers.
Benjamin Kramer75234372013-02-15 20:37:21 +00004175 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4176 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4177 ClobberRegs.end());
4178 Clobbers.assign(ClobberRegs.size(), std::string());
4179 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4180 raw_string_ostream OS(Clobbers[I]);
4181 IP->printRegName(OS, ClobberRegs[I]);
4182 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004183
4184 // Merge the various outputs and inputs. Output are expected first.
4185 if (NumOutputs || NumInputs) {
4186 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004187 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004188 Constraints.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004189 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004190 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004191 Constraints[i] = OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004192 }
4193 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004194 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004195 Constraints[j] = InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004196 }
4197 }
4198
4199 // Build the IR assembly string.
4200 std::string AsmStringIR;
4201 raw_string_ostream OS(AsmStringIR);
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004202 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4203 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
Benjamin Kramer75234372013-02-15 20:37:21 +00004204 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), RewritesSort);
4205 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4206 E = AsmStrRewrites.end();
4207 I != E; ++I) {
Chad Rosierdda4b6b2013-04-12 16:26:42 +00004208 AsmRewriteKind Kind = (*I).Kind;
4209 if (Kind == AOK_Delete)
4210 continue;
4211
Chad Rosierb1f8c132012-10-18 15:49:34 +00004212 const char *Loc = (*I).Loc.getPointer();
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004213 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier96d58e62012-10-19 20:57:14 +00004214
Chad Rosier023c8802013-03-19 17:32:17 +00004215 // Emit everything up to the immediate/expression.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004216 unsigned Len = Loc - AsmStart;
Chad Rosierf06cc982013-04-11 21:49:30 +00004217 if (Len)
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004218 OS << StringRef(AsmStart, Len);
Chad Rosier96d58e62012-10-19 20:57:14 +00004219
Chad Rosier5a719fc2012-10-23 17:43:43 +00004220 // Skip the original expression.
4221 if (Kind == AOK_Skip) {
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004222 AsmStart = Loc + (*I).Len;
Chad Rosier5a719fc2012-10-23 17:43:43 +00004223 continue;
4224 }
4225
Chad Rosierdda4b6b2013-04-12 16:26:42 +00004226 unsigned AdditionalSkip = 0;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004227 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00004228 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004229 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004230 case AOK_Imm:
Benjamin Kramer75234372013-02-15 20:37:21 +00004231 OS << "$$" << (*I).Val;
Chad Rosierefcb3d92012-10-26 18:04:20 +00004232 break;
4233 case AOK_ImmPrefix:
Benjamin Kramer75234372013-02-15 20:37:21 +00004234 OS << "$$";
Chad Rosierb1f8c132012-10-18 15:49:34 +00004235 break;
4236 case AOK_Input:
Benjamin Kramer75234372013-02-15 20:37:21 +00004237 OS << '$' << InputIdx++;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004238 break;
4239 case AOK_Output:
Benjamin Kramer75234372013-02-15 20:37:21 +00004240 OS << '$' << OutputIdx++;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004241 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00004242 case AOK_SizeDirective:
Benjamin Kramer75234372013-02-15 20:37:21 +00004243 switch ((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00004244 default: break;
4245 case 8: OS << "byte ptr "; break;
4246 case 16: OS << "word ptr "; break;
4247 case 32: OS << "dword ptr "; break;
4248 case 64: OS << "qword ptr "; break;
4249 case 80: OS << "xword ptr "; break;
4250 case 128: OS << "xmmword ptr "; break;
4251 case 256: OS << "ymmword ptr "; break;
4252 }
Eli Friedman2128aae2012-10-22 23:58:19 +00004253 break;
4254 case AOK_Emit:
4255 OS << ".byte";
4256 break;
Chad Rosier469b1442013-02-12 21:33:51 +00004257 case AOK_Align: {
4258 unsigned Val = (*I).Val;
4259 OS << ".align " << Val;
4260
4261 // Skip the original immediate.
Benjamin Kramer75234372013-02-15 20:37:21 +00004262 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosier469b1442013-02-12 21:33:51 +00004263 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4264 break;
4265 }
Chad Rosier6a020a72012-10-25 20:41:34 +00004266 case AOK_DotOperator:
4267 OS << (*I).Val;
4268 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004269 }
Chad Rosier96d58e62012-10-19 20:57:14 +00004270
Chad Rosierb1f8c132012-10-18 15:49:34 +00004271 // Skip the original expression.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004272 AsmStart = Loc + (*I).Len + AdditionalSkip;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004273 }
4274
4275 // Emit the remainder of the asm string.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004276 if (AsmStart != AsmEnd)
4277 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004278
4279 AsmString = OS.str();
4280 return false;
4281}
4282
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004283/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004284MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004285 MCContext &C, MCStreamer &Out,
4286 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004287 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004288}