blob: 9a753cb31a80438339d457d772c8281d70e587f6 [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.
Kevin Enderbydac29532011-12-15 00:00:27 +0000565 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
566 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000567 return false;
568}
569
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000570void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
571 if (InBuffer != -1) {
572 CurBuffer = InBuffer;
573 } else {
574 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
575 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000576 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
577}
578
Sean Callananfd0b0282010-01-21 00:19:58 +0000579const AsmToken &AsmParser::Lex() {
580 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000581
Sean Callananfd0b0282010-01-21 00:19:58 +0000582 if (tok->is(AsmToken::Eof)) {
583 // If this is the end of an included file, pop the parent file off the
584 // include stack.
585 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
586 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000587 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000588 tok = &Lexer.Lex();
589 }
590 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000591
Sean Callananfd0b0282010-01-21 00:19:58 +0000592 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000593 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000594
Sean Callananfd0b0282010-01-21 00:19:58 +0000595 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000596}
597
Chris Lattner79180e22010-04-05 23:15:42 +0000598bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000599 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000600 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000601 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000602
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000603 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000604 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000605
606 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000607 AsmCond StartingCondState = TheCondState;
608
Kevin Enderby613b7572011-11-01 22:27:22 +0000609 // If we are generating dwarf for assembly source files save the initial text
610 // section and generate a .file directive.
611 if (getContext().getGenDwarfForAssembly()) {
Peter Collingbournedf39be62013-04-17 21:18:16 +0000612 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
Kevin Enderby94c2e852011-12-09 18:09:40 +0000613 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
614 getStreamer().EmitLabel(SectionStartSym);
615 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000616 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
Eric Christopher6c583142012-12-18 00:31:01 +0000617 StringRef(),
618 getContext().getMainFileName());
Kevin Enderby613b7572011-11-01 22:27:22 +0000619 }
620
Chris Lattnerb717fb02009-07-02 21:53:43 +0000621 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000622 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000623 ParseStatementInfo Info;
624 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000625
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000626 // We had an error, validate that one was emitted and recover by skipping to
627 // the next line.
628 assert(HadError && "Parse statement returned an error, but none emitted!");
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000629 eatToEndOfStatement();
Chris Lattnerb717fb02009-07-02 21:53:43 +0000630 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000631
632 if (TheCondState.TheCond != StartingCondState.TheCond ||
633 TheCondState.Ignore != StartingCondState.Ignore)
634 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000635
636 // Check to see there are no empty DwarfFile slots.
Manman Ren9e999ad2013-03-12 20:17:00 +0000637 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000638 getContext().getMCDwarfFiles();
639 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000640 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000641 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000642 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000643
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000644 // Check to see that all assembler local symbols were actually defined.
645 // Targets that don't do subsections via symbols may not want this, though,
646 // so conservatively exclude them. Only do this if we're finalizing, though,
647 // as otherwise we won't necessarilly have seen everything yet.
648 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
649 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
650 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
651 e = Symbols.end();
652 i != e; ++i) {
653 MCSymbol *Sym = i->getValue();
654 // Variable symbols may not be marked as defined, so check those
655 // explicitly. If we know it's a variable, we have a definition for
656 // the purposes of this check.
657 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
658 // FIXME: We would really like to refer back to where the symbol was
659 // first referenced for a source location. We need to add something
660 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000661 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
662 "assembler local symbol '" + Sym->getName() +
663 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000664 }
665 }
666
667
Chris Lattner79180e22010-04-05 23:15:42 +0000668 // Finalize the output stream if there are no errors and if the client wants
669 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000670 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000671 Out.Finish();
672
Chris Lattnerb717fb02009-07-02 21:53:43 +0000673 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000674}
675
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000676void AsmParser::checkForValidSection() {
Peter Collingbournedf39be62013-04-17 21:18:16 +0000677 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000678 TokError("expected section directive before assembly directive");
Eli Bendersky030f63a2013-01-14 19:04:57 +0000679 Out.InitToTextSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000680 }
681}
682
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000683/// eatToEndOfStatement - Throw away the rest of the line for testing purposes.
684void AsmParser::eatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000685 while (Lexer.isNot(AsmToken::EndOfStatement) &&
686 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000687 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000688
Chris Lattner2cf5f142009-06-22 01:29:09 +0000689 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000690 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000691 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000692}
693
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000694StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000695 const char *Start = getTok().getLoc().getPointer();
696
697 while (Lexer.isNot(AsmToken::EndOfStatement) &&
698 Lexer.isNot(AsmToken::Eof))
699 Lex();
700
701 const char *End = getTok().getLoc().getPointer();
702 return StringRef(Start, End - Start);
703}
Chris Lattnerc4193832009-06-22 05:51:26 +0000704
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000705StringRef AsmParser::ParseStringToComma() {
706 const char *Start = getTok().getLoc().getPointer();
707
708 while (Lexer.isNot(AsmToken::EndOfStatement) &&
709 Lexer.isNot(AsmToken::Comma) &&
710 Lexer.isNot(AsmToken::Eof))
711 Lex();
712
713 const char *End = getTok().getLoc().getPointer();
714 return StringRef(Start, End - Start);
715}
716
Chris Lattner74ec1a32009-06-22 06:32:03 +0000717/// ParseParenExpr - Parse a paren expression and return it.
718/// NOTE: This assumes the leading '(' has already been consumed.
719///
720/// parenexpr ::= expr)
721///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000722bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000723 if (parseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000724 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000725 return TokError("expected ')' in parentheses expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000726 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000727 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000728 return false;
729}
Chris Lattnerc4193832009-06-22 05:51:26 +0000730
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000731/// ParseBracketExpr - Parse a bracket expression and return it.
732/// NOTE: This assumes the leading '[' has already been consumed.
733///
734/// bracketexpr ::= expr]
735///
736bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000737 if (parseExpression(Res)) return true;
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000738 if (Lexer.isNot(AsmToken::RBrac))
739 return TokError("expected ']' in brackets expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000740 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000741 Lex();
742 return false;
743}
744
Chris Lattner74ec1a32009-06-22 06:32:03 +0000745/// ParsePrimaryExpr - Parse a primary expression and return it.
746/// primaryexpr ::= (parenexpr
747/// primaryexpr ::= symbol
748/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000749/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000750/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000751bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby5de048e2013-01-22 21:09:20 +0000752 SMLoc FirstTokenLoc = getLexer().getLoc();
753 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
754 switch (FirstTokenKind) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000755 default:
756 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000757 // If we have an error assume that we've already handled it.
758 case AsmToken::Error:
759 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000760 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000761 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000762 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000763 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000764 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000765 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000766 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000767 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000768 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000769 StringRef Identifier;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000770 if (parseIdentifier(Identifier)) {
Kevin Enderby5de048e2013-01-22 21:09:20 +0000771 if (FirstTokenKind == AsmToken::Dollar)
772 return Error(FirstTokenLoc, "invalid token in expression");
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000773 return true;
Kevin Enderby5de048e2013-01-22 21:09:20 +0000774 }
Daniel Dunbare17edff2010-08-24 19:13:42 +0000775
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000776 EndLoc = SMLoc::getFromPointer(Identifier.end());
777
Daniel Dunbarfffff912009-10-16 01:34:54 +0000778 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000779 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000780 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000781
782 // Lookup the symbol variant if used.
783 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000784 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000785 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000786 if (Variant == MCSymbolRefExpr::VK_Invalid) {
787 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000788 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000789 }
790 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000791
Daniel Dunbarfffff912009-10-16 01:34:54 +0000792 // If this is an absolute variable reference, substitute it now to preserve
793 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000794 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000795 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000796 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000797
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000798 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000799 return false;
800 }
801
802 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000803 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000804 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000805 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000806 case AsmToken::Integer: {
807 SMLoc Loc = getTok().getLoc();
808 int64_t IntVal = getTok().getIntVal();
809 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000810 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000811 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000812 // Look for 'b' or 'f' following an Integer as a directional label
813 if (Lexer.getKind() == AsmToken::Identifier) {
814 StringRef IDVal = getTok().getString();
Ulrich Weigand151ad372013-06-20 16:24:17 +0000815 // Lookup the symbol variant if used.
816 std::pair<StringRef, StringRef> Split = IDVal.split('@');
817 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
818 if (Split.first.size() != IDVal.size()) {
819 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
820 if (Variant == MCSymbolRefExpr::VK_Invalid) {
821 Variant = MCSymbolRefExpr::VK_None;
822 return TokError("invalid variant '" + Split.second + "'");
823 }
824 IDVal = Split.first;
825 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000826 if (IDVal == "f" || IDVal == "b"){
827 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
828 IDVal == "f" ? 1 : 0);
Ulrich Weigand151ad372013-06-20 16:24:17 +0000829 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000830 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000831 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000832 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000833 Lex(); // Eat identifier.
834 }
835 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000836 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000837 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000838 case AsmToken::Real: {
839 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000840 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000841 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000842 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000843 Lex(); // Eat token.
844 return false;
845 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000846 case AsmToken::Dot: {
847 // This is a '.' reference, which references the current PC. Emit a
848 // temporary label to the streamer and refer to it.
849 MCSymbol *Sym = Ctx.CreateTempSymbol();
850 Out.EmitLabel(Sym);
851 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000852 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattnerd3050352010-04-14 04:40:28 +0000853 Lex(); // Eat identifier.
854 return false;
855 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000856 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000857 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000858 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000859 case AsmToken::LBrac:
860 if (!PlatformParser->HasBracketExpressions())
861 return TokError("brackets expression not supported on this target");
862 Lex(); // Eat the '['.
863 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000864 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000865 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000866 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000867 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000868 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000869 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000870 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000871 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000872 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000873 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000874 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000875 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000876 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000877 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000878 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000879 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000880 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000881 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000882 }
883}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000884
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000885bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000886 SMLoc EndLoc;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000887 return parseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000888}
889
Chad Rosierba69b362013-04-10 17:35:30 +0000890bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
891 return ParsePrimaryExpr(Res, EndLoc);
892}
893
Daniel Dunbarcceba832010-09-17 02:47:07 +0000894const MCExpr *
895AsmParser::ApplyModifierToExpr(const MCExpr *E,
896 MCSymbolRefExpr::VariantKind Variant) {
897 // Recurse over the given expression, rebuilding it to apply the given variant
898 // if there is exactly one symbol.
899 switch (E->getKind()) {
900 case MCExpr::Target:
901 case MCExpr::Constant:
902 return 0;
903
904 case MCExpr::SymbolRef: {
905 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
906
907 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
908 TokError("invalid variant on expression '" +
909 getTok().getIdentifier() + "' (already modified)");
910 return E;
911 }
912
913 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
914 }
915
916 case MCExpr::Unary: {
917 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
918 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
919 if (!Sub)
920 return 0;
921 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
922 }
923
924 case MCExpr::Binary: {
925 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
926 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
927 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
928
929 if (!LHS && !RHS)
930 return 0;
931
932 if (!LHS) LHS = BE->getLHS();
933 if (!RHS) RHS = BE->getRHS();
934
935 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
936 }
937 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000938
Craig Topper85814382012-02-07 05:05:23 +0000939 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000940}
941
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000942/// parseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000943///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000944/// expr ::= expr &&,|| expr -> lowest.
945/// expr ::= expr |,^,&,! expr
946/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
947/// expr ::= expr <<,>> expr
948/// expr ::= expr +,- expr
949/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000950/// expr ::= primaryexpr
951///
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000952bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000953 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000954 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000955 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
956 return true;
957
Daniel Dunbarcceba832010-09-17 02:47:07 +0000958 // As a special case, we support 'a op b @ modifier' by rewriting the
959 // expression to include the modifier. This is inefficient, but in general we
960 // expect users to use 'a@modifier op b'.
961 if (Lexer.getKind() == AsmToken::At) {
962 Lex();
963
964 if (Lexer.isNot(AsmToken::Identifier))
965 return TokError("unexpected symbol modifier following '@'");
966
967 MCSymbolRefExpr::VariantKind Variant =
968 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
969 if (Variant == MCSymbolRefExpr::VK_Invalid)
970 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
971
972 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
973 if (!ModifiedRes) {
974 return TokError("invalid modifier '" + getTok().getIdentifier() +
975 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000976 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000977
Daniel Dunbarcceba832010-09-17 02:47:07 +0000978 Res = ModifiedRes;
979 Lex();
980 }
981
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000982 // Try to constant fold it up front, if possible.
983 int64_t Value;
984 if (Res->EvaluateAsAbsolute(Value))
985 Res = MCConstantExpr::Create(Value, getContext());
986
987 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000988}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000989
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000990bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000991 Res = 0;
992 return ParseParenExpr(Res, EndLoc) ||
993 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000994}
995
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000996bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000997 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000998
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000999 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001000 if (parseExpression(Expr))
Daniel Dunbar475839e2009-06-29 20:37:27 +00001001 return true;
1002
Daniel Dunbare00b0112009-10-16 01:57:52 +00001003 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00001004 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +00001005
1006 return false;
1007}
1008
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001009static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001010 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001011 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001012 default:
1013 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +00001014
Jim Grosbachfbe16812011-08-20 16:24:13 +00001015 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +00001016 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001017 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001018 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001019 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001020 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001021 return 1;
1022
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001023
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001024 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +00001025 //
1026 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +00001027 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001028 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001029 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001030 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001031 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001032 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001033 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001034 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001035 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001036
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001037 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001038 case AsmToken::EqualEqual:
1039 Kind = MCBinaryExpr::EQ;
1040 return 3;
1041 case AsmToken::ExclaimEqual:
1042 case AsmToken::LessGreater:
1043 Kind = MCBinaryExpr::NE;
1044 return 3;
1045 case AsmToken::Less:
1046 Kind = MCBinaryExpr::LT;
1047 return 3;
1048 case AsmToken::LessEqual:
1049 Kind = MCBinaryExpr::LTE;
1050 return 3;
1051 case AsmToken::Greater:
1052 Kind = MCBinaryExpr::GT;
1053 return 3;
1054 case AsmToken::GreaterEqual:
1055 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001056 return 3;
1057
Jim Grosbachfbe16812011-08-20 16:24:13 +00001058 // Intermediate Precedence: <<, >>
1059 case AsmToken::LessLess:
1060 Kind = MCBinaryExpr::Shl;
1061 return 4;
1062 case AsmToken::GreaterGreater:
1063 Kind = MCBinaryExpr::Shr;
1064 return 4;
1065
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001066 // High Intermediate Precedence: +, -
1067 case AsmToken::Plus:
1068 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001069 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001070 case AsmToken::Minus:
1071 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001072 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001073
Jim Grosbachfbe16812011-08-20 16:24:13 +00001074 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001075 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001076 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001077 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001078 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001079 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001080 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001081 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001082 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001083 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001084 }
1085}
1086
1087
1088/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1089/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001090bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1091 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001092 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001093 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001094 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001095
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001096 // If the next token is lower precedence than we are allowed to eat, return
1097 // successfully with what we ate already.
1098 if (TokPrec < Precedence)
1099 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001100
Sean Callanan79ed1a82010-01-19 20:22:31 +00001101 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001102
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001103 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001104 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001105 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001106
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001107 // If BinOp binds less tightly with RHS than the operator after RHS, let
1108 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001109 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001110 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001111 if (TokPrec < NextTokPrec) {
Kevin Enderby88535dd2013-05-07 21:40:58 +00001112 if (ParseBinOpRHS(TokPrec+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001113 }
1114
Daniel Dunbar475839e2009-06-29 20:37:27 +00001115 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001116 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001117 }
1118}
1119
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001120/// ParseStatement:
1121/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001122/// ::= Label* Directive ...Operands... EndOfStatement
1123/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001124bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001125 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001126 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001127 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001128 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001129 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001130
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001131 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001132 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001133 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001134 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001135 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001136 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001137 if (Lexer.is(AsmToken::Hash))
1138 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001139
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001140 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001141 if (Lexer.is(AsmToken::Integer)) {
1142 LocalLabelVal = getTok().getIntVal();
1143 if (LocalLabelVal < 0) {
1144 if (!TheCondState.Ignore)
1145 return TokError("unexpected token at start of statement");
1146 IDVal = "";
Eli Benderskyed5df012013-01-16 19:32:36 +00001147 } else {
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001148 IDVal = getTok().getString();
1149 Lex(); // Consume the integer token to be used as an identifier token.
1150 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001151 if (!TheCondState.Ignore)
1152 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001153 }
1154 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001155 } else if (Lexer.is(AsmToken::Dot)) {
1156 // Treat '.' as a valid identifier in this context.
1157 Lex();
1158 IDVal = ".";
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001159 } else if (parseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001160 if (!TheCondState.Ignore)
1161 return TokError("unexpected token at start of statement");
1162 IDVal = "";
1163 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001164
Chris Lattner7834fac2010-04-17 18:14:27 +00001165 // Handle conditional assembly here before checking for skipping. We
1166 // have to do this so that .endif isn't skipped in a ".if 0" block for
1167 // example.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001168 StringMap<DirectiveKind>::const_iterator DirKindIt =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001169 DirectiveKindMap.find(IDVal);
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001170 DirectiveKind DirKind =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001171 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1172 DirKindIt->getValue();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001173 switch (DirKind) {
1174 default:
1175 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001176 case DK_IF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001177 return ParseDirectiveIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001178 case DK_IFB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001179 return ParseDirectiveIfb(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001180 case DK_IFNB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001181 return ParseDirectiveIfb(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001182 case DK_IFC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001183 return ParseDirectiveIfc(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001184 case DK_IFNC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001185 return ParseDirectiveIfc(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001186 case DK_IFDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001187 return ParseDirectiveIfdef(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001188 case DK_IFNDEF:
1189 case DK_IFNOTDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001190 return ParseDirectiveIfdef(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001191 case DK_ELSEIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001192 return ParseDirectiveElseIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001193 case DK_ELSE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001194 return ParseDirectiveElse(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001195 case DK_ENDIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001196 return ParseDirectiveEndIf(IDLoc);
1197 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001198
Eli Benderskyed5df012013-01-16 19:32:36 +00001199 // Ignore the statement if in the middle of inactive conditional
1200 // (e.g. ".if 0").
Chad Rosier17feeec2012-10-20 00:47:08 +00001201 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001202 eatToEndOfStatement();
Chris Lattner7834fac2010-04-17 18:14:27 +00001203 return false;
1204 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001205
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001206 // FIXME: Recurse on local labels?
1207
1208 // See what kind of statement we have.
1209 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001210 case AsmToken::Colon: {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001211 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001212
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001213 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001214 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001215
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001216 // Diagnose attempt to use '.' as a label.
1217 if (IDVal == ".")
1218 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1219
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001220 // Diagnose attempt to use a variable as a label.
1221 //
1222 // FIXME: Diagnostics. Note the location of the definition as a label.
1223 // FIXME: This doesn't diagnose assignment to a symbol which has been
1224 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001225 MCSymbol *Sym;
1226 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001227 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001228 else
1229 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001230 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001231 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001232
Daniel Dunbar959fd882009-08-26 22:13:22 +00001233 // Emit the label.
Chad Rosierdeb1bab2013-01-07 20:34:12 +00001234 if (!ParsingInlineAsm)
1235 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001236
Kevin Enderby94c2e852011-12-09 18:09:40 +00001237 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001238 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001239 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001240 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1241 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001242
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001243 // Consume any end of statement token, if present, to avoid spurious
1244 // AddBlankLine calls().
1245 if (Lexer.is(AsmToken::EndOfStatement)) {
1246 Lex();
1247 if (Lexer.is(AsmToken::Eof))
1248 return false;
1249 }
1250
Eli Friedman2128aae2012-10-22 23:58:19 +00001251 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001252 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001253
Daniel Dunbar3f872332009-07-28 16:08:33 +00001254 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001255 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001256 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001257
Nico Weber4c4c7322011-01-28 03:04:41 +00001258 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001259
1260 default: // Normal instruction or directive.
1261 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001262 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001263
1264 // If macros are enabled, check to see if this is a macro instantiation.
Eli Bendersky733c3362013-01-14 18:08:41 +00001265 if (MacrosEnabled())
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001266 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1267 return HandleMacroEntry(M, IDLoc);
1268 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001269
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001270 // Otherwise, we have a normal instruction or directive.
Eli Bendersky6ee13082013-01-15 22:59:42 +00001271
1272 // Directives start with "."
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001273 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00001274 // There are several entities interested in parsing directives:
1275 //
1276 // 1. The target-specific assembly parser. Some directives are target
1277 // specific or may potentially behave differently on certain targets.
1278 // 2. Asm parser extensions. For example, platform-specific parsers
1279 // (like the ELF parser) register themselves as extensions.
1280 // 3. The generic directive parser implemented by this class. These are
1281 // all the directives that behave in a target and platform independent
1282 // manner, or at least have a default behavior that's shared between
1283 // all targets and platforms.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001284
Eli Bendersky6ee13082013-01-15 22:59:42 +00001285 // First query the target-specific parser. It will return 'true' if it
1286 // isn't interested in this directive.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001287 if (!getTargetParser().ParseDirective(ID))
1288 return false;
1289
Eli Bendersky6ee13082013-01-15 22:59:42 +00001290 // Next, check the extention directive map to see if any extension has
1291 // registered itself to parse this directive.
1292 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1293 ExtensionDirectiveMap.lookup(IDVal);
1294 if (Handler.first)
1295 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1296
1297 // Finally, if no one else is interested in this directive, it must be
1298 // generic and familiar to this class.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001299 switch (DirKind) {
1300 default:
1301 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001302 case DK_SET:
1303 case DK_EQU:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001304 return ParseDirectiveSet(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001305 case DK_EQUIV:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001306 return ParseDirectiveSet(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001307 case DK_ASCII:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001308 return ParseDirectiveAscii(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001309 case DK_ASCIZ:
1310 case DK_STRING:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001311 return ParseDirectiveAscii(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001312 case DK_BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001313 return ParseDirectiveValue(1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001314 case DK_SHORT:
1315 case DK_VALUE:
1316 case DK_2BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001317 return ParseDirectiveValue(2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001318 case DK_LONG:
1319 case DK_INT:
1320 case DK_4BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001321 return ParseDirectiveValue(4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001322 case DK_QUAD:
1323 case DK_8BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001324 return ParseDirectiveValue(8);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001325 case DK_SINGLE:
1326 case DK_FLOAT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001327 return ParseDirectiveRealValue(APFloat::IEEEsingle);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001328 case DK_DOUBLE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001329 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001330 case DK_ALIGN: {
Bill Wendling99cb6222013-06-18 07:20:20 +00001331 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001332 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1333 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001334 case DK_ALIGN32: {
Bill Wendling99cb6222013-06-18 07:20:20 +00001335 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001336 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1337 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001338 case DK_BALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001339 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001340 case DK_BALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001341 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001342 case DK_BALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001343 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001344 case DK_P2ALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001345 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001346 case DK_P2ALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001347 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001348 case DK_P2ALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001349 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001350 case DK_ORG:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001351 return ParseDirectiveOrg();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001352 case DK_FILL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001353 return ParseDirectiveFill();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001354 case DK_ZERO:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001355 return ParseDirectiveZero();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001356 case DK_EXTERN:
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001357 eatToEndOfStatement(); // .extern is the default, ignore it.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001358 return false;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001359 case DK_GLOBL:
1360 case DK_GLOBAL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001361 return ParseDirectiveSymbolAttribute(MCSA_Global);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001362 case DK_INDIRECT_SYMBOL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001363 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001364 case DK_LAZY_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001365 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001366 case DK_NO_DEAD_STRIP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001367 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001368 case DK_SYMBOL_RESOLVER:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001369 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001370 case DK_PRIVATE_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001371 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001372 case DK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001373 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001374 case DK_WEAK_DEFINITION:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001375 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001376 case DK_WEAK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001377 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001378 case DK_WEAK_DEF_CAN_BE_HIDDEN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001379 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001380 case DK_COMM:
1381 case DK_COMMON:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001382 return ParseDirectiveComm(/*IsLocal=*/false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001383 case DK_LCOMM:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001384 return ParseDirectiveComm(/*IsLocal=*/true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001385 case DK_ABORT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001386 return ParseDirectiveAbort();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001387 case DK_INCLUDE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001388 return ParseDirectiveInclude();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001389 case DK_INCBIN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001390 return ParseDirectiveIncbin();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001391 case DK_CODE16:
1392 case DK_CODE16GCC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001393 return TokError(Twine(IDVal) + " not supported yet");
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001394 case DK_REPT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001395 return ParseDirectiveRept(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001396 case DK_IRP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001397 return ParseDirectiveIrp(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001398 case DK_IRPC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001399 return ParseDirectiveIrpc(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001400 case DK_ENDR:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001401 return ParseDirectiveEndr(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001402 case DK_BUNDLE_ALIGN_MODE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001403 return ParseDirectiveBundleAlignMode();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001404 case DK_BUNDLE_LOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001405 return ParseDirectiveBundleLock();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001406 case DK_BUNDLE_UNLOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001407 return ParseDirectiveBundleUnlock();
Eli Bendersky6ee13082013-01-15 22:59:42 +00001408 case DK_SLEB128:
1409 return ParseDirectiveLEB128(true);
1410 case DK_ULEB128:
1411 return ParseDirectiveLEB128(false);
1412 case DK_SPACE:
1413 case DK_SKIP:
1414 return ParseDirectiveSpace(IDVal);
1415 case DK_FILE:
1416 return ParseDirectiveFile(IDLoc);
1417 case DK_LINE:
1418 return ParseDirectiveLine();
1419 case DK_LOC:
1420 return ParseDirectiveLoc();
1421 case DK_STABS:
1422 return ParseDirectiveStabs();
1423 case DK_CFI_SECTIONS:
1424 return ParseDirectiveCFISections();
1425 case DK_CFI_STARTPROC:
1426 return ParseDirectiveCFIStartProc();
1427 case DK_CFI_ENDPROC:
1428 return ParseDirectiveCFIEndProc();
1429 case DK_CFI_DEF_CFA:
1430 return ParseDirectiveCFIDefCfa(IDLoc);
1431 case DK_CFI_DEF_CFA_OFFSET:
1432 return ParseDirectiveCFIDefCfaOffset();
1433 case DK_CFI_ADJUST_CFA_OFFSET:
1434 return ParseDirectiveCFIAdjustCfaOffset();
1435 case DK_CFI_DEF_CFA_REGISTER:
1436 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1437 case DK_CFI_OFFSET:
1438 return ParseDirectiveCFIOffset(IDLoc);
1439 case DK_CFI_REL_OFFSET:
1440 return ParseDirectiveCFIRelOffset(IDLoc);
1441 case DK_CFI_PERSONALITY:
1442 return ParseDirectiveCFIPersonalityOrLsda(true);
1443 case DK_CFI_LSDA:
1444 return ParseDirectiveCFIPersonalityOrLsda(false);
1445 case DK_CFI_REMEMBER_STATE:
1446 return ParseDirectiveCFIRememberState();
1447 case DK_CFI_RESTORE_STATE:
1448 return ParseDirectiveCFIRestoreState();
1449 case DK_CFI_SAME_VALUE:
1450 return ParseDirectiveCFISameValue(IDLoc);
1451 case DK_CFI_RESTORE:
1452 return ParseDirectiveCFIRestore(IDLoc);
1453 case DK_CFI_ESCAPE:
1454 return ParseDirectiveCFIEscape();
1455 case DK_CFI_SIGNAL_FRAME:
1456 return ParseDirectiveCFISignalFrame();
1457 case DK_CFI_UNDEFINED:
1458 return ParseDirectiveCFIUndefined(IDLoc);
1459 case DK_CFI_REGISTER:
1460 return ParseDirectiveCFIRegister(IDLoc);
1461 case DK_MACROS_ON:
1462 case DK_MACROS_OFF:
1463 return ParseDirectiveMacrosOnOff(IDVal);
1464 case DK_MACRO:
1465 return ParseDirectiveMacro(IDLoc);
1466 case DK_ENDM:
1467 case DK_ENDMACRO:
1468 return ParseDirectiveEndMacro(IDVal);
1469 case DK_PURGEM:
1470 return ParseDirectivePurgeMacro(IDLoc);
Eli Friedman5d68ec22010-07-19 04:17:25 +00001471 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001472
Jim Grosbach686c0182012-05-01 18:38:27 +00001473 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001474 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001475
Chad Rosier469b1442013-02-12 21:33:51 +00001476 // __asm _emit or __asm __emit
1477 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1478 IDVal == "_EMIT" || IDVal == "__EMIT"))
1479 return ParseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1480
1481 // __asm align
1482 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1483 return ParseDirectiveMSAlign(IDLoc, Info);
Eli Friedman2128aae2012-10-22 23:58:19 +00001484
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001485 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001486
Chris Lattnera7f13542010-05-19 23:34:33 +00001487 // Canonicalize the opcode to lower case.
Eli Benderskyed5df012013-01-16 19:32:36 +00001488 std::string OpcodeStr = IDVal.lower();
Chad Rosier6a020a72012-10-25 20:41:34 +00001489 ParseInstructionInfo IInfo(Info.AsmRewrites);
Eli Benderskyed5df012013-01-16 19:32:36 +00001490 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr,
1491 IDLoc, Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001492 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001493
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001494 // Dump the parsed representation, if requested.
1495 if (getShowParsedOperands()) {
1496 SmallString<256> Str;
1497 raw_svector_ostream OS(Str);
1498 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001499 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001500 if (i != 0)
1501 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001502 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001503 }
1504 OS << "]";
1505
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001506 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001507 }
1508
Kevin Enderby613b7572011-11-01 22:27:22 +00001509 // If we are generating dwarf for assembly source files and the current
1510 // section is the initial text section then generate a .loc directive for
1511 // the instruction.
1512 if (!HadError && getContext().getGenDwarfForAssembly() &&
Peter Collingbournedf39be62013-04-17 21:18:16 +00001513 getContext().getGenDwarfSection() ==
1514 getStreamer().getCurrentSection().first) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001515
Eli Benderskyed5df012013-01-16 19:32:36 +00001516 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
Kevin Enderby938482f2012-11-01 17:31:35 +00001517
Eli Benderskyed5df012013-01-16 19:32:36 +00001518 // If we previously parsed a cpp hash file line comment then make sure the
1519 // current Dwarf File is for the CppHashFilename if not then emit the
1520 // Dwarf File table for it and adjust the line number for the .loc.
Manman Ren9e999ad2013-03-12 20:17:00 +00001521 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
Eli Benderskyed5df012013-01-16 19:32:36 +00001522 getContext().getMCDwarfFiles();
1523 if (CppHashFilename.size() != 0) {
1524 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
Kevin Enderby938482f2012-11-01 17:31:35 +00001525 CppHashFilename)
Eli Benderskyed5df012013-01-16 19:32:36 +00001526 getStreamer().EmitDwarfFileDirective(
1527 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001528
Kevin Enderbya8959492013-06-21 20:51:39 +00001529 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1530 // cache with the different Loc from the call above we save the last
1531 // info we queried here with SrcMgr.FindLineNumber().
1532 unsigned CppHashLocLineNo;
1533 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1534 CppHashLocLineNo = LastQueryLine;
1535 else {
1536 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1537 LastQueryLine = CppHashLocLineNo;
1538 LastQueryIDLoc = CppHashLoc;
1539 LastQueryBuffer = CppHashBuf;
1540 }
Kevin Enderby938482f2012-11-01 17:31:35 +00001541 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
Eli Benderskyed5df012013-01-16 19:32:36 +00001542 }
Kevin Enderby938482f2012-11-01 17:31:35 +00001543
Kevin Enderby613b7572011-11-01 22:27:22 +00001544 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001545 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001546 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001547 StringRef());
1548 }
1549
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001550 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001551 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001552 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001553 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1554 Info.ParsedOperands,
1555 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001556 ParsingInlineAsm);
1557 }
Chris Lattner98986712010-01-14 22:21:20 +00001558
Chris Lattnercbf8a982010-09-11 16:18:25 +00001559 // Don't skip the rest of the line, the instruction parser is responsible for
1560 // that.
1561 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001562}
Chris Lattner9a023f72009-06-24 04:43:34 +00001563
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001564/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1565/// since they may not be able to be tokenized to get to the end of line token.
1566void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001567 if (!Lexer.is(AsmToken::EndOfStatement))
1568 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001569 // Eat EOL.
1570 Lex();
1571}
1572
1573/// ParseCppHashLineFilenameComment as this:
1574/// ::= # number "filename"
1575/// or just as a full line comment if it doesn't have a number and a string.
1576bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1577 Lex(); // Eat the hash token.
1578
1579 if (getLexer().isNot(AsmToken::Integer)) {
1580 // Consume the line since in cases it is not a well-formed line directive,
1581 // as if were simply a full line comment.
1582 EatToEndOfLine();
1583 return false;
1584 }
1585
1586 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001587 Lex();
1588
1589 if (getLexer().isNot(AsmToken::String)) {
1590 EatToEndOfLine();
1591 return false;
1592 }
1593
1594 StringRef Filename = getTok().getString();
1595 // Get rid of the enclosing quotes.
1596 Filename = Filename.substr(1, Filename.size()-2);
1597
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001598 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1599 CppHashLoc = L;
1600 CppHashFilename = Filename;
1601 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001602 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001603
1604 // Ignore any trailing characters, they're just comment.
1605 EatToEndOfLine();
1606 return false;
1607}
1608
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001609/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001610/// for the Filename and LineNo if any in the diagnostic.
1611void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1612 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1613 raw_ostream &OS = errs();
1614
1615 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1616 const SMLoc &DiagLoc = Diag.getLoc();
1617 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1618 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1619
1620 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1621 // before printing the message.
1622 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001623 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001624 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1625 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1626 }
1627
Eric Christopher2318ba12012-12-18 00:30:54 +00001628 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001629 // manager changed or buffer changed (like in a nested include) then just
1630 // print the normal diagnostic using its Filename and LineNo.
1631 if (!Parser->CppHashLineNumber ||
1632 &DiagSrcMgr != &Parser->SrcMgr ||
1633 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001634 if (Parser->SavedDiagHandler)
1635 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1636 else
1637 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001638 return;
1639 }
1640
Eric Christopher2318ba12012-12-18 00:30:54 +00001641 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001642 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1643 // the diagnostic.
1644 const std::string Filename = Parser->CppHashFilename;
1645
1646 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1647 int CppHashLocLineNo =
1648 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1649 int LineNo = Parser->CppHashLineNumber - 1 +
1650 (DiagLocLineNo - CppHashLocLineNo);
1651
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001652 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1653 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001654 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001655 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001656
Benjamin Kramer04a04262011-10-16 10:48:29 +00001657 if (Parser->SavedDiagHandler)
1658 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1659 else
1660 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001661}
1662
Rafael Espindola799aacf2012-08-21 18:29:30 +00001663// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1664// difference being that that function accepts '@' as part of identifiers and
1665// we can't do that. AsmLexer.cpp should probably be changed to handle
1666// '@' as a special case when needed.
1667static bool isIdentifierChar(char c) {
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001668 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1669 c == '.';
Rafael Espindola799aacf2012-08-21 18:29:30 +00001670}
1671
Rafael Espindola761cb062012-06-03 23:57:14 +00001672bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001673 const MCAsmMacroParameters &Parameters,
1674 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001675 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001676 unsigned NParameters = Parameters.size();
1677 if (NParameters != 0 && NParameters != A.size())
1678 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001679
Preston Gurd7b6f2032012-09-19 20:36:12 +00001680 // A macro without parameters is handled differently on Darwin:
1681 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001682 while (!Body.empty()) {
1683 // Scan for the next substitution.
1684 std::size_t End = Body.size(), Pos = 0;
1685 for (; Pos != End; ++Pos) {
1686 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001687 if (!NParameters) {
1688 // This macro has no parameters, look for $0, $1, etc.
1689 if (Body[Pos] != '$' || Pos + 1 == End)
1690 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001691
Rafael Espindola65366442011-06-05 02:43:45 +00001692 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001693 if (Next == '$' || Next == 'n' ||
1694 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola65366442011-06-05 02:43:45 +00001695 break;
1696 } else {
1697 // This macro has parameters, look for \foo, \bar, etc.
1698 if (Body[Pos] == '\\' && Pos + 1 != End)
1699 break;
1700 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001701 }
1702
1703 // Add the prefix.
1704 OS << Body.slice(0, Pos);
1705
1706 // Check if we reached the end.
1707 if (Pos == End)
1708 break;
1709
Rafael Espindola65366442011-06-05 02:43:45 +00001710 if (!NParameters) {
1711 switch (Body[Pos+1]) {
1712 // $$ => $
1713 case '$':
1714 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001715 break;
1716
Rafael Espindola65366442011-06-05 02:43:45 +00001717 // $n => number of arguments
1718 case 'n':
1719 OS << A.size();
1720 break;
1721
1722 // $[0-9] => argument
1723 default: {
1724 // Missing arguments are ignored.
1725 unsigned Index = Body[Pos+1] - '0';
1726 if (Index >= A.size())
1727 break;
1728
1729 // Otherwise substitute with the token values, with spaces eliminated.
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001730 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001731 ie = A[Index].end(); it != ie; ++it)
1732 OS << it->getString();
1733 break;
1734 }
1735 }
1736 Pos += 2;
1737 } else {
1738 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001739 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001740 ++I;
1741
1742 const char *Begin = Body.data() + Pos +1;
1743 StringRef Argument(Begin, I - (Pos +1));
1744 unsigned Index = 0;
1745 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001746 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001747 break;
1748
Preston Gurd7b6f2032012-09-19 20:36:12 +00001749 if (Index == NParameters) {
1750 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1751 Pos += 3;
1752 else {
1753 OS << '\\' << Argument;
1754 Pos = I;
1755 }
1756 } else {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001757 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Preston Gurd7b6f2032012-09-19 20:36:12 +00001758 ie = A[Index].end(); it != ie; ++it)
1759 if (it->getKind() == AsmToken::String)
1760 OS << it->getStringContents();
1761 else
1762 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001763
Preston Gurd7b6f2032012-09-19 20:36:12 +00001764 Pos += 1 + Argument.size();
1765 }
Rafael Espindola65366442011-06-05 02:43:45 +00001766 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001767 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001768 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001769 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001770
Rafael Espindola65366442011-06-05 02:43:45 +00001771 return false;
1772}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001773
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001774MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001775 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001776 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001777 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1778 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001779{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001780}
1781
Preston Gurd7b6f2032012-09-19 20:36:12 +00001782static bool IsOperator(AsmToken::TokenKind kind)
1783{
1784 switch (kind)
1785 {
1786 default:
1787 return false;
1788 case AsmToken::Plus:
1789 case AsmToken::Minus:
1790 case AsmToken::Tilde:
1791 case AsmToken::Slash:
1792 case AsmToken::Star:
1793 case AsmToken::Dot:
1794 case AsmToken::Equal:
1795 case AsmToken::EqualEqual:
1796 case AsmToken::Pipe:
1797 case AsmToken::PipePipe:
1798 case AsmToken::Caret:
1799 case AsmToken::Amp:
1800 case AsmToken::AmpAmp:
1801 case AsmToken::Exclaim:
1802 case AsmToken::ExclaimEqual:
1803 case AsmToken::Percent:
1804 case AsmToken::Less:
1805 case AsmToken::LessEqual:
1806 case AsmToken::LessLess:
1807 case AsmToken::LessGreater:
1808 case AsmToken::Greater:
1809 case AsmToken::GreaterEqual:
1810 case AsmToken::GreaterGreater:
1811 return true;
1812 }
1813}
1814
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001815bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
Preston Gurd7b6f2032012-09-19 20:36:12 +00001816 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001817 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001818 unsigned AddTokens = 0;
1819
1820 // gas accepts arguments separated by whitespace, except on Darwin
1821 if (!IsDarwin)
1822 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001823
1824 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001825 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1826 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001827 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001828 }
1829
1830 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1831 // Spaces and commas cannot be mixed to delimit parameters
1832 if (ArgumentDelimiter == AsmToken::Eof)
1833 ArgumentDelimiter = AsmToken::Comma;
1834 else if (ArgumentDelimiter != AsmToken::Comma) {
1835 Lexer.setSkipSpace(true);
1836 return TokError("expected ' ' for macro argument separator");
1837 }
1838 break;
1839 }
1840
1841 if (Lexer.is(AsmToken::Space)) {
1842 Lex(); // Eat spaces
1843
1844 // Spaces can delimit parameters, but could also be part an expression.
1845 // If the token after a space is an operator, add the token and the next
1846 // one into this argument
1847 if (ArgumentDelimiter == AsmToken::Space ||
1848 ArgumentDelimiter == AsmToken::Eof) {
1849 if (IsOperator(Lexer.getKind())) {
1850 // Check to see whether the token is used as an operator,
1851 // or part of an identifier
Jordan Rose3ebe59c2013-01-07 19:00:49 +00001852 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd7b6f2032012-09-19 20:36:12 +00001853 if (*NextChar == ' ')
1854 AddTokens = 2;
1855 }
1856
1857 if (!AddTokens && ParenLevel == 0) {
1858 if (ArgumentDelimiter == AsmToken::Eof &&
1859 !IsOperator(Lexer.getKind()))
1860 ArgumentDelimiter = AsmToken::Space;
1861 break;
1862 }
1863 }
1864 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001865
1866 // HandleMacroEntry relies on not advancing the lexer here
1867 // to be able to fill in the remaining default parameter values
1868 if (Lexer.is(AsmToken::EndOfStatement))
1869 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001870
1871 // Adjust the current parentheses level.
1872 if (Lexer.is(AsmToken::LParen))
1873 ++ParenLevel;
1874 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1875 --ParenLevel;
1876
1877 // Append the token to the current argument list.
1878 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001879 if (AddTokens)
1880 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001881 Lex();
1882 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001883
1884 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001885 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001886 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001887 return false;
1888}
1889
1890// Parse the macro instantiation arguments.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001891bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001892 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001893 // Argument delimiter is initially unknown. It will be set by
1894 // ParseMacroArgument()
1895 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001896
1897 // Parse two kinds of macro invocations:
1898 // - macros defined without any parameters accept an arbitrary number of them
1899 // - macros defined with parameters accept at most that many of them
1900 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1901 ++Parameter) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001902 MCAsmMacroArgument MA;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001903
Preston Gurd7b6f2032012-09-19 20:36:12 +00001904 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001905 return true;
1906
Preston Gurd6c9176a2012-09-19 20:29:04 +00001907 if (!MA.empty() || !NParameters)
1908 A.push_back(MA);
1909 else if (NParameters) {
1910 if (!M->Parameters[Parameter].second.empty())
1911 A.push_back(M->Parameters[Parameter].second);
1912 }
Jim Grosbach97146442012-07-30 22:44:17 +00001913
Preston Gurd6c9176a2012-09-19 20:29:04 +00001914 // At the end of the statement, fill in remaining arguments that have
1915 // default values. If there aren't any, then the next argument is
1916 // required but missing
1917 if (Lexer.is(AsmToken::EndOfStatement)) {
1918 if (NParameters && Parameter < NParameters - 1) {
1919 if (M->Parameters[Parameter + 1].second.empty())
1920 return TokError("macro argument '" +
1921 Twine(M->Parameters[Parameter + 1].first) +
1922 "' is missing");
1923 else
1924 continue;
1925 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001926 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001927 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001928
1929 if (Lexer.is(AsmToken::Comma))
1930 Lex();
1931 }
1932 return TokError("Too many arguments");
1933}
1934
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001935const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1936 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1937 return (I == MacroMap.end()) ? NULL : I->getValue();
1938}
1939
1940void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1941 MacroMap[Name] = new MCAsmMacro(Macro);
1942}
1943
1944void AsmParser::UndefineMacro(StringRef Name) {
1945 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1946 if (I != MacroMap.end()) {
1947 delete I->getValue();
1948 MacroMap.erase(I);
1949 }
1950}
1951
1952bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001953 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1954 // this, although we should protect against infinite loops.
1955 if (ActiveMacros.size() == 20)
1956 return TokError("macros cannot be nested more than 20 levels deep");
1957
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001958 MCAsmMacroArguments A;
Rafael Espindola8a403d32012-08-08 14:51:03 +00001959 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001960 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001961
Jim Grosbach97146442012-07-30 22:44:17 +00001962 // Remove any trailing empty arguments. Do this after-the-fact as we have
1963 // to keep empty arguments in the middle of the list or positionality
1964 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001965 while (!A.empty() && A.back().empty())
1966 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001967
Rafael Espindola65366442011-06-05 02:43:45 +00001968 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1969 // to hold the macro body with substitutions.
1970 SmallString<256> Buf;
1971 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001972 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001973
Rafael Espindola8a403d32012-08-08 14:51:03 +00001974 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001975 return true;
1976
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001977 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola761cb062012-06-03 23:57:14 +00001978 // instantiation.
1979 OS << ".endmacro\n";
1980
Rafael Espindola65366442011-06-05 02:43:45 +00001981 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001982 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001983
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001984 // Create the macro instantiation object and add to the current macro
1985 // instantiation stack.
1986 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001987 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001988 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001989 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001990 ActiveMacros.push_back(MI);
1991
1992 // Jump to the macro instantiation and prime the lexer.
1993 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1994 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1995 Lex();
1996
1997 return false;
1998}
1999
2000void AsmParser::HandleMacroExit() {
2001 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00002002 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00002003 Lex();
2004
2005 // Pop the instantiation entry.
2006 delete ActiveMacros.back();
2007 ActiveMacros.pop_back();
2008}
2009
Rafael Espindolae71cc862012-01-28 05:57:00 +00002010static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002011 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00002012 case MCExpr::Binary: {
2013 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
2014 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002015 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00002016 case MCExpr::Target:
2017 case MCExpr::Constant:
2018 return false;
2019 case MCExpr::SymbolRef: {
2020 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00002021 if (S.isVariable())
2022 return IsUsedIn(Sym, S.getVariableValue());
2023 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00002024 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002025 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00002026 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002027 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00002028
2029 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002030}
2031
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002032bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
2033 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002034 // FIXME: Use better location, we should use proper tokens.
2035 SMLoc EqualLoc = Lexer.getLoc();
2036
Daniel Dunbar821e3332009-08-31 08:09:28 +00002037 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002038 if (parseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002039 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002040
Rafael Espindolae71cc862012-01-28 05:57:00 +00002041 // Note: we don't count b as used in "a = b". This is to allow
2042 // a = b
2043 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002044
Daniel Dunbar3f872332009-07-28 16:08:33 +00002045 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002046 return TokError("unexpected token in assignment");
2047
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00002048 // Error on assignment to '.'.
2049 if (Name == ".") {
2050 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2051 "(use '.space' or '.org').)"));
2052 }
2053
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002054 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00002055 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002056
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002057 // Validate that the LHS is allowed to be a variable (either it has not been
2058 // used as a symbol, or it is an absolute symbol).
2059 MCSymbol *Sym = getContext().LookupSymbol(Name);
2060 if (Sym) {
2061 // Diagnose assignment to a label.
2062 //
2063 // FIXME: Diagnostics. Note the location of the definition as a label.
2064 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00002065 if (IsUsedIn(Sym, Value))
2066 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2067 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00002068 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00002069 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2070 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00002071 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002072 return Error(EqualLoc, "redefinition of '" + Name + "'");
2073 else if (!Sym->isVariable())
2074 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00002075 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002076 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2077 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002078
2079 // Don't count these checks as uses.
2080 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002081 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002082 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002083
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002084 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002085
2086 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00002087 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002088 if (NoDeadStrip)
2089 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2090
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002091
2092 return false;
2093}
2094
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002095/// parseIdentifier:
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002096/// ::= identifier
2097/// ::= string
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002098bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00002099 // The assembler has relaxed rules for accepting identifiers, in particular we
2100 // allow things like '.globl $foo', which would normally be separate
2101 // tokens. At this level, we have already lexed so we cannot (currently)
2102 // handle this as a context dependent token, instead we detect adjacent tokens
2103 // and return the combined identifier.
2104 if (Lexer.is(AsmToken::Dollar)) {
2105 SMLoc DollarLoc = getLexer().getLoc();
2106
2107 // Consume the dollar sign, and check for a following identifier.
2108 Lex();
2109 if (Lexer.isNot(AsmToken::Identifier))
2110 return true;
2111
2112 // We have a '$' followed by an identifier, make sure they are adjacent.
2113 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2114 return true;
2115
2116 // Construct the joined identifier and consume the token.
2117 Res = StringRef(DollarLoc.getPointer(),
2118 getTok().getIdentifier().size() + 1);
2119 Lex();
2120 return false;
2121 }
2122
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002123 if (Lexer.isNot(AsmToken::Identifier) &&
2124 Lexer.isNot(AsmToken::String))
2125 return true;
2126
Sean Callanan18b83232010-01-19 21:44:56 +00002127 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002128
Sean Callanan79ed1a82010-01-19 20:22:31 +00002129 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002130
2131 return false;
2132}
2133
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002134/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002135/// ::= .equ identifier ',' expression
2136/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002137/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002138bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002139 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002140
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002141 if (parseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002142 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002143
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002144 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002145 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002146 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002147
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002148 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002149}
2150
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002151bool AsmParser::parseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002152 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002153
2154 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002155 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002156 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2157 if (Str[i] != '\\') {
2158 Data += Str[i];
2159 continue;
2160 }
2161
2162 // Recognize escaped characters. Note that this escape semantics currently
2163 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2164 ++i;
2165 if (i == e)
2166 return TokError("unexpected backslash at end of string");
2167
2168 // Recognize octal sequences.
2169 if ((unsigned) (Str[i] - '0') <= 7) {
2170 // Consume up to three octal characters.
2171 unsigned Value = Str[i] - '0';
2172
2173 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2174 ++i;
2175 Value = Value * 8 + (Str[i] - '0');
2176
2177 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2178 ++i;
2179 Value = Value * 8 + (Str[i] - '0');
2180 }
2181 }
2182
2183 if (Value > 255)
2184 return TokError("invalid octal escape sequence (out of range)");
2185
2186 Data += (unsigned char) Value;
2187 continue;
2188 }
2189
2190 // Otherwise recognize individual escapes.
2191 switch (Str[i]) {
2192 default:
2193 // Just reject invalid escape sequences for now.
2194 return TokError("invalid escape sequence (unrecognized character)");
2195
2196 case 'b': Data += '\b'; break;
2197 case 'f': Data += '\f'; break;
2198 case 'n': Data += '\n'; break;
2199 case 'r': Data += '\r'; break;
2200 case 't': Data += '\t'; break;
2201 case '"': Data += '"'; break;
2202 case '\\': Data += '\\'; break;
2203 }
2204 }
2205
2206 return false;
2207}
2208
Daniel Dunbara0d14262009-06-24 23:30:00 +00002209/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002210/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2211bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002212 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002213 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002214
Daniel Dunbara0d14262009-06-24 23:30:00 +00002215 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002216 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002217 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002218
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002219 std::string Data;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002220 if (parseEscapedString(Data))
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002221 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002222
2223 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002224 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002225 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2226
Sean Callanan79ed1a82010-01-19 20:22:31 +00002227 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002228
2229 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002230 break;
2231
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002232 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002233 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002234 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002235 }
2236 }
2237
Sean Callanan79ed1a82010-01-19 20:22:31 +00002238 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002239 return false;
2240}
2241
2242/// ParseDirectiveValue
2243/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2244bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002245 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002246 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002247
Daniel Dunbara0d14262009-06-24 23:30:00 +00002248 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002249 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002250 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002251 if (parseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002252 return true;
2253
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002254 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002255 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2256 assert(Size <= 8 && "Invalid size");
2257 uint64_t IntValue = MCE->getValue();
2258 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2259 return Error(ExprLoc, "literal value out of range for directive");
2260 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2261 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002262 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002263
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002264 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002265 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002266
Daniel Dunbara0d14262009-06-24 23:30:00 +00002267 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002268 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002269 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002270 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002271 }
2272 }
2273
Sean Callanan79ed1a82010-01-19 20:22:31 +00002274 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002275 return false;
2276}
2277
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002278/// ParseDirectiveRealValue
2279/// ::= (.single | .double) [ expression (, expression)* ]
2280bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2281 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002282 checkForValidSection();
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002283
2284 for (;;) {
2285 // We don't truly support arithmetic on floating point expressions, so we
2286 // have to manually parse unary prefixes.
2287 bool IsNeg = false;
2288 if (getLexer().is(AsmToken::Minus)) {
2289 Lex();
2290 IsNeg = true;
2291 } else if (getLexer().is(AsmToken::Plus))
2292 Lex();
2293
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002294 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002295 getLexer().isNot(AsmToken::Real) &&
2296 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002297 return TokError("unexpected token in directive");
2298
2299 // Convert to an APFloat.
2300 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002301 StringRef IDVal = getTok().getString();
2302 if (getLexer().is(AsmToken::Identifier)) {
2303 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2304 Value = APFloat::getInf(Semantics);
2305 else if (!IDVal.compare_lower("nan"))
2306 Value = APFloat::getNaN(Semantics, false, ~0);
2307 else
2308 return TokError("invalid floating point literal");
2309 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002310 APFloat::opInvalidOp)
2311 return TokError("invalid floating point literal");
2312 if (IsNeg)
2313 Value.changeSign();
2314
2315 // Consume the numeric token.
2316 Lex();
2317
2318 // Emit the value as an integer.
2319 APInt AsInt = Value.bitcastToAPInt();
2320 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2321 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2322
2323 if (getLexer().is(AsmToken::EndOfStatement))
2324 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002325
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002326 if (getLexer().isNot(AsmToken::Comma))
2327 return TokError("unexpected token in directive");
2328 Lex();
2329 }
2330 }
2331
2332 Lex();
2333 return false;
2334}
2335
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002336/// ParseDirectiveZero
2337/// ::= .zero expression
2338bool AsmParser::ParseDirectiveZero() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002339 checkForValidSection();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002340
2341 int64_t NumBytes;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002342 if (parseAbsoluteExpression(NumBytes))
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002343 return true;
2344
Rafael Espindolae452b172010-10-05 19:42:57 +00002345 int64_t Val = 0;
2346 if (getLexer().is(AsmToken::Comma)) {
2347 Lex();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002348 if (parseAbsoluteExpression(Val))
Rafael Espindolae452b172010-10-05 19:42:57 +00002349 return true;
2350 }
2351
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002352 if (getLexer().isNot(AsmToken::EndOfStatement))
2353 return TokError("unexpected token in '.zero' directive");
2354
2355 Lex();
2356
Rafael Espindolae452b172010-10-05 19:42:57 +00002357 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002358
2359 return false;
2360}
2361
Daniel Dunbara0d14262009-06-24 23:30:00 +00002362/// ParseDirectiveFill
2363/// ::= .fill expression , expression , expression
2364bool AsmParser::ParseDirectiveFill() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002365 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002366
Daniel Dunbara0d14262009-06-24 23:30:00 +00002367 int64_t NumValues;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002368 if (parseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002369 return true;
2370
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002371 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002372 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002373 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002374
Daniel Dunbara0d14262009-06-24 23:30:00 +00002375 int64_t FillSize;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002376 if (parseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002377 return true;
2378
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002379 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002380 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002381 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002382
Daniel Dunbara0d14262009-06-24 23:30:00 +00002383 int64_t FillExpr;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002384 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002385 return true;
2386
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002387 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002388 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002389
Sean Callanan79ed1a82010-01-19 20:22:31 +00002390 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002391
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002392 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2393 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002394
2395 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002396 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002397
2398 return false;
2399}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002400
2401/// ParseDirectiveOrg
2402/// ::= .org expression [ , expression ]
2403bool AsmParser::ParseDirectiveOrg() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002404 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002405
Daniel Dunbar821e3332009-08-31 08:09:28 +00002406 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002407 SMLoc Loc = getTok().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002408 if (parseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002409 return true;
2410
2411 // Parse optional fill expression.
2412 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002413 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2414 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002415 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002416 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002417
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002418 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002419 return true;
2420
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002421 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002422 return TokError("unexpected token in '.org' directive");
2423 }
2424
Sean Callanan79ed1a82010-01-19 20:22:31 +00002425 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002426
Jim Grosbachebd4c052012-01-27 00:37:08 +00002427 // Only limited forms of relocatable expressions are accepted here, it
2428 // has to be relative to the current section. The streamer will return
2429 // 'true' if the expression wasn't evaluatable.
2430 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2431 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002432
2433 return false;
2434}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002435
2436/// ParseDirectiveAlign
2437/// ::= {.align, ...} expression [ , expression [ , expression ]]
2438bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002439 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002440
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002441 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002442 int64_t Alignment;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002443 if (parseAbsoluteExpression(Alignment))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002444 return true;
2445
2446 SMLoc MaxBytesLoc;
2447 bool HasFillExpr = false;
2448 int64_t FillExpr = 0;
2449 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002450 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2451 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002452 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002453 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002454
2455 // The fill expression can be omitted while specifying a maximum number of
2456 // alignment bytes, e.g:
2457 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002458 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002459 HasFillExpr = true;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002460 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002461 return true;
2462 }
2463
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002464 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2465 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002466 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002467 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002468
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002469 MaxBytesLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002470 if (parseAbsoluteExpression(MaxBytesToFill))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002471 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002472
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002473 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002474 return TokError("unexpected token in directive");
2475 }
2476 }
2477
Sean Callanan79ed1a82010-01-19 20:22:31 +00002478 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002479
Daniel Dunbar648ac512010-05-17 21:54:30 +00002480 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002481 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002482
2483 // Compute alignment in bytes.
2484 if (IsPow2) {
2485 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002486 if (Alignment >= 32) {
2487 Error(AlignmentLoc, "invalid alignment value");
2488 Alignment = 31;
2489 }
2490
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002491 Alignment = 1ULL << Alignment;
Benjamin Kramer8a89cf22013-02-16 15:00:16 +00002492 } else {
2493 // Reject alignments that aren't a power of two, for gas compatibility.
2494 if (!isPowerOf2_64(Alignment))
2495 Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002496 }
2497
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002498 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002499 if (MaxBytesLoc.isValid()) {
2500 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002501 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2502 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002503 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002504 }
2505
2506 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002507 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2508 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002509 MaxBytesToFill = 0;
2510 }
2511 }
2512
Daniel Dunbar648ac512010-05-17 21:54:30 +00002513 // Check whether we should use optimal code alignment for this .align
2514 // directive.
Peter Collingbournedf39be62013-04-17 21:18:16 +00002515 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002516 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2517 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002518 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002519 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002520 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002521 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2522 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002523 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002524
2525 return false;
2526}
2527
Eli Bendersky6ee13082013-01-15 22:59:42 +00002528/// ParseDirectiveFile
2529/// ::= .file [number] filename
2530/// ::= .file number directory filename
2531bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2532 // FIXME: I'm not sure what this is.
2533 int64_t FileNumber = -1;
2534 SMLoc FileNumberLoc = getLexer().getLoc();
2535 if (getLexer().is(AsmToken::Integer)) {
2536 FileNumber = getTok().getIntVal();
2537 Lex();
2538
2539 if (FileNumber < 1)
2540 return TokError("file number less than one");
2541 }
2542
2543 if (getLexer().isNot(AsmToken::String))
2544 return TokError("unexpected token in '.file' directive");
2545
2546 // Usually the directory and filename together, otherwise just the directory.
2547 StringRef Path = getTok().getString();
2548 Path = Path.substr(1, Path.size()-2);
2549 Lex();
2550
2551 StringRef Directory;
2552 StringRef Filename;
2553 if (getLexer().is(AsmToken::String)) {
2554 if (FileNumber == -1)
2555 return TokError("explicit path specified, but no file number");
2556 Filename = getTok().getString();
2557 Filename = Filename.substr(1, Filename.size()-2);
2558 Directory = Path;
2559 Lex();
2560 } else {
2561 Filename = Path;
2562 }
2563
2564 if (getLexer().isNot(AsmToken::EndOfStatement))
2565 return TokError("unexpected token in '.file' directive");
2566
2567 if (FileNumber == -1)
2568 getStreamer().EmitFileDirective(Filename);
2569 else {
2570 if (getContext().getGenDwarfForAssembly() == true)
2571 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2572 "used to generate dwarf debug info for assembly code");
2573
2574 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2575 Error(FileNumberLoc, "file number already allocated");
2576 }
2577
2578 return false;
2579}
2580
2581/// ParseDirectiveLine
2582/// ::= .line [number]
2583bool AsmParser::ParseDirectiveLine() {
2584 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2585 if (getLexer().isNot(AsmToken::Integer))
2586 return TokError("unexpected token in '.line' directive");
2587
2588 int64_t LineNumber = getTok().getIntVal();
2589 (void) LineNumber;
2590 Lex();
2591
2592 // FIXME: Do something with the .line.
2593 }
2594
2595 if (getLexer().isNot(AsmToken::EndOfStatement))
2596 return TokError("unexpected token in '.line' directive");
2597
2598 return false;
2599}
2600
2601/// ParseDirectiveLoc
2602/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2603/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2604/// The first number is a file number, must have been previously assigned with
2605/// a .file directive, the second number is the line number and optionally the
2606/// third number is a column position (zero if not specified). The remaining
2607/// optional items are .loc sub-directives.
2608bool AsmParser::ParseDirectiveLoc() {
2609 if (getLexer().isNot(AsmToken::Integer))
2610 return TokError("unexpected token in '.loc' directive");
2611 int64_t FileNumber = getTok().getIntVal();
2612 if (FileNumber < 1)
2613 return TokError("file number less than one in '.loc' directive");
2614 if (!getContext().isValidDwarfFileNumber(FileNumber))
2615 return TokError("unassigned file number in '.loc' directive");
2616 Lex();
2617
2618 int64_t LineNumber = 0;
2619 if (getLexer().is(AsmToken::Integer)) {
2620 LineNumber = getTok().getIntVal();
2621 if (LineNumber < 1)
2622 return TokError("line number less than one in '.loc' directive");
2623 Lex();
2624 }
2625
2626 int64_t ColumnPos = 0;
2627 if (getLexer().is(AsmToken::Integer)) {
2628 ColumnPos = getTok().getIntVal();
2629 if (ColumnPos < 0)
2630 return TokError("column position less than zero in '.loc' directive");
2631 Lex();
2632 }
2633
2634 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2635 unsigned Isa = 0;
2636 int64_t Discriminator = 0;
2637 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2638 for (;;) {
2639 if (getLexer().is(AsmToken::EndOfStatement))
2640 break;
2641
2642 StringRef Name;
2643 SMLoc Loc = getTok().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002644 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002645 return TokError("unexpected token in '.loc' directive");
2646
2647 if (Name == "basic_block")
2648 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2649 else if (Name == "prologue_end")
2650 Flags |= DWARF2_FLAG_PROLOGUE_END;
2651 else if (Name == "epilogue_begin")
2652 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2653 else if (Name == "is_stmt") {
2654 Loc = getTok().getLoc();
2655 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002656 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002657 return true;
2658 // The expression must be the constant 0 or 1.
2659 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2660 int Value = MCE->getValue();
2661 if (Value == 0)
2662 Flags &= ~DWARF2_FLAG_IS_STMT;
2663 else if (Value == 1)
2664 Flags |= DWARF2_FLAG_IS_STMT;
2665 else
2666 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperefa703d2013-04-22 04:22:40 +00002667 } else {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002668 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2669 }
Craig Topperefa703d2013-04-22 04:22:40 +00002670 } else if (Name == "isa") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002671 Loc = getTok().getLoc();
2672 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002673 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002674 return true;
2675 // The expression must be a constant greater or equal to 0.
2676 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2677 int Value = MCE->getValue();
2678 if (Value < 0)
2679 return Error(Loc, "isa number less than zero");
2680 Isa = Value;
Craig Topperefa703d2013-04-22 04:22:40 +00002681 } else {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002682 return Error(Loc, "isa number not a constant value");
2683 }
Craig Topperefa703d2013-04-22 04:22:40 +00002684 } else if (Name == "discriminator") {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002685 if (parseAbsoluteExpression(Discriminator))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002686 return true;
Craig Topperefa703d2013-04-22 04:22:40 +00002687 } else {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002688 return Error(Loc, "unknown sub-directive in '.loc' directive");
2689 }
2690
2691 if (getLexer().is(AsmToken::EndOfStatement))
2692 break;
2693 }
2694 }
2695
2696 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2697 Isa, Discriminator, StringRef());
2698
2699 return false;
2700}
2701
2702/// ParseDirectiveStabs
2703/// ::= .stabs string, number, number, number
2704bool AsmParser::ParseDirectiveStabs() {
2705 return TokError("unsupported directive '.stabs'");
2706}
2707
2708/// ParseDirectiveCFISections
2709/// ::= .cfi_sections section [, section]
2710bool AsmParser::ParseDirectiveCFISections() {
2711 StringRef Name;
2712 bool EH = false;
2713 bool Debug = false;
2714
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002715 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002716 return TokError("Expected an identifier");
2717
2718 if (Name == ".eh_frame")
2719 EH = true;
2720 else if (Name == ".debug_frame")
2721 Debug = true;
2722
2723 if (getLexer().is(AsmToken::Comma)) {
2724 Lex();
2725
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002726 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002727 return TokError("Expected an identifier");
2728
2729 if (Name == ".eh_frame")
2730 EH = true;
2731 else if (Name == ".debug_frame")
2732 Debug = true;
2733 }
2734
2735 getStreamer().EmitCFISections(EH, Debug);
2736 return false;
2737}
2738
2739/// ParseDirectiveCFIStartProc
2740/// ::= .cfi_startproc
2741bool AsmParser::ParseDirectiveCFIStartProc() {
2742 getStreamer().EmitCFIStartProc();
2743 return false;
2744}
2745
2746/// ParseDirectiveCFIEndProc
2747/// ::= .cfi_endproc
2748bool AsmParser::ParseDirectiveCFIEndProc() {
2749 getStreamer().EmitCFIEndProc();
2750 return false;
2751}
2752
2753/// ParseRegisterOrRegisterNumber - parse register name or number.
2754bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2755 SMLoc DirectiveLoc) {
2756 unsigned RegNo;
2757
2758 if (getLexer().isNot(AsmToken::Integer)) {
2759 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2760 return true;
Bill Wendling99cb6222013-06-18 07:20:20 +00002761 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky6ee13082013-01-15 22:59:42 +00002762 } else
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002763 return parseAbsoluteExpression(Register);
Eli Bendersky6ee13082013-01-15 22:59:42 +00002764
2765 return false;
2766}
2767
2768/// ParseDirectiveCFIDefCfa
2769/// ::= .cfi_def_cfa register, offset
2770bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2771 int64_t Register = 0;
2772 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2773 return true;
2774
2775 if (getLexer().isNot(AsmToken::Comma))
2776 return TokError("unexpected token in directive");
2777 Lex();
2778
2779 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002780 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002781 return true;
2782
2783 getStreamer().EmitCFIDefCfa(Register, Offset);
2784 return false;
2785}
2786
2787/// ParseDirectiveCFIDefCfaOffset
2788/// ::= .cfi_def_cfa_offset offset
2789bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
2790 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002791 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002792 return true;
2793
2794 getStreamer().EmitCFIDefCfaOffset(Offset);
2795 return false;
2796}
2797
2798/// ParseDirectiveCFIRegister
2799/// ::= .cfi_register register, register
2800bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2801 int64_t Register1 = 0;
2802 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2803 return true;
2804
2805 if (getLexer().isNot(AsmToken::Comma))
2806 return TokError("unexpected token in directive");
2807 Lex();
2808
2809 int64_t Register2 = 0;
2810 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2811 return true;
2812
2813 getStreamer().EmitCFIRegister(Register1, Register2);
2814 return false;
2815}
2816
2817/// ParseDirectiveCFIAdjustCfaOffset
2818/// ::= .cfi_adjust_cfa_offset adjustment
2819bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
2820 int64_t Adjustment = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002821 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002822 return true;
2823
2824 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2825 return false;
2826}
2827
2828/// ParseDirectiveCFIDefCfaRegister
2829/// ::= .cfi_def_cfa_register register
2830bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2831 int64_t Register = 0;
2832 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2833 return true;
2834
2835 getStreamer().EmitCFIDefCfaRegister(Register);
2836 return false;
2837}
2838
2839/// ParseDirectiveCFIOffset
2840/// ::= .cfi_offset register, offset
2841bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2842 int64_t Register = 0;
2843 int64_t Offset = 0;
2844
2845 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2846 return true;
2847
2848 if (getLexer().isNot(AsmToken::Comma))
2849 return TokError("unexpected token in directive");
2850 Lex();
2851
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002852 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002853 return true;
2854
2855 getStreamer().EmitCFIOffset(Register, Offset);
2856 return false;
2857}
2858
2859/// ParseDirectiveCFIRelOffset
2860/// ::= .cfi_rel_offset register, offset
2861bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2862 int64_t Register = 0;
2863
2864 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2865 return true;
2866
2867 if (getLexer().isNot(AsmToken::Comma))
2868 return TokError("unexpected token in directive");
2869 Lex();
2870
2871 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002872 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002873 return true;
2874
2875 getStreamer().EmitCFIRelOffset(Register, Offset);
2876 return false;
2877}
2878
2879static bool isValidEncoding(int64_t Encoding) {
2880 if (Encoding & ~0xff)
2881 return false;
2882
2883 if (Encoding == dwarf::DW_EH_PE_omit)
2884 return true;
2885
2886 const unsigned Format = Encoding & 0xf;
2887 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2888 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2889 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2890 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2891 return false;
2892
2893 const unsigned Application = Encoding & 0x70;
2894 if (Application != dwarf::DW_EH_PE_absptr &&
2895 Application != dwarf::DW_EH_PE_pcrel)
2896 return false;
2897
2898 return true;
2899}
2900
2901/// ParseDirectiveCFIPersonalityOrLsda
2902/// IsPersonality true for cfi_personality, false for cfi_lsda
2903/// ::= .cfi_personality encoding, [symbol_name]
2904/// ::= .cfi_lsda encoding, [symbol_name]
2905bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2906 int64_t Encoding = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002907 if (parseAbsoluteExpression(Encoding))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002908 return true;
2909 if (Encoding == dwarf::DW_EH_PE_omit)
2910 return false;
2911
2912 if (!isValidEncoding(Encoding))
2913 return TokError("unsupported encoding.");
2914
2915 if (getLexer().isNot(AsmToken::Comma))
2916 return TokError("unexpected token in directive");
2917 Lex();
2918
2919 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002920 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002921 return TokError("expected identifier in directive");
2922
2923 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2924
2925 if (IsPersonality)
2926 getStreamer().EmitCFIPersonality(Sym, Encoding);
2927 else
2928 getStreamer().EmitCFILsda(Sym, Encoding);
2929 return false;
2930}
2931
2932/// ParseDirectiveCFIRememberState
2933/// ::= .cfi_remember_state
2934bool AsmParser::ParseDirectiveCFIRememberState() {
2935 getStreamer().EmitCFIRememberState();
2936 return false;
2937}
2938
2939/// ParseDirectiveCFIRestoreState
2940/// ::= .cfi_remember_state
2941bool AsmParser::ParseDirectiveCFIRestoreState() {
2942 getStreamer().EmitCFIRestoreState();
2943 return false;
2944}
2945
2946/// ParseDirectiveCFISameValue
2947/// ::= .cfi_same_value register
2948bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2949 int64_t Register = 0;
2950
2951 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2952 return true;
2953
2954 getStreamer().EmitCFISameValue(Register);
2955 return false;
2956}
2957
2958/// ParseDirectiveCFIRestore
2959/// ::= .cfi_restore register
2960bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2961 int64_t Register = 0;
2962 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2963 return true;
2964
2965 getStreamer().EmitCFIRestore(Register);
2966 return false;
2967}
2968
2969/// ParseDirectiveCFIEscape
2970/// ::= .cfi_escape expression[,...]
2971bool AsmParser::ParseDirectiveCFIEscape() {
2972 std::string Values;
2973 int64_t CurrValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002974 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002975 return true;
2976
2977 Values.push_back((uint8_t)CurrValue);
2978
2979 while (getLexer().is(AsmToken::Comma)) {
2980 Lex();
2981
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002982 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002983 return true;
2984
2985 Values.push_back((uint8_t)CurrValue);
2986 }
2987
2988 getStreamer().EmitCFIEscape(Values);
2989 return false;
2990}
2991
2992/// ParseDirectiveCFISignalFrame
2993/// ::= .cfi_signal_frame
2994bool AsmParser::ParseDirectiveCFISignalFrame() {
2995 if (getLexer().isNot(AsmToken::EndOfStatement))
2996 return Error(getLexer().getLoc(),
2997 "unexpected token in '.cfi_signal_frame'");
2998
2999 getStreamer().EmitCFISignalFrame();
3000 return false;
3001}
3002
3003/// ParseDirectiveCFIUndefined
3004/// ::= .cfi_undefined register
3005bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
3006 int64_t Register = 0;
3007
3008 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3009 return true;
3010
3011 getStreamer().EmitCFIUndefined(Register);
3012 return false;
3013}
3014
3015/// ParseDirectiveMacrosOnOff
3016/// ::= .macros_on
3017/// ::= .macros_off
3018bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
3019 if (getLexer().isNot(AsmToken::EndOfStatement))
3020 return Error(getLexer().getLoc(),
3021 "unexpected token in '" + Directive + "' directive");
3022
3023 SetMacrosEnabled(Directive == ".macros_on");
3024 return false;
3025}
3026
3027/// ParseDirectiveMacro
3028/// ::= .macro name [parameters]
3029bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
3030 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003031 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003032 return TokError("expected identifier in '.macro' directive");
3033
3034 MCAsmMacroParameters Parameters;
3035 // Argument delimiter is initially unknown. It will be set by
3036 // ParseMacroArgument()
3037 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3038 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3039 for (;;) {
3040 MCAsmMacroParameter Parameter;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003041 if (parseIdentifier(Parameter.first))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003042 return TokError("expected identifier in '.macro' directive");
3043
3044 if (getLexer().is(AsmToken::Equal)) {
3045 Lex();
3046 if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3047 return true;
3048 }
3049
3050 Parameters.push_back(Parameter);
3051
3052 if (getLexer().is(AsmToken::Comma))
3053 Lex();
3054 else if (getLexer().is(AsmToken::EndOfStatement))
3055 break;
3056 }
3057 }
3058
3059 // Eat the end of statement.
3060 Lex();
3061
3062 AsmToken EndToken, StartToken = getTok();
3063
3064 // Lex the macro definition.
3065 for (;;) {
3066 // Check whether we have reached the end of the file.
3067 if (getLexer().is(AsmToken::Eof))
3068 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3069
3070 // Otherwise, check whether we have reach the .endmacro.
3071 if (getLexer().is(AsmToken::Identifier) &&
3072 (getTok().getIdentifier() == ".endm" ||
3073 getTok().getIdentifier() == ".endmacro")) {
3074 EndToken = getTok();
3075 Lex();
3076 if (getLexer().isNot(AsmToken::EndOfStatement))
3077 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3078 "' directive");
3079 break;
3080 }
3081
3082 // Otherwise, scan til the end of the statement.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003083 eatToEndOfStatement();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003084 }
3085
3086 if (LookupMacro(Name)) {
3087 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3088 }
3089
3090 const char *BodyStart = StartToken.getLoc().getPointer();
3091 const char *BodyEnd = EndToken.getLoc().getPointer();
3092 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Kevin Enderby221514e2013-01-22 21:44:53 +00003093 CheckForBadMacro(DirectiveLoc, Name, Body, Parameters);
Eli Bendersky6ee13082013-01-15 22:59:42 +00003094 DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3095 return false;
3096}
3097
Kevin Enderby221514e2013-01-22 21:44:53 +00003098/// CheckForBadMacro
3099///
3100/// With the support added for named parameters there may be code out there that
3101/// is transitioning from positional parameters. In versions of gas that did
3102/// not support named parameters they would be ignored on the macro defintion.
3103/// But to support both styles of parameters this is not possible so if a macro
3104/// defintion has named parameters but does not use them and has what appears
3105/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3106/// warning that the positional parameter found in body which have no effect.
3107/// Hoping the developer will either remove the named parameters from the macro
3108/// definiton so the positional parameters get used if that was what was
3109/// intended or change the macro to use the named parameters. It is possible
3110/// this warning will trigger when the none of the named parameters are used
3111/// and the strings like $1 are infact to simply to be passed trough unchanged.
3112void AsmParser::CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3113 StringRef Body,
3114 MCAsmMacroParameters Parameters) {
3115 // If this macro is not defined with named parameters the warning we are
3116 // checking for here doesn't apply.
3117 unsigned NParameters = Parameters.size();
3118 if (NParameters == 0)
3119 return;
3120
3121 bool NamedParametersFound = false;
3122 bool PositionalParametersFound = false;
3123
3124 // Look at the body of the macro for use of both the named parameters and what
3125 // are likely to be positional parameters. This is what expandMacro() is
3126 // doing when it finds the parameters in the body.
3127 while (!Body.empty()) {
3128 // Scan for the next possible parameter.
3129 std::size_t End = Body.size(), Pos = 0;
3130 for (; Pos != End; ++Pos) {
3131 // Check for a substitution or escape.
3132 // This macro is defined with parameters, look for \foo, \bar, etc.
3133 if (Body[Pos] == '\\' && Pos + 1 != End)
3134 break;
3135
3136 // This macro should have parameters, but look for $0, $1, ..., $n too.
3137 if (Body[Pos] != '$' || Pos + 1 == End)
3138 continue;
3139 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00003140 if (Next == '$' || Next == 'n' ||
3141 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby221514e2013-01-22 21:44:53 +00003142 break;
3143 }
3144
3145 // Check if we reached the end.
3146 if (Pos == End)
3147 break;
3148
3149 if (Body[Pos] == '$') {
3150 switch (Body[Pos+1]) {
3151 // $$ => $
3152 case '$':
3153 break;
3154
3155 // $n => number of arguments
3156 case 'n':
3157 PositionalParametersFound = true;
3158 break;
3159
3160 // $[0-9] => argument
3161 default: {
3162 PositionalParametersFound = true;
3163 break;
3164 }
3165 }
3166 Pos += 2;
3167 } else {
3168 unsigned I = Pos + 1;
3169 while (isIdentifierChar(Body[I]) && I + 1 != End)
3170 ++I;
3171
3172 const char *Begin = Body.data() + Pos +1;
3173 StringRef Argument(Begin, I - (Pos +1));
3174 unsigned Index = 0;
3175 for (; Index < NParameters; ++Index)
3176 if (Parameters[Index].first == Argument)
3177 break;
3178
3179 if (Index == NParameters) {
3180 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
3181 Pos += 3;
3182 else {
3183 Pos = I;
3184 }
3185 } else {
3186 NamedParametersFound = true;
3187 Pos += 1 + Argument.size();
3188 }
3189 }
3190 // Update the scan point.
3191 Body = Body.substr(Pos);
3192 }
3193
3194 if (!NamedParametersFound && PositionalParametersFound)
3195 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3196 "used in macro body, possible positional parameter "
3197 "found in body which will have no effect");
3198}
3199
Eli Bendersky6ee13082013-01-15 22:59:42 +00003200/// ParseDirectiveEndMacro
3201/// ::= .endm
3202/// ::= .endmacro
3203bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
3204 if (getLexer().isNot(AsmToken::EndOfStatement))
3205 return TokError("unexpected token in '" + Directive + "' directive");
3206
3207 // If we are inside a macro instantiation, terminate the current
3208 // instantiation.
3209 if (InsideMacroInstantiation()) {
3210 HandleMacroExit();
3211 return false;
3212 }
3213
3214 // Otherwise, this .endmacro is a stray entry in the file; well formed
3215 // .endmacro directives are handled during the macro definition parsing.
3216 return TokError("unexpected '" + Directive + "' in file, "
3217 "no current macro definition");
3218}
3219
3220/// ParseDirectivePurgeMacro
3221/// ::= .purgem
3222bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3223 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003224 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003225 return TokError("expected identifier in '.purgem' directive");
3226
3227 if (getLexer().isNot(AsmToken::EndOfStatement))
3228 return TokError("unexpected token in '.purgem' directive");
3229
3230 if (!LookupMacro(Name))
3231 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3232
3233 UndefineMacro(Name);
3234 return false;
3235}
Eli Bendersky4766ef42012-12-20 19:05:53 +00003236
3237/// ParseDirectiveBundleAlignMode
3238/// ::= {.bundle_align_mode} expression
3239bool AsmParser::ParseDirectiveBundleAlignMode() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003240 checkForValidSection();
Eli Bendersky4766ef42012-12-20 19:05:53 +00003241
3242 // Expect a single argument: an expression that evaluates to a constant
3243 // in the inclusive range 0-30.
3244 SMLoc ExprLoc = getLexer().getLoc();
3245 int64_t AlignSizePow2;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003246 if (parseAbsoluteExpression(AlignSizePow2))
Eli Bendersky4766ef42012-12-20 19:05:53 +00003247 return true;
3248 else if (getLexer().isNot(AsmToken::EndOfStatement))
3249 return TokError("unexpected token after expression in"
3250 " '.bundle_align_mode' directive");
3251 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3252 return Error(ExprLoc,
3253 "invalid bundle alignment size (expected between 0 and 30)");
3254
3255 Lex();
3256
3257 // Because of AlignSizePow2's verified range we can safely truncate it to
3258 // unsigned.
3259 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3260 return false;
3261}
3262
3263/// ParseDirectiveBundleLock
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003264/// ::= {.bundle_lock} [align_to_end]
Eli Bendersky4766ef42012-12-20 19:05:53 +00003265bool AsmParser::ParseDirectiveBundleLock() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003266 checkForValidSection();
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003267 bool AlignToEnd = false;
Eli Bendersky4766ef42012-12-20 19:05:53 +00003268
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003269 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3270 StringRef Option;
3271 SMLoc Loc = getTok().getLoc();
3272 const char *kInvalidOptionError =
3273 "invalid option for '.bundle_lock' directive";
3274
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003275 if (parseIdentifier(Option))
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003276 return Error(Loc, kInvalidOptionError);
3277
3278 if (Option != "align_to_end")
3279 return Error(Loc, kInvalidOptionError);
3280 else if (getLexer().isNot(AsmToken::EndOfStatement))
3281 return Error(Loc,
3282 "unexpected token after '.bundle_lock' directive option");
3283 AlignToEnd = true;
3284 }
3285
Eli Bendersky4766ef42012-12-20 19:05:53 +00003286 Lex();
3287
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003288 getStreamer().EmitBundleLock(AlignToEnd);
Eli Bendersky4766ef42012-12-20 19:05:53 +00003289 return false;
3290}
3291
3292/// ParseDirectiveBundleLock
3293/// ::= {.bundle_lock}
3294bool AsmParser::ParseDirectiveBundleUnlock() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003295 checkForValidSection();
Eli Bendersky4766ef42012-12-20 19:05:53 +00003296
3297 if (getLexer().isNot(AsmToken::EndOfStatement))
3298 return TokError("unexpected token in '.bundle_unlock' directive");
3299 Lex();
3300
3301 getStreamer().EmitBundleUnlock();
3302 return false;
3303}
3304
Eli Bendersky6ee13082013-01-15 22:59:42 +00003305/// ParseDirectiveSpace
3306/// ::= (.skip | .space) expression [ , expression ]
3307bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003308 checkForValidSection();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003309
3310 int64_t NumBytes;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003311 if (parseAbsoluteExpression(NumBytes))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003312 return true;
3313
3314 int64_t FillExpr = 0;
3315 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3316 if (getLexer().isNot(AsmToken::Comma))
3317 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3318 Lex();
3319
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003320 if (parseAbsoluteExpression(FillExpr))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003321 return true;
3322
3323 if (getLexer().isNot(AsmToken::EndOfStatement))
3324 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3325 }
3326
3327 Lex();
3328
3329 if (NumBytes <= 0)
3330 return TokError("invalid number of bytes in '" +
3331 Twine(IDVal) + "' directive");
3332
3333 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3334 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
3335
3336 return false;
3337}
3338
3339/// ParseDirectiveLEB128
3340/// ::= (.sleb128 | .uleb128) expression
3341bool AsmParser::ParseDirectiveLEB128(bool Signed) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003342 checkForValidSection();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003343 const MCExpr *Value;
3344
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003345 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003346 return true;
3347
3348 if (getLexer().isNot(AsmToken::EndOfStatement))
3349 return TokError("unexpected token in directive");
3350
3351 if (Signed)
3352 getStreamer().EmitSLEB128Value(Value);
3353 else
3354 getStreamer().EmitULEB128Value(Value);
3355
3356 return false;
3357}
3358
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003359/// ParseDirectiveSymbolAttribute
3360/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00003361bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003362 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003363 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003364 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00003365 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003366
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003367 if (parseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00003368 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003369
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003370 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003371
Jim Grosbach10ec6502011-09-15 17:56:49 +00003372 // Assembler local symbols don't make any sense here. Complain loudly.
3373 if (Sym->isTemporary())
3374 return Error(Loc, "non-local symbol required in directive");
3375
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003376 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003377
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003378 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003379 break;
3380
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003381 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003382 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003383 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003384 }
3385 }
3386
Sean Callanan79ed1a82010-01-19 20:22:31 +00003387 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00003388 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003389}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003390
3391/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00003392/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3393bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003394 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00003395
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003396 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003397 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003398 if (parseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003399 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003400
Daniel Dunbar76c4d762009-07-31 21:55:09 +00003401 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003402 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003403
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003404 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003405 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003406 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003407
3408 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003409 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003410 if (parseAbsoluteExpression(Size))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003411 return true;
3412
3413 int64_t Pow2Alignment = 0;
3414 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003415 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00003416 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003417 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003418 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003419 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003420
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003421 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3422 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00003423 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3424
Chris Lattner258281d2010-01-19 06:22:22 +00003425 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003426 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3427 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00003428 if (!isPowerOf2_64(Pow2Alignment))
3429 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3430 Pow2Alignment = Log2_64(Pow2Alignment);
3431 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003432 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003433
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003434 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00003435 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003436
Sean Callanan79ed1a82010-01-19 20:22:31 +00003437 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003438
Chris Lattner1fc3d752009-07-09 17:25:12 +00003439 // NOTE: a size of zero for a .comm should create a undefined symbol
3440 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003441 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003442 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3443 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003444
Eric Christopherc260a3e2010-05-14 01:38:54 +00003445 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003446 // may internally end up wanting an alignment in bytes.
3447 // FIXME: Diagnose overflow.
3448 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003449 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3450 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003451
Daniel Dunbar8906ff12009-08-22 07:22:36 +00003452 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003453 return Error(IDLoc, "invalid symbol redefinition");
3454
Chris Lattner1fc3d752009-07-09 17:25:12 +00003455 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003456 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00003457 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003458 return false;
3459 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003460
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003461 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003462 return false;
3463}
Chris Lattner9be3fee2009-07-10 22:20:30 +00003464
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003465/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003466/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003467bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003468 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003469 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003470
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003471 StringRef Str = parseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003472 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003473 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003474
Sean Callanan79ed1a82010-01-19 20:22:31 +00003475 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003476
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003477 if (Str.empty())
3478 Error(Loc, ".abort detected. Assembly stopping.");
3479 else
3480 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003481 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003482
3483 return false;
3484}
Kevin Enderby71148242009-07-14 21:35:03 +00003485
Kevin Enderby1f049b22009-07-14 23:21:55 +00003486/// ParseDirectiveInclude
3487/// ::= .include "filename"
3488bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003489 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003490 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003491
Sean Callanan18b83232010-01-19 21:44:56 +00003492 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003493 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00003494 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00003495
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003496 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003497 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003498
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003499 // Strip the quotes.
3500 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003501
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003502 // Attempt to switch the lexer to the included file before consuming the end
3503 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00003504 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00003505 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003506 return true;
3507 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00003508
3509 return false;
3510}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00003511
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003512/// ParseDirectiveIncbin
3513/// ::= .incbin "filename"
3514bool AsmParser::ParseDirectiveIncbin() {
3515 if (getLexer().isNot(AsmToken::String))
3516 return TokError("expected string in '.incbin' directive");
3517
3518 std::string Filename = getTok().getString();
3519 SMLoc IncbinLoc = getLexer().getLoc();
3520 Lex();
3521
3522 if (getLexer().isNot(AsmToken::EndOfStatement))
3523 return TokError("unexpected token in '.incbin' directive");
3524
3525 // Strip the quotes.
3526 Filename = Filename.substr(1, Filename.size()-2);
3527
3528 // Attempt to process the included file.
3529 if (ProcessIncbinFile(Filename)) {
3530 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3531 return true;
3532 }
3533
3534 return false;
3535}
3536
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003537/// ParseDirectiveIf
3538/// ::= .if expression
3539bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003540 TheCondStack.push_back(TheCondState);
3541 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00003542 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003543 eatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00003544 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003545 int64_t ExprValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003546 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003547 return true;
3548
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003549 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003550 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003551
Sean Callanan79ed1a82010-01-19 20:22:31 +00003552 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003553
3554 TheCondState.CondMet = ExprValue;
3555 TheCondState.Ignore = !TheCondState.CondMet;
3556 }
3557
3558 return false;
3559}
3560
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003561/// ParseDirectiveIfb
3562/// ::= .ifb string
3563bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3564 TheCondStack.push_back(TheCondState);
3565 TheCondState.TheCond = AsmCond::IfCond;
3566
Benjamin Kramer29739e72012-05-12 16:52:21 +00003567 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003568 eatToEndOfStatement();
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003569 } else {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003570 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003571
3572 if (getLexer().isNot(AsmToken::EndOfStatement))
3573 return TokError("unexpected token in '.ifb' directive");
3574
3575 Lex();
3576
3577 TheCondState.CondMet = ExpectBlank == Str.empty();
3578 TheCondState.Ignore = !TheCondState.CondMet;
3579 }
3580
3581 return false;
3582}
3583
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003584/// ParseDirectiveIfc
3585/// ::= .ifc string1, string2
3586bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3587 TheCondStack.push_back(TheCondState);
3588 TheCondState.TheCond = AsmCond::IfCond;
3589
Benjamin Kramer29739e72012-05-12 16:52:21 +00003590 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003591 eatToEndOfStatement();
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003592 } else {
3593 StringRef Str1 = ParseStringToComma();
3594
3595 if (getLexer().isNot(AsmToken::Comma))
3596 return TokError("unexpected token in '.ifc' directive");
3597
3598 Lex();
3599
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003600 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003601
3602 if (getLexer().isNot(AsmToken::EndOfStatement))
3603 return TokError("unexpected token in '.ifc' directive");
3604
3605 Lex();
3606
3607 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3608 TheCondState.Ignore = !TheCondState.CondMet;
3609 }
3610
3611 return false;
3612}
3613
3614/// ParseDirectiveIfdef
3615/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003616bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3617 StringRef Name;
3618 TheCondStack.push_back(TheCondState);
3619 TheCondState.TheCond = AsmCond::IfCond;
3620
3621 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003622 eatToEndOfStatement();
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003623 } else {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003624 if (parseIdentifier(Name))
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003625 return TokError("expected identifier after '.ifdef'");
3626
3627 Lex();
3628
3629 MCSymbol *Sym = getContext().LookupSymbol(Name);
3630
3631 if (expect_defined)
3632 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3633 else
3634 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3635 TheCondState.Ignore = !TheCondState.CondMet;
3636 }
3637
3638 return false;
3639}
3640
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003641/// ParseDirectiveElseIf
3642/// ::= .elseif expression
3643bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
3644 if (TheCondState.TheCond != AsmCond::IfCond &&
3645 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper955d1e92013-04-22 04:24:02 +00003646 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3647 " an .elseif");
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003648 TheCondState.TheCond = AsmCond::ElseIfCond;
3649
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003650 bool LastIgnoreState = false;
3651 if (!TheCondStack.empty())
Craig Topper955d1e92013-04-22 04:24:02 +00003652 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003653 if (LastIgnoreState || TheCondState.CondMet) {
3654 TheCondState.Ignore = true;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003655 eatToEndOfStatement();
Craig Topperefa703d2013-04-22 04:22:40 +00003656 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003657 int64_t ExprValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003658 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003659 return true;
3660
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003661 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003662 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003663
Sean Callanan79ed1a82010-01-19 20:22:31 +00003664 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003665 TheCondState.CondMet = ExprValue;
3666 TheCondState.Ignore = !TheCondState.CondMet;
3667 }
3668
3669 return false;
3670}
3671
3672/// ParseDirectiveElse
3673/// ::= .else
3674bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003675 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003676 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003677
Sean Callanan79ed1a82010-01-19 20:22:31 +00003678 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003679
3680 if (TheCondState.TheCond != AsmCond::IfCond &&
3681 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper955d1e92013-04-22 04:24:02 +00003682 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3683 ".elseif");
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003684 TheCondState.TheCond = AsmCond::ElseCond;
3685 bool LastIgnoreState = false;
3686 if (!TheCondStack.empty())
3687 LastIgnoreState = TheCondStack.back().Ignore;
3688 if (LastIgnoreState || TheCondState.CondMet)
3689 TheCondState.Ignore = true;
3690 else
3691 TheCondState.Ignore = false;
3692
3693 return false;
3694}
3695
3696/// ParseDirectiveEndIf
3697/// ::= .endif
3698bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003699 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003700 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003701
Sean Callanan79ed1a82010-01-19 20:22:31 +00003702 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003703
3704 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3705 TheCondStack.empty())
3706 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3707 ".else");
3708 if (!TheCondStack.empty()) {
3709 TheCondState = TheCondStack.back();
3710 TheCondStack.pop_back();
3711 }
3712
3713 return false;
3714}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003715
Eli Bendersky6ee13082013-01-15 22:59:42 +00003716void AsmParser::initializeDirectiveKindMap() {
3717 DirectiveKindMap[".set"] = DK_SET;
3718 DirectiveKindMap[".equ"] = DK_EQU;
3719 DirectiveKindMap[".equiv"] = DK_EQUIV;
3720 DirectiveKindMap[".ascii"] = DK_ASCII;
3721 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3722 DirectiveKindMap[".string"] = DK_STRING;
3723 DirectiveKindMap[".byte"] = DK_BYTE;
3724 DirectiveKindMap[".short"] = DK_SHORT;
3725 DirectiveKindMap[".value"] = DK_VALUE;
3726 DirectiveKindMap[".2byte"] = DK_2BYTE;
3727 DirectiveKindMap[".long"] = DK_LONG;
3728 DirectiveKindMap[".int"] = DK_INT;
3729 DirectiveKindMap[".4byte"] = DK_4BYTE;
3730 DirectiveKindMap[".quad"] = DK_QUAD;
3731 DirectiveKindMap[".8byte"] = DK_8BYTE;
3732 DirectiveKindMap[".single"] = DK_SINGLE;
3733 DirectiveKindMap[".float"] = DK_FLOAT;
3734 DirectiveKindMap[".double"] = DK_DOUBLE;
3735 DirectiveKindMap[".align"] = DK_ALIGN;
3736 DirectiveKindMap[".align32"] = DK_ALIGN32;
3737 DirectiveKindMap[".balign"] = DK_BALIGN;
3738 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3739 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3740 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3741 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3742 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3743 DirectiveKindMap[".org"] = DK_ORG;
3744 DirectiveKindMap[".fill"] = DK_FILL;
3745 DirectiveKindMap[".zero"] = DK_ZERO;
3746 DirectiveKindMap[".extern"] = DK_EXTERN;
3747 DirectiveKindMap[".globl"] = DK_GLOBL;
3748 DirectiveKindMap[".global"] = DK_GLOBAL;
3749 DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
3750 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3751 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3752 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3753 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3754 DirectiveKindMap[".reference"] = DK_REFERENCE;
3755 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3756 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3757 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3758 DirectiveKindMap[".comm"] = DK_COMM;
3759 DirectiveKindMap[".common"] = DK_COMMON;
3760 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3761 DirectiveKindMap[".abort"] = DK_ABORT;
3762 DirectiveKindMap[".include"] = DK_INCLUDE;
3763 DirectiveKindMap[".incbin"] = DK_INCBIN;
3764 DirectiveKindMap[".code16"] = DK_CODE16;
3765 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3766 DirectiveKindMap[".rept"] = DK_REPT;
3767 DirectiveKindMap[".irp"] = DK_IRP;
3768 DirectiveKindMap[".irpc"] = DK_IRPC;
3769 DirectiveKindMap[".endr"] = DK_ENDR;
3770 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3771 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3772 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3773 DirectiveKindMap[".if"] = DK_IF;
3774 DirectiveKindMap[".ifb"] = DK_IFB;
3775 DirectiveKindMap[".ifnb"] = DK_IFNB;
3776 DirectiveKindMap[".ifc"] = DK_IFC;
3777 DirectiveKindMap[".ifnc"] = DK_IFNC;
3778 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3779 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3780 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3781 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3782 DirectiveKindMap[".else"] = DK_ELSE;
3783 DirectiveKindMap[".endif"] = DK_ENDIF;
3784 DirectiveKindMap[".skip"] = DK_SKIP;
3785 DirectiveKindMap[".space"] = DK_SPACE;
3786 DirectiveKindMap[".file"] = DK_FILE;
3787 DirectiveKindMap[".line"] = DK_LINE;
3788 DirectiveKindMap[".loc"] = DK_LOC;
3789 DirectiveKindMap[".stabs"] = DK_STABS;
3790 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3791 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3792 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3793 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3794 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3795 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3796 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3797 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3798 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3799 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3800 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3801 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3802 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3803 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3804 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3805 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3806 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3807 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3808 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3809 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3810 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3811 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3812 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3813 DirectiveKindMap[".macro"] = DK_MACRO;
3814 DirectiveKindMap[".endm"] = DK_ENDM;
3815 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3816 DirectiveKindMap[".purgem"] = DK_PURGEM;
Eli Bendersky5d0f0612013-01-10 22:44:57 +00003817}
3818
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003819
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003820MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003821 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003822
Rafael Espindola761cb062012-06-03 23:57:14 +00003823 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003824 for (;;) {
3825 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003826 if (getLexer().is(AsmToken::Eof)) {
3827 Error(DirectiveLoc, "no matching '.endr' in definition");
3828 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003829 }
3830
Rafael Espindola761cb062012-06-03 23:57:14 +00003831 if (Lexer.is(AsmToken::Identifier) &&
3832 (getTok().getIdentifier() == ".rept")) {
3833 ++NestLevel;
3834 }
3835
3836 // Otherwise, check whether we have reached the .endr.
3837 if (Lexer.is(AsmToken::Identifier) &&
3838 getTok().getIdentifier() == ".endr") {
3839 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003840 EndToken = getTok();
3841 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003842 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3843 TokError("unexpected token in '.endr' directive");
3844 return 0;
3845 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003846 break;
3847 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003848 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003849 }
3850
Rafael Espindola761cb062012-06-03 23:57:14 +00003851 // Otherwise, scan till the end of the statement.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003852 eatToEndOfStatement();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003853 }
3854
3855 const char *BodyStart = StartToken.getLoc().getPointer();
3856 const char *BodyEnd = EndToken.getLoc().getPointer();
3857 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3858
Rafael Espindola761cb062012-06-03 23:57:14 +00003859 // We Are Anonymous.
3860 StringRef Name;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003861 MCAsmMacroParameters Parameters;
3862 return new MCAsmMacro(Name, Body, Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +00003863}
3864
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003865void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +00003866 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003867 OS << ".endr\n";
3868
3869 MemoryBuffer *Instantiation =
3870 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3871
Rafael Espindola761cb062012-06-03 23:57:14 +00003872 // Create the macro instantiation object and add to the current macro
3873 // instantiation stack.
3874 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003875 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003876 getTok().getLoc(),
3877 Instantiation);
3878 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003879
Rafael Espindola761cb062012-06-03 23:57:14 +00003880 // Jump to the macro instantiation and prime the lexer.
3881 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3882 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3883 Lex();
3884}
3885
3886bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3887 int64_t Count;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003888 if (parseAbsoluteExpression(Count))
Rafael Espindola761cb062012-06-03 23:57:14 +00003889 return TokError("unexpected token in '.rept' directive");
3890
3891 if (Count < 0)
3892 return TokError("Count is negative");
3893
3894 if (Lexer.isNot(AsmToken::EndOfStatement))
3895 return TokError("unexpected token in '.rept' directive");
3896
3897 // Eat the end of statement.
3898 Lex();
3899
3900 // Lex the rept definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003901 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindola761cb062012-06-03 23:57:14 +00003902 if (!M)
3903 return true;
3904
3905 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3906 // to hold the macro body with substitutions.
3907 SmallString<256> Buf;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003908 MCAsmMacroParameters Parameters;
3909 MCAsmMacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003910 raw_svector_ostream OS(Buf);
3911 while (Count--) {
3912 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3913 return true;
3914 }
3915 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003916
3917 return false;
3918}
3919
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003920/// ParseDirectiveIrp
3921/// ::= .irp symbol,values
3922bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003923 MCAsmMacroParameters Parameters;
3924 MCAsmMacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003925
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003926 if (parseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003927 return TokError("expected identifier in '.irp' directive");
3928
3929 Parameters.push_back(Parameter);
3930
3931 if (Lexer.isNot(AsmToken::Comma))
3932 return TokError("expected comma in '.irp' directive");
3933
3934 Lex();
3935
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003936 MCAsmMacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003937 if (ParseMacroArguments(0, A))
3938 return true;
3939
3940 // Eat the end of statement.
3941 Lex();
3942
3943 // Lex the irp definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003944 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003945 if (!M)
3946 return true;
3947
3948 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3949 // to hold the macro body with substitutions.
3950 SmallString<256> Buf;
3951 raw_svector_ostream OS(Buf);
3952
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003953 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3954 MCAsmMacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003955 Args.push_back(*i);
3956
3957 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3958 return true;
3959 }
3960
3961 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3962
3963 return false;
3964}
3965
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003966/// ParseDirectiveIrpc
3967/// ::= .irpc symbol,values
3968bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003969 MCAsmMacroParameters Parameters;
3970 MCAsmMacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003971
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003972 if (parseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003973 return TokError("expected identifier in '.irpc' directive");
3974
3975 Parameters.push_back(Parameter);
3976
3977 if (Lexer.isNot(AsmToken::Comma))
3978 return TokError("expected comma in '.irpc' directive");
3979
3980 Lex();
3981
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003982 MCAsmMacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003983 if (ParseMacroArguments(0, A))
3984 return true;
3985
3986 if (A.size() != 1 || A.front().size() != 1)
3987 return TokError("unexpected token in '.irpc' directive");
3988
3989 // Eat the end of statement.
3990 Lex();
3991
3992 // Lex the irpc definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003993 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003994 if (!M)
3995 return true;
3996
3997 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3998 // to hold the macro body with substitutions.
3999 SmallString<256> Buf;
4000 raw_svector_ostream OS(Buf);
4001
4002 StringRef Values = A.front().front().getString();
4003 std::size_t I, End = Values.size();
4004 for (I = 0; I < End; ++I) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00004005 MCAsmMacroArgument Arg;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00004006 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
4007
Eli Benderskyc0c67b02013-01-14 23:22:36 +00004008 MCAsmMacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00004009 Args.push_back(Arg);
4010
4011 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
4012 return true;
4013 }
4014
4015 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
4016
4017 return false;
4018}
4019
Rafael Espindola761cb062012-06-03 23:57:14 +00004020bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
4021 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00004022 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004023
4024 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00004025 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004026 assert(getLexer().is(AsmToken::EndOfStatement));
4027
Rafael Espindola761cb062012-06-03 23:57:14 +00004028 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004029 return false;
4030}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00004031
Benjamin Kramer75234372013-02-15 20:37:21 +00004032bool AsmParser::ParseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4033 size_t Len) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004034 const MCExpr *Value;
4035 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004036 if (parseExpression(Value))
Eli Friedman2128aae2012-10-22 23:58:19 +00004037 return true;
4038 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4039 if (!MCE)
4040 return Error(ExprLoc, "unexpected expression in _emit");
4041 uint64_t IntValue = MCE->getValue();
4042 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4043 return Error(ExprLoc, "literal value out of range for directive");
4044
Chad Rosier469b1442013-02-12 21:33:51 +00004045 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4046 return false;
4047}
4048
4049bool AsmParser::ParseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4050 const MCExpr *Value;
4051 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004052 if (parseExpression(Value))
Chad Rosier469b1442013-02-12 21:33:51 +00004053 return true;
4054 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4055 if (!MCE)
4056 return Error(ExprLoc, "unexpected expression in align");
4057 uint64_t IntValue = MCE->getValue();
4058 if (!isPowerOf2_64(IntValue))
4059 return Error(ExprLoc, "literal value not a power of two greater then zero");
4060
Benjamin Kramer75234372013-02-15 20:37:21 +00004061 Info.AsmRewrites->push_back(AsmRewrite(AOK_Align, IDLoc, 5,
4062 Log2_64(IntValue)));
Eli Friedman2128aae2012-10-22 23:58:19 +00004063 return false;
4064}
4065
Chad Rosier19aa3e32013-02-13 21:27:17 +00004066// We are comparing pointers, but the pointers are relative to a single string.
4067// Thus, this should always be deterministic.
Benjamin Kramer75234372013-02-15 20:37:21 +00004068static int RewritesSort(const void *A, const void *B) {
4069 const AsmRewrite *AsmRewriteA = static_cast<const AsmRewrite *>(A);
4070 const AsmRewrite *AsmRewriteB = static_cast<const AsmRewrite *>(B);
Chad Rosierabde6752013-02-13 18:38:58 +00004071 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4072 return -1;
4073 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4074 return 1;
Chad Rosierb54562b2013-02-15 22:54:16 +00004075
Chad Rosier6b369ce2013-04-08 17:43:47 +00004076 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4077 // rewrite to the same location. Make sure the SizeDirective rewrite is
4078 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4079 // ensures the sort algorithm is stable.
4080 if (AsmRewritePrecedence [AsmRewriteA->Kind] >
4081 AsmRewritePrecedence [AsmRewriteB->Kind])
Chad Rosierb54562b2013-02-15 22:54:16 +00004082 return -1;
Chad Rosier6b369ce2013-04-08 17:43:47 +00004083
4084 if (AsmRewritePrecedence [AsmRewriteA->Kind] <
4085 AsmRewritePrecedence [AsmRewriteB->Kind])
Chad Rosierb54562b2013-02-15 22:54:16 +00004086 return 1;
Chad Rosierb54562b2013-02-15 22:54:16 +00004087 llvm_unreachable ("Unstable rewrite sort.");
Chad Rosierb1953982013-02-13 01:03:13 +00004088}
4089
Benjamin Kramer75234372013-02-15 20:37:21 +00004090bool
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004091AsmParser::parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Benjamin Kramer75234372013-02-15 20:37:21 +00004092 unsigned &NumOutputs, unsigned &NumInputs,
4093 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4094 SmallVectorImpl<std::string> &Constraints,
4095 SmallVectorImpl<std::string> &Clobbers,
4096 const MCInstrInfo *MII,
4097 const MCInstPrinter *IP,
4098 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004099 SmallVector<void *, 4> InputDecls;
4100 SmallVector<void *, 4> OutputDecls;
Chad Rosierc1ec2072013-01-10 22:10:27 +00004101 SmallVector<bool, 4> InputDeclsAddressOf;
4102 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004103 SmallVector<std::string, 4> InputConstraints;
4104 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer75234372013-02-15 20:37:21 +00004105 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004106
Benjamin Kramer75234372013-02-15 20:37:21 +00004107 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004108
4109 // Prime the lexer.
4110 Lex();
4111
4112 // While we have input, parse each statement.
4113 unsigned InputIdx = 0;
4114 unsigned OutputIdx = 0;
4115 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004116 ParseStatementInfo Info(&AsmStrRewrites);
4117 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00004118 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004119
Chad Rosier57498012012-12-12 22:45:52 +00004120 if (Info.ParseError)
4121 return true;
4122
Benjamin Kramer75234372013-02-15 20:37:21 +00004123 if (Info.Opcode == ~0U)
4124 continue;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004125
Benjamin Kramer75234372013-02-15 20:37:21 +00004126 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004127
Benjamin Kramer75234372013-02-15 20:37:21 +00004128 // Build the list of clobbers, outputs and inputs.
4129 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4130 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004131
Benjamin Kramer75234372013-02-15 20:37:21 +00004132 // Immediate.
Chad Rosier811ddf62013-03-19 21:58:18 +00004133 if (Operand->isImm())
Benjamin Kramer75234372013-02-15 20:37:21 +00004134 continue;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004135
Benjamin Kramer75234372013-02-15 20:37:21 +00004136 // Register operand.
4137 if (Operand->isReg() && !Operand->needAddressOf()) {
4138 unsigned NumDefs = Desc.getNumDefs();
4139 // Clobber.
4140 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4141 ClobberRegs.push_back(Operand->getReg());
4142 continue;
4143 }
4144
4145 // Expr/Input or Output.
Chad Rosierb976e402013-04-09 17:53:49 +00004146 StringRef SymName = Operand->getSymName();
4147 if (SymName.empty())
4148 continue;
4149
Chad Rosier087c3092013-04-22 22:12:12 +00004150 void *OpDecl = Operand->getOpDecl();
Benjamin Kramer75234372013-02-15 20:37:21 +00004151 if (!OpDecl)
4152 continue;
4153
4154 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierb976e402013-04-09 17:53:49 +00004155 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer75234372013-02-15 20:37:21 +00004156 if (isOutput) {
4157 ++InputIdx;
4158 OutputDecls.push_back(OpDecl);
4159 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4160 OutputConstraints.push_back('=' + Operand->getConstraint().str());
Chad Rosierb976e402013-04-09 17:53:49 +00004161 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
Benjamin Kramer75234372013-02-15 20:37:21 +00004162 } else {
4163 InputDecls.push_back(OpDecl);
4164 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4165 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosierb976e402013-04-09 17:53:49 +00004166 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00004167 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004168 }
4169 }
4170
4171 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004172 NumOutputs = OutputDecls.size();
4173 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00004174
4175 // Set the unique clobbers.
Benjamin Kramer75234372013-02-15 20:37:21 +00004176 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4177 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4178 ClobberRegs.end());
4179 Clobbers.assign(ClobberRegs.size(), std::string());
4180 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4181 raw_string_ostream OS(Clobbers[I]);
4182 IP->printRegName(OS, ClobberRegs[I]);
4183 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004184
4185 // Merge the various outputs and inputs. Output are expected first.
4186 if (NumOutputs || NumInputs) {
4187 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004188 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004189 Constraints.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004190 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004191 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004192 Constraints[i] = OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004193 }
4194 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004195 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004196 Constraints[j] = InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004197 }
4198 }
4199
4200 // Build the IR assembly string.
4201 std::string AsmStringIR;
4202 raw_string_ostream OS(AsmStringIR);
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004203 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4204 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
Benjamin Kramer75234372013-02-15 20:37:21 +00004205 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), RewritesSort);
4206 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4207 E = AsmStrRewrites.end();
4208 I != E; ++I) {
Chad Rosierdda4b6b2013-04-12 16:26:42 +00004209 AsmRewriteKind Kind = (*I).Kind;
4210 if (Kind == AOK_Delete)
4211 continue;
4212
Chad Rosierb1f8c132012-10-18 15:49:34 +00004213 const char *Loc = (*I).Loc.getPointer();
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004214 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier96d58e62012-10-19 20:57:14 +00004215
Chad Rosier023c8802013-03-19 17:32:17 +00004216 // Emit everything up to the immediate/expression.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004217 unsigned Len = Loc - AsmStart;
Chad Rosierf06cc982013-04-11 21:49:30 +00004218 if (Len)
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004219 OS << StringRef(AsmStart, Len);
Chad Rosier96d58e62012-10-19 20:57:14 +00004220
Chad Rosier5a719fc2012-10-23 17:43:43 +00004221 // Skip the original expression.
4222 if (Kind == AOK_Skip) {
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004223 AsmStart = Loc + (*I).Len;
Chad Rosier5a719fc2012-10-23 17:43:43 +00004224 continue;
4225 }
4226
Chad Rosierdda4b6b2013-04-12 16:26:42 +00004227 unsigned AdditionalSkip = 0;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004228 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00004229 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004230 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004231 case AOK_Imm:
Benjamin Kramer75234372013-02-15 20:37:21 +00004232 OS << "$$" << (*I).Val;
Chad Rosierefcb3d92012-10-26 18:04:20 +00004233 break;
4234 case AOK_ImmPrefix:
Benjamin Kramer75234372013-02-15 20:37:21 +00004235 OS << "$$";
Chad Rosierb1f8c132012-10-18 15:49:34 +00004236 break;
4237 case AOK_Input:
Benjamin Kramer75234372013-02-15 20:37:21 +00004238 OS << '$' << InputIdx++;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004239 break;
4240 case AOK_Output:
Benjamin Kramer75234372013-02-15 20:37:21 +00004241 OS << '$' << OutputIdx++;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004242 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00004243 case AOK_SizeDirective:
Benjamin Kramer75234372013-02-15 20:37:21 +00004244 switch ((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00004245 default: break;
4246 case 8: OS << "byte ptr "; break;
4247 case 16: OS << "word ptr "; break;
4248 case 32: OS << "dword ptr "; break;
4249 case 64: OS << "qword ptr "; break;
4250 case 80: OS << "xword ptr "; break;
4251 case 128: OS << "xmmword ptr "; break;
4252 case 256: OS << "ymmword ptr "; break;
4253 }
Eli Friedman2128aae2012-10-22 23:58:19 +00004254 break;
4255 case AOK_Emit:
4256 OS << ".byte";
4257 break;
Chad Rosier469b1442013-02-12 21:33:51 +00004258 case AOK_Align: {
4259 unsigned Val = (*I).Val;
4260 OS << ".align " << Val;
4261
4262 // Skip the original immediate.
Benjamin Kramer75234372013-02-15 20:37:21 +00004263 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosier469b1442013-02-12 21:33:51 +00004264 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4265 break;
4266 }
Chad Rosier6a020a72012-10-25 20:41:34 +00004267 case AOK_DotOperator:
4268 OS << (*I).Val;
4269 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004270 }
Chad Rosier96d58e62012-10-19 20:57:14 +00004271
Chad Rosierb1f8c132012-10-18 15:49:34 +00004272 // Skip the original expression.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004273 AsmStart = Loc + (*I).Len + AdditionalSkip;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004274 }
4275
4276 // Emit the remainder of the asm string.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004277 if (AsmStart != AsmEnd)
4278 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004279
4280 AsmString = OS.str();
4281 return false;
4282}
4283
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004284/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004285MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004286 MCContext &C, MCStreamer &Out,
4287 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004288 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004289}