blob: 167e64174fbe885f0ec25007c6b8aa863f076b99 [file] [log] [blame]
Chris Lattner27aa7d22009-06-21 20:16:42 +00001//===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This class implements the parser for assembly files.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbarb95a0792010-09-24 01:59:56 +000014#include "llvm/ADT/APFloat.h"
Daniel Dunbar7c0a3342009-08-26 22:49:51 +000015#include "llvm/ADT/SmallString.h"
Chad Rosierabde6752013-02-13 18:38:58 +000016#include "llvm/ADT/STLExtras.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000017#include "llvm/ADT/StringMap.h"
Daniel Dunbarf9507ff2009-07-27 23:20:52 +000018#include "llvm/ADT/Twine.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000019#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000020#include "llvm/MC/MCContext.h"
Evan Cheng94b95502011-07-26 00:24:13 +000021#include "llvm/MC/MCDwarf.h"
Daniel Dunbar28c251b2009-08-31 08:06:59 +000022#include "llvm/MC/MCExpr.h"
Chad Rosierb1f8c132012-10-18 15:49:34 +000023#include "llvm/MC/MCInstPrinter.h"
24#include "llvm/MC/MCInstrInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000025#include "llvm/MC/MCParser/AsmCond.h"
26#include "llvm/MC/MCParser/AsmLexer.h"
27#include "llvm/MC/MCParser/MCAsmParser.h"
28#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Evan Chenge76a33b2011-07-20 05:58:47 +000029#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000030#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000031#include "llvm/MC/MCStreamer.h"
Daniel Dunbardce0f3c2009-06-29 23:43:14 +000032#include "llvm/MC/MCSymbol.h"
Evan Cheng94b95502011-07-26 00:24:13 +000033#include "llvm/MC/MCTargetAsmParser.h"
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000034#include "llvm/Support/CommandLine.h"
Benjamin Kramer518ff562012-01-28 15:28:41 +000035#include "llvm/Support/ErrorHandling.h"
Jim Grosbach254cf032011-06-29 16:05:14 +000036#include "llvm/Support/MathExtras.h"
Kevin Enderbyf187ac52010-06-28 21:45:58 +000037#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000038#include "llvm/Support/SourceMgr.h"
Chris Lattnerb0789ed2009-06-21 20:54:55 +000039#include "llvm/Support/raw_ostream.h"
Nick Lewycky476b2422010-12-19 20:43:38 +000040#include <cctype>
Chad Rosierb1f8c132012-10-18 15:49:34 +000041#include <set>
42#include <string>
Daniel Dunbaraef87e32010-07-18 18:31:38 +000043#include <vector>
Chris Lattner27aa7d22009-06-21 20:16:42 +000044using namespace llvm;
45
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000046static cl::opt<bool>
47FatalAssemblerWarnings("fatal-assembler-warnings",
48 cl::desc("Consider warnings as error"));
49
Eric Christopher2318ba12012-12-18 00:30:54 +000050MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
Nick Lewycky0d7d11d2012-10-19 07:00:09 +000051
Daniel Dunbar81ea00f2010-07-12 17:54:38 +000052namespace {
53
Eli Benderskyf9f40bd2013-01-16 18:56:50 +000054/// \brief Helper types for tracking macro definitions.
55typedef std::vector<AsmToken> MCAsmMacroArgument;
56typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
57typedef std::pair<StringRef, MCAsmMacroArgument> MCAsmMacroParameter;
58typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
59
60struct MCAsmMacro {
61 StringRef Name;
62 StringRef Body;
63 MCAsmMacroParameters Parameters;
64
65public:
66 MCAsmMacro(StringRef N, StringRef B, const MCAsmMacroParameters &P) :
67 Name(N), Body(B), Parameters(P) {}
68
69 MCAsmMacro(const MCAsmMacro& Other)
70 : Name(Other.Name), Body(Other.Body), Parameters(Other.Parameters) {}
71};
72
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000073/// \brief Helper class for storing information about an active macro
74/// instantiation.
75struct MacroInstantiation {
76 /// The macro being instantiated.
Eli Benderskyc0c67b02013-01-14 23:22:36 +000077 const MCAsmMacro *TheMacro;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000078
79 /// The macro instantiation with substitutions.
80 MemoryBuffer *Instantiation;
81
82 /// The location of the instantiation.
83 SMLoc InstantiationLoc;
84
Daniel Dunbar4259a1a2012-12-01 01:38:48 +000085 /// The buffer where parsing should resume upon instantiation completion.
86 int ExitBuffer;
87
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000088 /// The location where parsing should resume upon instantiation completion.
89 SMLoc ExitLoc;
90
91public:
Eli Benderskyc0c67b02013-01-14 23:22:36 +000092 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000093 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000094};
95
Eli Friedman2128aae2012-10-22 23:58:19 +000096struct ParseStatementInfo {
97 /// ParsedOperands - The parsed operands from the last parsed statement.
98 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
99
100 /// Opcode - The opcode from the last parsed instruction.
101 unsigned Opcode;
102
Chad Rosier57498012012-12-12 22:45:52 +0000103 /// Error - Was there an error parsing the inline assembly?
104 bool ParseError;
105
Eli Friedman2128aae2012-10-22 23:58:19 +0000106 SmallVectorImpl<AsmRewrite> *AsmRewrites;
107
Chad Rosier57498012012-12-12 22:45:52 +0000108 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
Eli Friedman2128aae2012-10-22 23:58:19 +0000109 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier57498012012-12-12 22:45:52 +0000110 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman2128aae2012-10-22 23:58:19 +0000111
112 ~ParseStatementInfo() {
113 // Free any parsed operands.
114 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
115 delete ParsedOperands[i];
116 ParsedOperands.clear();
117 }
118};
119
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000120/// \brief The concrete assembly parser instance.
121class AsmParser : public MCAsmParser {
Craig Topper85aadc02012-09-15 16:23:52 +0000122 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
123 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000124private:
125 AsmLexer Lexer;
126 MCContext &Ctx;
127 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000128 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000129 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +0000130 SourceMgr::DiagHandlerTy SavedDiagHandler;
131 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000132 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000133
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000134 /// This is the current buffer index we're lexing from as managed by the
135 /// SourceMgr object.
136 int CurBuffer;
137
138 AsmCond TheCondState;
139 std::vector<AsmCond> TheCondStack;
140
Eli Bendersky6ee13082013-01-15 22:59:42 +0000141 /// ExtensionDirectiveMap - maps directive names to handler methods in parser
142 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000143 /// addDirectiveHandler.
Eli Bendersky6ee13082013-01-15 22:59:42 +0000144 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000145
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000146 /// MacroMap - Map of currently defined macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000147 StringMap<MCAsmMacro*> MacroMap;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000148
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000149 /// ActiveMacros - Stack of active macro instantiations.
150 std::vector<MacroInstantiation*> ActiveMacros;
151
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000152 /// Boolean tracking whether macro substitution is enabled.
Eli Bendersky733c3362013-01-14 18:08:41 +0000153 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000154
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000155 /// Flag tracking whether any errors have been encountered.
156 unsigned HadError : 1;
157
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000158 /// The values from the last parsed cpp hash file line comment if any.
159 StringRef CppHashFilename;
160 int64_t CppHashLineNumber;
161 SMLoc CppHashLoc;
Kevin Enderby32c1a822012-11-05 21:55:41 +0000162 int CppHashBuf;
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000163
Devang Patel0db58bf2012-01-31 18:14:05 +0000164 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
165 unsigned AssemblerDialect;
166
Preston Gurd7b6f2032012-09-19 20:36:12 +0000167 /// IsDarwin - is Darwin compatibility enabled?
168 bool IsDarwin;
169
Chad Rosier8f138d12012-10-15 17:19:13 +0000170 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000171 bool ParsingInlineAsm;
172
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000173public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000174 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000175 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000176 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000177
178 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
179
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000180 virtual void addDirectiveHandler(StringRef Directive,
Eli Bendersky171192f2013-01-16 00:50:52 +0000181 ExtensionDirectiveHandler Handler) {
182 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000183 }
184
185public:
186 /// @name MCAsmParser Interface
187 /// {
188
189 virtual SourceMgr &getSourceManager() { return SrcMgr; }
190 virtual MCAsmLexer &getLexer() { return Lexer; }
191 virtual MCContext &getContext() { return Ctx; }
192 virtual MCStreamer &getStreamer() { return Out; }
Eric Christopher2318ba12012-12-18 00:30:54 +0000193 virtual unsigned getAssemblerDialect() {
Devang Patel0db58bf2012-01-31 18:14:05 +0000194 if (AssemblerDialect == ~0U)
Eric Christopher2318ba12012-12-18 00:30:54 +0000195 return MAI.getAssemblerDialect();
Devang Patel0db58bf2012-01-31 18:14:05 +0000196 else
197 return AssemblerDialect;
198 }
199 virtual void setAssemblerDialect(unsigned i) {
200 AssemblerDialect = i;
201 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000202
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000203 virtual bool Warning(SMLoc L, const Twine &Msg,
Dmitri Gribenko5c332db2013-05-05 00:40:33 +0000204 ArrayRef<SMRange> Ranges = None);
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000205 virtual bool Error(SMLoc L, const Twine &Msg,
Dmitri Gribenko5c332db2013-05-05 00:40:33 +0000206 ArrayRef<SMRange> Ranges = None);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000207
Craig Topper345d16d2012-08-29 05:48:09 +0000208 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000209
Chad Rosier84125ca2012-10-13 00:26:04 +0000210 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosierc5ac87d2012-10-16 20:16:20 +0000211 bool isParsingInlineAsm() { return ParsingInlineAsm; }
Chad Rosierb1f8c132012-10-18 15:49:34 +0000212
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000213 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000214 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +0000215 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000216 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000217 SmallVectorImpl<std::string> &Clobbers,
218 const MCInstrInfo *MII,
219 const MCInstPrinter *IP,
220 MCAsmParserSemaCallback &SI);
Chad Rosier84125ca2012-10-13 00:26:04 +0000221
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000222 bool parseExpression(const MCExpr *&Res);
223 virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc);
Chad Rosierba69b362013-04-10 17:35:30 +0000224 virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000225 virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
226 virtual bool parseAbsoluteExpression(int64_t &Res);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000227
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000228 /// parseIdentifier - Parse an identifier or string (as a quoted identifier)
Eli Benderskybf706b32013-01-12 00:05:00 +0000229 /// and set \p Res to the identifier contents.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000230 virtual bool parseIdentifier(StringRef &Res);
231 virtual void eatToEndOfStatement();
Eli Benderskybf706b32013-01-12 00:05:00 +0000232
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000233 virtual void checkForValidSection();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000234 /// }
235
236private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000237
Eli Friedman2128aae2012-10-22 23:58:19 +0000238 bool ParseStatement(ParseStatementInfo &Info);
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000239 void EatToEndOfLine();
240 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000241
Kevin Enderby221514e2013-01-22 21:44:53 +0000242 void CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
243 MCAsmMacroParameters Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +0000244 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000245 const MCAsmMacroParameters &Parameters,
246 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000247 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000248
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000249 /// \brief Are macros enabled in the parser?
250 bool MacrosEnabled() {return MacrosEnabledFlag;}
251
252 /// \brief Control a flag in the parser that enables or disables macros.
253 void SetMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
254
255 /// \brief Lookup a previously defined macro.
256 /// \param Name Macro name.
257 /// \returns Pointer to macro. NULL if no such macro was defined.
258 const MCAsmMacro* LookupMacro(StringRef Name);
259
260 /// \brief Define a new macro with the given name and information.
261 void DefineMacro(StringRef Name, const MCAsmMacro& Macro);
262
263 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
264 void UndefineMacro(StringRef Name);
265
266 /// \brief Are we inside a macro instantiation?
267 bool InsideMacroInstantiation() {return !ActiveMacros.empty();}
268
269 /// \brief Handle entry to macro instantiation.
270 ///
271 /// \param M The macro.
272 /// \param NameLoc Instantiation location.
273 bool HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
274
275 /// \brief Handle exit from macro instantiation.
276 void HandleMacroExit();
277
278 /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
279 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
280 /// correct delimiter by the method.
281 bool ParseMacroArgument(MCAsmMacroArgument &MA,
282 AsmToken::TokenKind &ArgumentDelimiter);
283
284 /// \brief Parse all macro arguments for a given macro.
285 bool ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
286
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000287 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000288 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Dmitri Gribenko5c332db2013-05-05 00:40:33 +0000289 ArrayRef<SMRange> Ranges = None) const {
Chris Lattner462b43c2011-10-16 05:47:55 +0000290 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000291 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000292 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000293
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000294 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
295 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000296 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
297 /// This returns true on failure.
298 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000299
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000300 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000301 /// current token is not set; clients should ensure Lex() is called
302 /// subsequently.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000303 ///
304 /// \param InBuffer If not -1, should be the known buffer id that contains the
305 /// location.
306 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000307
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000308 /// \brief Parse up to the end of statement and a return the contents from the
309 /// current token until the end of the statement; the current token on exit
310 /// will be either the EndOfStatement or EOF.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000311 virtual StringRef parseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000312
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000313 /// \brief Parse until the end of a statement or a comma is encountered,
314 /// return the contents from the current token up to the end or comma.
315 StringRef ParseStringToComma();
316
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000317 bool ParseAssignment(StringRef Name, bool allow_redef,
318 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000319
320 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
321 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
322 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000323 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000324
Eli Bendersky6ee13082013-01-15 22:59:42 +0000325 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola787c3372010-10-28 20:02:27 +0000326
Eli Bendersky6ee13082013-01-15 22:59:42 +0000327 // Generic (target and platform independent) directive parsing.
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000328 enum DirectiveKind {
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000329 DK_NO_DIRECTIVE, // Placeholder
330 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
331 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
332 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky9b1bb052013-01-11 22:55:28 +0000333 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000334 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
335 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
336 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
337 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
338 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
339 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
340 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
Eli Bendersky6ee13082013-01-15 22:59:42 +0000341 DK_ELSEIF, DK_ELSE, DK_ENDIF,
342 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
343 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
344 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
345 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
346 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
347 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
348 DK_CFI_REGISTER,
349 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
350 DK_SLEB128, DK_ULEB128
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000351 };
352
Eli Bendersky6ee13082013-01-15 22:59:42 +0000353 /// DirectiveKindMap - Maps directive name --> DirectiveKind enum, for
354 /// directives parsed by this class.
355 StringMap<DirectiveKind> DirectiveKindMap;
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000356
357 // ".ascii", ".asciz", ".string"
Rafael Espindola787c3372010-10-28 20:02:27 +0000358 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000359 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000360 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000361 bool ParseDirectiveFill(); // ".fill"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000362 bool ParseDirectiveZero(); // ".zero"
Eric Christopher2318ba12012-12-18 00:30:54 +0000363 // ".set", ".equ", ".equiv"
364 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000365 bool ParseDirectiveOrg(); // ".org"
366 // ".align{,32}", ".p2align{,w,l}"
367 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
368
Eli Bendersky6ee13082013-01-15 22:59:42 +0000369 // ".file", ".line", ".loc", ".stabs"
370 bool ParseDirectiveFile(SMLoc DirectiveLoc);
371 bool ParseDirectiveLine();
372 bool ParseDirectiveLoc();
373 bool ParseDirectiveStabs();
374
375 // .cfi directives
376 bool ParseDirectiveCFIRegister(SMLoc DirectiveLoc);
377 bool ParseDirectiveCFISections();
378 bool ParseDirectiveCFIStartProc();
379 bool ParseDirectiveCFIEndProc();
380 bool ParseDirectiveCFIDefCfaOffset();
381 bool ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
382 bool ParseDirectiveCFIAdjustCfaOffset();
383 bool ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
384 bool ParseDirectiveCFIOffset(SMLoc DirectiveLoc);
385 bool ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
386 bool ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
387 bool ParseDirectiveCFIRememberState();
388 bool ParseDirectiveCFIRestoreState();
389 bool ParseDirectiveCFISameValue(SMLoc DirectiveLoc);
390 bool ParseDirectiveCFIRestore(SMLoc DirectiveLoc);
391 bool ParseDirectiveCFIEscape();
392 bool ParseDirectiveCFISignalFrame();
393 bool ParseDirectiveCFIUndefined(SMLoc DirectiveLoc);
394
395 // macro directives
396 bool ParseDirectivePurgeMacro(SMLoc DirectiveLoc);
397 bool ParseDirectiveEndMacro(StringRef Directive);
398 bool ParseDirectiveMacro(SMLoc DirectiveLoc);
399 bool ParseDirectiveMacrosOnOff(StringRef Directive);
400
Eli Bendersky4766ef42012-12-20 19:05:53 +0000401 // ".bundle_align_mode"
402 bool ParseDirectiveBundleAlignMode();
403 // ".bundle_lock"
404 bool ParseDirectiveBundleLock();
405 // ".bundle_unlock"
406 bool ParseDirectiveBundleUnlock();
407
Eli Bendersky6ee13082013-01-15 22:59:42 +0000408 // ".space", ".skip"
409 bool ParseDirectiveSpace(StringRef IDVal);
410
411 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
412 bool ParseDirectiveLEB128(bool Signed);
413
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000414 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
415 /// accepts a single symbol (which should be a label or an external).
416 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000417
418 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
419
420 bool ParseDirectiveAbort(); // ".abort"
421 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000422 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000423
424 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000425 // ".ifb" or ".ifnb", depending on ExpectBlank.
426 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000427 // ".ifc" or ".ifnc", depending on ExpectEqual.
428 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000429 // ".ifdef" or ".ifndef", depending on expect_defined
430 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000431 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
432 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
433 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000434 virtual bool parseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000435
436 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
437 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000438
Rafael Espindola761cb062012-06-03 23:57:14 +0000439 // Macro-like directives
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000440 MCAsmMacro *ParseMacroLikeBody(SMLoc DirectiveLoc);
441 void InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +0000442 raw_svector_ostream &OS);
443 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000444 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000445 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000446 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000447
Chad Rosier469b1442013-02-12 21:33:51 +0000448 // "_emit" or "__emit"
449 bool ParseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
450 size_t Len);
451
452 // "align"
453 bool ParseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000454
Eli Bendersky6ee13082013-01-15 22:59:42 +0000455 void initializeDirectiveKindMap();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000456};
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000457}
458
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000459namespace llvm {
460
461extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000462extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000463extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000464
465}
466
Chris Lattneraaec2052010-01-19 19:46:13 +0000467enum { DEFAULT_ADDRSPACE = 0 };
468
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000469AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000470 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000471 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Eli Bendersky6ee13082013-01-15 22:59:42 +0000472 PlatformParser(0),
Eli Bendersky733c3362013-01-14 18:08:41 +0000473 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000474 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000475 // Save the old handler.
476 SavedDiagHandler = SrcMgr.getDiagHandler();
477 SavedDiagContext = SrcMgr.getDiagContext();
478 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000479 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000480 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000481
Daniel Dunbare4749702010-07-12 18:12:02 +0000482 // Initialize the platform / file format parser.
483 //
484 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
485 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000486 if (_MAI.hasMicrosoftFastStdCallMangling()) {
487 PlatformParser = createCOFFAsmParser();
488 PlatformParser->Initialize(*this);
489 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000490 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000491 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000492 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000493 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000494 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000495 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000496 }
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000497
Eli Bendersky6ee13082013-01-15 22:59:42 +0000498 initializeDirectiveKindMap();
Chris Lattnerebb89b42009-09-27 21:16:52 +0000499}
500
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000501AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000502 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
503
504 // Destroy any macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000505 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
Daniel Dunbar56491302010-07-29 01:51:55 +0000506 ie = MacroMap.end(); it != ie; ++it)
507 delete it->getValue();
508
Daniel Dunbare4749702010-07-12 18:12:02 +0000509 delete PlatformParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000510}
511
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000512void AsmParser::PrintMacroInstantiations() {
513 // Print the active macro instantiation stack.
514 for (std::vector<MacroInstantiation*>::const_reverse_iterator
515 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000516 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
517 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000518}
519
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000520bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000521 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000522 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000523 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000524 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000525 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000526}
527
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000528bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000529 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000530 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000531 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000532 return true;
533}
534
Sean Callananfd0b0282010-01-21 00:19:58 +0000535bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000536 std::string IncludedFile;
537 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000538 if (NewBuf == -1)
539 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000540
Sean Callananfd0b0282010-01-21 00:19:58 +0000541 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000542
Sean Callananfd0b0282010-01-21 00:19:58 +0000543 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000544
Sean Callananfd0b0282010-01-21 00:19:58 +0000545 return false;
546}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000547
Sylvestre Ledruda2ed452013-05-14 23:36:24 +0000548/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000549/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000550/// returns true on failure.
551bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
552 std::string IncludedFile;
553 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
554 if (NewBuf == -1)
555 return true;
556
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000557 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000558 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
559 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000560 return false;
561}
562
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000563void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
564 if (InBuffer != -1) {
565 CurBuffer = InBuffer;
566 } else {
567 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
568 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000569 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
570}
571
Sean Callananfd0b0282010-01-21 00:19:58 +0000572const AsmToken &AsmParser::Lex() {
573 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000574
Sean Callananfd0b0282010-01-21 00:19:58 +0000575 if (tok->is(AsmToken::Eof)) {
576 // If this is the end of an included file, pop the parent file off the
577 // include stack.
578 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
579 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000580 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000581 tok = &Lexer.Lex();
582 }
583 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000584
Sean Callananfd0b0282010-01-21 00:19:58 +0000585 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000586 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000587
Sean Callananfd0b0282010-01-21 00:19:58 +0000588 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000589}
590
Chris Lattner79180e22010-04-05 23:15:42 +0000591bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000592 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000593 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000594 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000595
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000596 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000597 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000598
599 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000600 AsmCond StartingCondState = TheCondState;
601
Kevin Enderby613b7572011-11-01 22:27:22 +0000602 // If we are generating dwarf for assembly source files save the initial text
603 // section and generate a .file directive.
604 if (getContext().getGenDwarfForAssembly()) {
Peter Collingbournedf39be62013-04-17 21:18:16 +0000605 getContext().setGenDwarfSection(getStreamer().getCurrentSection().first);
Kevin Enderby94c2e852011-12-09 18:09:40 +0000606 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
607 getStreamer().EmitLabel(SectionStartSym);
608 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000609 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
Eric Christopher6c583142012-12-18 00:31:01 +0000610 StringRef(),
611 getContext().getMainFileName());
Kevin Enderby613b7572011-11-01 22:27:22 +0000612 }
613
Chris Lattnerb717fb02009-07-02 21:53:43 +0000614 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000615 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000616 ParseStatementInfo Info;
617 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000618
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000619 // We had an error, validate that one was emitted and recover by skipping to
620 // the next line.
621 assert(HadError && "Parse statement returned an error, but none emitted!");
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000622 eatToEndOfStatement();
Chris Lattnerb717fb02009-07-02 21:53:43 +0000623 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000624
625 if (TheCondState.TheCond != StartingCondState.TheCond ||
626 TheCondState.Ignore != StartingCondState.Ignore)
627 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000628
629 // Check to see there are no empty DwarfFile slots.
Manman Ren9e999ad2013-03-12 20:17:00 +0000630 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000631 getContext().getMCDwarfFiles();
632 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000633 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000634 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000635 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000636
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000637 // Check to see that all assembler local symbols were actually defined.
638 // Targets that don't do subsections via symbols may not want this, though,
639 // so conservatively exclude them. Only do this if we're finalizing, though,
640 // as otherwise we won't necessarilly have seen everything yet.
641 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
642 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
643 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
644 e = Symbols.end();
645 i != e; ++i) {
646 MCSymbol *Sym = i->getValue();
647 // Variable symbols may not be marked as defined, so check those
648 // explicitly. If we know it's a variable, we have a definition for
649 // the purposes of this check.
650 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
651 // FIXME: We would really like to refer back to where the symbol was
652 // first referenced for a source location. We need to add something
653 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000654 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
655 "assembler local symbol '" + Sym->getName() +
656 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000657 }
658 }
659
660
Chris Lattner79180e22010-04-05 23:15:42 +0000661 // Finalize the output stream if there are no errors and if the client wants
662 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000663 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000664 Out.Finish();
665
Chris Lattnerb717fb02009-07-02 21:53:43 +0000666 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000667}
668
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000669void AsmParser::checkForValidSection() {
Peter Collingbournedf39be62013-04-17 21:18:16 +0000670 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000671 TokError("expected section directive before assembly directive");
Eli Bendersky030f63a2013-01-14 19:04:57 +0000672 Out.InitToTextSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000673 }
674}
675
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000676/// eatToEndOfStatement - Throw away the rest of the line for testing purposes.
677void AsmParser::eatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000678 while (Lexer.isNot(AsmToken::EndOfStatement) &&
679 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000680 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000681
Chris Lattner2cf5f142009-06-22 01:29:09 +0000682 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000683 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000684 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000685}
686
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000687StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000688 const char *Start = getTok().getLoc().getPointer();
689
690 while (Lexer.isNot(AsmToken::EndOfStatement) &&
691 Lexer.isNot(AsmToken::Eof))
692 Lex();
693
694 const char *End = getTok().getLoc().getPointer();
695 return StringRef(Start, End - Start);
696}
Chris Lattnerc4193832009-06-22 05:51:26 +0000697
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000698StringRef AsmParser::ParseStringToComma() {
699 const char *Start = getTok().getLoc().getPointer();
700
701 while (Lexer.isNot(AsmToken::EndOfStatement) &&
702 Lexer.isNot(AsmToken::Comma) &&
703 Lexer.isNot(AsmToken::Eof))
704 Lex();
705
706 const char *End = getTok().getLoc().getPointer();
707 return StringRef(Start, End - Start);
708}
709
Chris Lattner74ec1a32009-06-22 06:32:03 +0000710/// ParseParenExpr - Parse a paren expression and return it.
711/// NOTE: This assumes the leading '(' has already been consumed.
712///
713/// parenexpr ::= expr)
714///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000715bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000716 if (parseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000717 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000718 return TokError("expected ')' in parentheses expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000719 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000720 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000721 return false;
722}
Chris Lattnerc4193832009-06-22 05:51:26 +0000723
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000724/// ParseBracketExpr - Parse a bracket expression and return it.
725/// NOTE: This assumes the leading '[' has already been consumed.
726///
727/// bracketexpr ::= expr]
728///
729bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000730 if (parseExpression(Res)) return true;
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000731 if (Lexer.isNot(AsmToken::RBrac))
732 return TokError("expected ']' in brackets expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000733 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000734 Lex();
735 return false;
736}
737
Chris Lattner74ec1a32009-06-22 06:32:03 +0000738/// ParsePrimaryExpr - Parse a primary expression and return it.
739/// primaryexpr ::= (parenexpr
740/// primaryexpr ::= symbol
741/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000742/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000743/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000744bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby5de048e2013-01-22 21:09:20 +0000745 SMLoc FirstTokenLoc = getLexer().getLoc();
746 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
747 switch (FirstTokenKind) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000748 default:
749 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000750 // If we have an error assume that we've already handled it.
751 case AsmToken::Error:
752 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000753 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000754 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000755 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000756 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000757 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000758 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000759 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000760 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000761 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000762 StringRef Identifier;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000763 if (parseIdentifier(Identifier)) {
Kevin Enderby5de048e2013-01-22 21:09:20 +0000764 if (FirstTokenKind == AsmToken::Dollar)
765 return Error(FirstTokenLoc, "invalid token in expression");
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000766 return true;
Kevin Enderby5de048e2013-01-22 21:09:20 +0000767 }
Daniel Dunbare17edff2010-08-24 19:13:42 +0000768
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000769 EndLoc = SMLoc::getFromPointer(Identifier.end());
770
Daniel Dunbarfffff912009-10-16 01:34:54 +0000771 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000772 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000773 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000774
775 // Lookup the symbol variant if used.
776 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000777 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000778 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000779 if (Variant == MCSymbolRefExpr::VK_Invalid) {
780 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000781 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000782 }
783 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000784
Daniel Dunbarfffff912009-10-16 01:34:54 +0000785 // If this is an absolute variable reference, substitute it now to preserve
786 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000787 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000788 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000789 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000790
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000791 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000792 return false;
793 }
794
795 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000796 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000797 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000798 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000799 case AsmToken::Integer: {
800 SMLoc Loc = getTok().getLoc();
801 int64_t IntVal = getTok().getIntVal();
802 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000803 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000804 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000805 // Look for 'b' or 'f' following an Integer as a directional label
806 if (Lexer.getKind() == AsmToken::Identifier) {
807 StringRef IDVal = getTok().getString();
Ulrich Weigand151ad372013-06-20 16:24:17 +0000808 // Lookup the symbol variant if used.
809 std::pair<StringRef, StringRef> Split = IDVal.split('@');
810 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
811 if (Split.first.size() != IDVal.size()) {
812 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
813 if (Variant == MCSymbolRefExpr::VK_Invalid) {
814 Variant = MCSymbolRefExpr::VK_None;
815 return TokError("invalid variant '" + Split.second + "'");
816 }
817 IDVal = Split.first;
818 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000819 if (IDVal == "f" || IDVal == "b"){
820 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
821 IDVal == "f" ? 1 : 0);
Ulrich Weigand151ad372013-06-20 16:24:17 +0000822 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000823 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000824 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000825 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000826 Lex(); // Eat identifier.
827 }
828 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000829 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000830 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000831 case AsmToken::Real: {
832 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000833 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000834 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000835 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000836 Lex(); // Eat token.
837 return false;
838 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000839 case AsmToken::Dot: {
840 // This is a '.' reference, which references the current PC. Emit a
841 // temporary label to the streamer and refer to it.
842 MCSymbol *Sym = Ctx.CreateTempSymbol();
843 Out.EmitLabel(Sym);
844 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000845 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattnerd3050352010-04-14 04:40:28 +0000846 Lex(); // Eat identifier.
847 return false;
848 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000849 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000850 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000851 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000852 case AsmToken::LBrac:
853 if (!PlatformParser->HasBracketExpressions())
854 return TokError("brackets expression not supported on this target");
855 Lex(); // Eat the '['.
856 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000857 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000858 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000859 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000860 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000861 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000862 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000863 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000864 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000865 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000866 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000867 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000868 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000869 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000870 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000871 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000872 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000873 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000874 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000875 }
876}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000877
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000878bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000879 SMLoc EndLoc;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000880 return parseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000881}
882
Chad Rosierba69b362013-04-10 17:35:30 +0000883bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
884 return ParsePrimaryExpr(Res, EndLoc);
885}
886
Daniel Dunbarcceba832010-09-17 02:47:07 +0000887const MCExpr *
888AsmParser::ApplyModifierToExpr(const MCExpr *E,
889 MCSymbolRefExpr::VariantKind Variant) {
890 // Recurse over the given expression, rebuilding it to apply the given variant
891 // if there is exactly one symbol.
892 switch (E->getKind()) {
893 case MCExpr::Target:
894 case MCExpr::Constant:
895 return 0;
896
897 case MCExpr::SymbolRef: {
898 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
899
900 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
901 TokError("invalid variant on expression '" +
902 getTok().getIdentifier() + "' (already modified)");
903 return E;
904 }
905
906 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
907 }
908
909 case MCExpr::Unary: {
910 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
911 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
912 if (!Sub)
913 return 0;
914 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
915 }
916
917 case MCExpr::Binary: {
918 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
919 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
920 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
921
922 if (!LHS && !RHS)
923 return 0;
924
925 if (!LHS) LHS = BE->getLHS();
926 if (!RHS) RHS = BE->getRHS();
927
928 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
929 }
930 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000931
Craig Topper85814382012-02-07 05:05:23 +0000932 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000933}
934
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000935/// parseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000936///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000937/// expr ::= expr &&,|| expr -> lowest.
938/// expr ::= expr |,^,&,! expr
939/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
940/// expr ::= expr <<,>> expr
941/// expr ::= expr +,- expr
942/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000943/// expr ::= primaryexpr
944///
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000945bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000946 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000947 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000948 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
949 return true;
950
Daniel Dunbarcceba832010-09-17 02:47:07 +0000951 // As a special case, we support 'a op b @ modifier' by rewriting the
952 // expression to include the modifier. This is inefficient, but in general we
953 // expect users to use 'a@modifier op b'.
954 if (Lexer.getKind() == AsmToken::At) {
955 Lex();
956
957 if (Lexer.isNot(AsmToken::Identifier))
958 return TokError("unexpected symbol modifier following '@'");
959
960 MCSymbolRefExpr::VariantKind Variant =
961 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
962 if (Variant == MCSymbolRefExpr::VK_Invalid)
963 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
964
965 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
966 if (!ModifiedRes) {
967 return TokError("invalid modifier '" + getTok().getIdentifier() +
968 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000969 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000970
Daniel Dunbarcceba832010-09-17 02:47:07 +0000971 Res = ModifiedRes;
972 Lex();
973 }
974
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000975 // Try to constant fold it up front, if possible.
976 int64_t Value;
977 if (Res->EvaluateAsAbsolute(Value))
978 Res = MCConstantExpr::Create(Value, getContext());
979
980 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000981}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000982
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000983bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000984 Res = 0;
985 return ParseParenExpr(Res, EndLoc) ||
986 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000987}
988
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000989bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000990 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000991
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000992 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000993 if (parseExpression(Expr))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000994 return true;
995
Daniel Dunbare00b0112009-10-16 01:57:52 +0000996 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000997 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000998
999 return false;
1000}
1001
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001002static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001003 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001004 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001005 default:
1006 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +00001007
Jim Grosbachfbe16812011-08-20 16:24:13 +00001008 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +00001009 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001010 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001011 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001012 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001013 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001014 return 1;
1015
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001016
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001017 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +00001018 //
1019 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +00001020 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001021 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001022 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001023 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001024 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001025 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001026 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001027 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001028 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001029
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001030 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001031 case AsmToken::EqualEqual:
1032 Kind = MCBinaryExpr::EQ;
1033 return 3;
1034 case AsmToken::ExclaimEqual:
1035 case AsmToken::LessGreater:
1036 Kind = MCBinaryExpr::NE;
1037 return 3;
1038 case AsmToken::Less:
1039 Kind = MCBinaryExpr::LT;
1040 return 3;
1041 case AsmToken::LessEqual:
1042 Kind = MCBinaryExpr::LTE;
1043 return 3;
1044 case AsmToken::Greater:
1045 Kind = MCBinaryExpr::GT;
1046 return 3;
1047 case AsmToken::GreaterEqual:
1048 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001049 return 3;
1050
Jim Grosbachfbe16812011-08-20 16:24:13 +00001051 // Intermediate Precedence: <<, >>
1052 case AsmToken::LessLess:
1053 Kind = MCBinaryExpr::Shl;
1054 return 4;
1055 case AsmToken::GreaterGreater:
1056 Kind = MCBinaryExpr::Shr;
1057 return 4;
1058
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001059 // High Intermediate Precedence: +, -
1060 case AsmToken::Plus:
1061 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001062 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001063 case AsmToken::Minus:
1064 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001065 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001066
Jim Grosbachfbe16812011-08-20 16:24:13 +00001067 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001068 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001069 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001070 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001071 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001072 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001073 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001074 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001075 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001076 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001077 }
1078}
1079
1080
1081/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1082/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001083bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1084 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001085 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001086 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001087 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001088
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001089 // If the next token is lower precedence than we are allowed to eat, return
1090 // successfully with what we ate already.
1091 if (TokPrec < Precedence)
1092 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001093
Sean Callanan79ed1a82010-01-19 20:22:31 +00001094 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001095
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001096 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001097 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001098 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001099
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001100 // If BinOp binds less tightly with RHS than the operator after RHS, let
1101 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001102 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001103 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001104 if (TokPrec < NextTokPrec) {
Kevin Enderby88535dd2013-05-07 21:40:58 +00001105 if (ParseBinOpRHS(TokPrec+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001106 }
1107
Daniel Dunbar475839e2009-06-29 20:37:27 +00001108 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001109 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001110 }
1111}
1112
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001113/// ParseStatement:
1114/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001115/// ::= Label* Directive ...Operands... EndOfStatement
1116/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001117bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001118 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001119 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001120 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001121 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001122 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001123
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001124 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001125 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001126 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001127 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001128 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001129 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001130 if (Lexer.is(AsmToken::Hash))
1131 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001132
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001133 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001134 if (Lexer.is(AsmToken::Integer)) {
1135 LocalLabelVal = getTok().getIntVal();
1136 if (LocalLabelVal < 0) {
1137 if (!TheCondState.Ignore)
1138 return TokError("unexpected token at start of statement");
1139 IDVal = "";
Eli Benderskyed5df012013-01-16 19:32:36 +00001140 } else {
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001141 IDVal = getTok().getString();
1142 Lex(); // Consume the integer token to be used as an identifier token.
1143 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001144 if (!TheCondState.Ignore)
1145 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001146 }
1147 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001148 } else if (Lexer.is(AsmToken::Dot)) {
1149 // Treat '.' as a valid identifier in this context.
1150 Lex();
1151 IDVal = ".";
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001152 } else if (parseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001153 if (!TheCondState.Ignore)
1154 return TokError("unexpected token at start of statement");
1155 IDVal = "";
1156 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001157
Chris Lattner7834fac2010-04-17 18:14:27 +00001158 // Handle conditional assembly here before checking for skipping. We
1159 // have to do this so that .endif isn't skipped in a ".if 0" block for
1160 // example.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001161 StringMap<DirectiveKind>::const_iterator DirKindIt =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001162 DirectiveKindMap.find(IDVal);
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001163 DirectiveKind DirKind =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001164 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1165 DirKindIt->getValue();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001166 switch (DirKind) {
1167 default:
1168 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001169 case DK_IF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001170 return ParseDirectiveIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001171 case DK_IFB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001172 return ParseDirectiveIfb(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001173 case DK_IFNB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001174 return ParseDirectiveIfb(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001175 case DK_IFC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001176 return ParseDirectiveIfc(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001177 case DK_IFNC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001178 return ParseDirectiveIfc(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001179 case DK_IFDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001180 return ParseDirectiveIfdef(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001181 case DK_IFNDEF:
1182 case DK_IFNOTDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001183 return ParseDirectiveIfdef(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001184 case DK_ELSEIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001185 return ParseDirectiveElseIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001186 case DK_ELSE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001187 return ParseDirectiveElse(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001188 case DK_ENDIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001189 return ParseDirectiveEndIf(IDLoc);
1190 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001191
Eli Benderskyed5df012013-01-16 19:32:36 +00001192 // Ignore the statement if in the middle of inactive conditional
1193 // (e.g. ".if 0").
Chad Rosier17feeec2012-10-20 00:47:08 +00001194 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001195 eatToEndOfStatement();
Chris Lattner7834fac2010-04-17 18:14:27 +00001196 return false;
1197 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001198
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001199 // FIXME: Recurse on local labels?
1200
1201 // See what kind of statement we have.
1202 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001203 case AsmToken::Colon: {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001204 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001205
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001206 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001207 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001208
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001209 // Diagnose attempt to use '.' as a label.
1210 if (IDVal == ".")
1211 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1212
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001213 // Diagnose attempt to use a variable as a label.
1214 //
1215 // FIXME: Diagnostics. Note the location of the definition as a label.
1216 // FIXME: This doesn't diagnose assignment to a symbol which has been
1217 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001218 MCSymbol *Sym;
1219 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001220 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001221 else
1222 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001223 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001224 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001225
Daniel Dunbar959fd882009-08-26 22:13:22 +00001226 // Emit the label.
Chad Rosierdeb1bab2013-01-07 20:34:12 +00001227 if (!ParsingInlineAsm)
1228 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001229
Kevin Enderby94c2e852011-12-09 18:09:40 +00001230 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001231 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001232 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001233 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1234 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001235
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001236 // Consume any end of statement token, if present, to avoid spurious
1237 // AddBlankLine calls().
1238 if (Lexer.is(AsmToken::EndOfStatement)) {
1239 Lex();
1240 if (Lexer.is(AsmToken::Eof))
1241 return false;
1242 }
1243
Eli Friedman2128aae2012-10-22 23:58:19 +00001244 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001245 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001246
Daniel Dunbar3f872332009-07-28 16:08:33 +00001247 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001248 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001249 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001250
Nico Weber4c4c7322011-01-28 03:04:41 +00001251 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001252
1253 default: // Normal instruction or directive.
1254 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001255 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001256
1257 // If macros are enabled, check to see if this is a macro instantiation.
Eli Bendersky733c3362013-01-14 18:08:41 +00001258 if (MacrosEnabled())
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001259 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1260 return HandleMacroEntry(M, IDLoc);
1261 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001262
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001263 // Otherwise, we have a normal instruction or directive.
Eli Bendersky6ee13082013-01-15 22:59:42 +00001264
1265 // Directives start with "."
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001266 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00001267 // There are several entities interested in parsing directives:
1268 //
1269 // 1. The target-specific assembly parser. Some directives are target
1270 // specific or may potentially behave differently on certain targets.
1271 // 2. Asm parser extensions. For example, platform-specific parsers
1272 // (like the ELF parser) register themselves as extensions.
1273 // 3. The generic directive parser implemented by this class. These are
1274 // all the directives that behave in a target and platform independent
1275 // manner, or at least have a default behavior that's shared between
1276 // all targets and platforms.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001277
Eli Bendersky6ee13082013-01-15 22:59:42 +00001278 // First query the target-specific parser. It will return 'true' if it
1279 // isn't interested in this directive.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001280 if (!getTargetParser().ParseDirective(ID))
1281 return false;
1282
Eli Bendersky6ee13082013-01-15 22:59:42 +00001283 // Next, check the extention directive map to see if any extension has
1284 // registered itself to parse this directive.
1285 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1286 ExtensionDirectiveMap.lookup(IDVal);
1287 if (Handler.first)
1288 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1289
1290 // Finally, if no one else is interested in this directive, it must be
1291 // generic and familiar to this class.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001292 switch (DirKind) {
1293 default:
1294 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001295 case DK_SET:
1296 case DK_EQU:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001297 return ParseDirectiveSet(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001298 case DK_EQUIV:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001299 return ParseDirectiveSet(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001300 case DK_ASCII:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001301 return ParseDirectiveAscii(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001302 case DK_ASCIZ:
1303 case DK_STRING:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001304 return ParseDirectiveAscii(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001305 case DK_BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001306 return ParseDirectiveValue(1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001307 case DK_SHORT:
1308 case DK_VALUE:
1309 case DK_2BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001310 return ParseDirectiveValue(2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001311 case DK_LONG:
1312 case DK_INT:
1313 case DK_4BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001314 return ParseDirectiveValue(4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001315 case DK_QUAD:
1316 case DK_8BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001317 return ParseDirectiveValue(8);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001318 case DK_SINGLE:
1319 case DK_FLOAT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001320 return ParseDirectiveRealValue(APFloat::IEEEsingle);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001321 case DK_DOUBLE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001322 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001323 case DK_ALIGN: {
Bill Wendling99cb6222013-06-18 07:20:20 +00001324 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001325 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1326 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001327 case DK_ALIGN32: {
Bill Wendling99cb6222013-06-18 07:20:20 +00001328 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001329 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1330 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001331 case DK_BALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001332 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001333 case DK_BALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001334 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001335 case DK_BALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001336 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001337 case DK_P2ALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001338 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001339 case DK_P2ALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001340 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001341 case DK_P2ALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001342 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001343 case DK_ORG:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001344 return ParseDirectiveOrg();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001345 case DK_FILL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001346 return ParseDirectiveFill();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001347 case DK_ZERO:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001348 return ParseDirectiveZero();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001349 case DK_EXTERN:
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001350 eatToEndOfStatement(); // .extern is the default, ignore it.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001351 return false;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001352 case DK_GLOBL:
1353 case DK_GLOBAL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001354 return ParseDirectiveSymbolAttribute(MCSA_Global);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001355 case DK_INDIRECT_SYMBOL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001356 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001357 case DK_LAZY_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001358 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001359 case DK_NO_DEAD_STRIP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001360 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001361 case DK_SYMBOL_RESOLVER:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001362 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001363 case DK_PRIVATE_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001364 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001365 case DK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001366 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001367 case DK_WEAK_DEFINITION:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001368 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001369 case DK_WEAK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001370 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001371 case DK_WEAK_DEF_CAN_BE_HIDDEN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001372 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001373 case DK_COMM:
1374 case DK_COMMON:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001375 return ParseDirectiveComm(/*IsLocal=*/false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001376 case DK_LCOMM:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001377 return ParseDirectiveComm(/*IsLocal=*/true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001378 case DK_ABORT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001379 return ParseDirectiveAbort();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001380 case DK_INCLUDE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001381 return ParseDirectiveInclude();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001382 case DK_INCBIN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001383 return ParseDirectiveIncbin();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001384 case DK_CODE16:
1385 case DK_CODE16GCC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001386 return TokError(Twine(IDVal) + " not supported yet");
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001387 case DK_REPT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001388 return ParseDirectiveRept(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001389 case DK_IRP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001390 return ParseDirectiveIrp(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001391 case DK_IRPC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001392 return ParseDirectiveIrpc(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001393 case DK_ENDR:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001394 return ParseDirectiveEndr(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001395 case DK_BUNDLE_ALIGN_MODE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001396 return ParseDirectiveBundleAlignMode();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001397 case DK_BUNDLE_LOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001398 return ParseDirectiveBundleLock();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001399 case DK_BUNDLE_UNLOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001400 return ParseDirectiveBundleUnlock();
Eli Bendersky6ee13082013-01-15 22:59:42 +00001401 case DK_SLEB128:
1402 return ParseDirectiveLEB128(true);
1403 case DK_ULEB128:
1404 return ParseDirectiveLEB128(false);
1405 case DK_SPACE:
1406 case DK_SKIP:
1407 return ParseDirectiveSpace(IDVal);
1408 case DK_FILE:
1409 return ParseDirectiveFile(IDLoc);
1410 case DK_LINE:
1411 return ParseDirectiveLine();
1412 case DK_LOC:
1413 return ParseDirectiveLoc();
1414 case DK_STABS:
1415 return ParseDirectiveStabs();
1416 case DK_CFI_SECTIONS:
1417 return ParseDirectiveCFISections();
1418 case DK_CFI_STARTPROC:
1419 return ParseDirectiveCFIStartProc();
1420 case DK_CFI_ENDPROC:
1421 return ParseDirectiveCFIEndProc();
1422 case DK_CFI_DEF_CFA:
1423 return ParseDirectiveCFIDefCfa(IDLoc);
1424 case DK_CFI_DEF_CFA_OFFSET:
1425 return ParseDirectiveCFIDefCfaOffset();
1426 case DK_CFI_ADJUST_CFA_OFFSET:
1427 return ParseDirectiveCFIAdjustCfaOffset();
1428 case DK_CFI_DEF_CFA_REGISTER:
1429 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1430 case DK_CFI_OFFSET:
1431 return ParseDirectiveCFIOffset(IDLoc);
1432 case DK_CFI_REL_OFFSET:
1433 return ParseDirectiveCFIRelOffset(IDLoc);
1434 case DK_CFI_PERSONALITY:
1435 return ParseDirectiveCFIPersonalityOrLsda(true);
1436 case DK_CFI_LSDA:
1437 return ParseDirectiveCFIPersonalityOrLsda(false);
1438 case DK_CFI_REMEMBER_STATE:
1439 return ParseDirectiveCFIRememberState();
1440 case DK_CFI_RESTORE_STATE:
1441 return ParseDirectiveCFIRestoreState();
1442 case DK_CFI_SAME_VALUE:
1443 return ParseDirectiveCFISameValue(IDLoc);
1444 case DK_CFI_RESTORE:
1445 return ParseDirectiveCFIRestore(IDLoc);
1446 case DK_CFI_ESCAPE:
1447 return ParseDirectiveCFIEscape();
1448 case DK_CFI_SIGNAL_FRAME:
1449 return ParseDirectiveCFISignalFrame();
1450 case DK_CFI_UNDEFINED:
1451 return ParseDirectiveCFIUndefined(IDLoc);
1452 case DK_CFI_REGISTER:
1453 return ParseDirectiveCFIRegister(IDLoc);
1454 case DK_MACROS_ON:
1455 case DK_MACROS_OFF:
1456 return ParseDirectiveMacrosOnOff(IDVal);
1457 case DK_MACRO:
1458 return ParseDirectiveMacro(IDLoc);
1459 case DK_ENDM:
1460 case DK_ENDMACRO:
1461 return ParseDirectiveEndMacro(IDVal);
1462 case DK_PURGEM:
1463 return ParseDirectivePurgeMacro(IDLoc);
Eli Friedman5d68ec22010-07-19 04:17:25 +00001464 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001465
Jim Grosbach686c0182012-05-01 18:38:27 +00001466 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001467 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001468
Chad Rosier469b1442013-02-12 21:33:51 +00001469 // __asm _emit or __asm __emit
1470 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1471 IDVal == "_EMIT" || IDVal == "__EMIT"))
1472 return ParseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1473
1474 // __asm align
1475 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1476 return ParseDirectiveMSAlign(IDLoc, Info);
Eli Friedman2128aae2012-10-22 23:58:19 +00001477
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001478 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001479
Chris Lattnera7f13542010-05-19 23:34:33 +00001480 // Canonicalize the opcode to lower case.
Eli Benderskyed5df012013-01-16 19:32:36 +00001481 std::string OpcodeStr = IDVal.lower();
Chad Rosier6a020a72012-10-25 20:41:34 +00001482 ParseInstructionInfo IInfo(Info.AsmRewrites);
Eli Benderskyed5df012013-01-16 19:32:36 +00001483 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr,
1484 IDLoc, Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001485 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001486
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001487 // Dump the parsed representation, if requested.
1488 if (getShowParsedOperands()) {
1489 SmallString<256> Str;
1490 raw_svector_ostream OS(Str);
1491 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001492 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001493 if (i != 0)
1494 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001495 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001496 }
1497 OS << "]";
1498
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001499 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001500 }
1501
Kevin Enderby613b7572011-11-01 22:27:22 +00001502 // If we are generating dwarf for assembly source files and the current
1503 // section is the initial text section then generate a .loc directive for
1504 // the instruction.
1505 if (!HadError && getContext().getGenDwarfForAssembly() &&
Peter Collingbournedf39be62013-04-17 21:18:16 +00001506 getContext().getGenDwarfSection() ==
1507 getStreamer().getCurrentSection().first) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001508
Eli Benderskyed5df012013-01-16 19:32:36 +00001509 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
Kevin Enderby938482f2012-11-01 17:31:35 +00001510
Eli Benderskyed5df012013-01-16 19:32:36 +00001511 // If we previously parsed a cpp hash file line comment then make sure the
1512 // current Dwarf File is for the CppHashFilename if not then emit the
1513 // Dwarf File table for it and adjust the line number for the .loc.
Manman Ren9e999ad2013-03-12 20:17:00 +00001514 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
Eli Benderskyed5df012013-01-16 19:32:36 +00001515 getContext().getMCDwarfFiles();
1516 if (CppHashFilename.size() != 0) {
1517 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
Kevin Enderby938482f2012-11-01 17:31:35 +00001518 CppHashFilename)
Eli Benderskyed5df012013-01-16 19:32:36 +00001519 getStreamer().EmitDwarfFileDirective(
1520 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001521
Kevin Enderby32c1a822012-11-05 21:55:41 +00001522 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
Kevin Enderby938482f2012-11-01 17:31:35 +00001523 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
Eli Benderskyed5df012013-01-16 19:32:36 +00001524 }
Kevin Enderby938482f2012-11-01 17:31:35 +00001525
Kevin Enderby613b7572011-11-01 22:27:22 +00001526 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001527 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001528 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001529 StringRef());
1530 }
1531
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001532 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001533 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001534 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001535 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1536 Info.ParsedOperands,
1537 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001538 ParsingInlineAsm);
1539 }
Chris Lattner98986712010-01-14 22:21:20 +00001540
Chris Lattnercbf8a982010-09-11 16:18:25 +00001541 // Don't skip the rest of the line, the instruction parser is responsible for
1542 // that.
1543 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001544}
Chris Lattner9a023f72009-06-24 04:43:34 +00001545
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001546/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1547/// since they may not be able to be tokenized to get to the end of line token.
1548void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001549 if (!Lexer.is(AsmToken::EndOfStatement))
1550 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001551 // Eat EOL.
1552 Lex();
1553}
1554
1555/// ParseCppHashLineFilenameComment as this:
1556/// ::= # number "filename"
1557/// or just as a full line comment if it doesn't have a number and a string.
1558bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1559 Lex(); // Eat the hash token.
1560
1561 if (getLexer().isNot(AsmToken::Integer)) {
1562 // Consume the line since in cases it is not a well-formed line directive,
1563 // as if were simply a full line comment.
1564 EatToEndOfLine();
1565 return false;
1566 }
1567
1568 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001569 Lex();
1570
1571 if (getLexer().isNot(AsmToken::String)) {
1572 EatToEndOfLine();
1573 return false;
1574 }
1575
1576 StringRef Filename = getTok().getString();
1577 // Get rid of the enclosing quotes.
1578 Filename = Filename.substr(1, Filename.size()-2);
1579
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001580 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1581 CppHashLoc = L;
1582 CppHashFilename = Filename;
1583 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001584 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001585
1586 // Ignore any trailing characters, they're just comment.
1587 EatToEndOfLine();
1588 return false;
1589}
1590
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001591/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001592/// for the Filename and LineNo if any in the diagnostic.
1593void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1594 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1595 raw_ostream &OS = errs();
1596
1597 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1598 const SMLoc &DiagLoc = Diag.getLoc();
1599 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1600 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1601
1602 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1603 // before printing the message.
1604 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001605 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001606 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1607 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1608 }
1609
Eric Christopher2318ba12012-12-18 00:30:54 +00001610 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001611 // manager changed or buffer changed (like in a nested include) then just
1612 // print the normal diagnostic using its Filename and LineNo.
1613 if (!Parser->CppHashLineNumber ||
1614 &DiagSrcMgr != &Parser->SrcMgr ||
1615 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001616 if (Parser->SavedDiagHandler)
1617 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1618 else
1619 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001620 return;
1621 }
1622
Eric Christopher2318ba12012-12-18 00:30:54 +00001623 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001624 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1625 // the diagnostic.
1626 const std::string Filename = Parser->CppHashFilename;
1627
1628 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1629 int CppHashLocLineNo =
1630 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1631 int LineNo = Parser->CppHashLineNumber - 1 +
1632 (DiagLocLineNo - CppHashLocLineNo);
1633
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001634 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1635 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001636 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001637 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001638
Benjamin Kramer04a04262011-10-16 10:48:29 +00001639 if (Parser->SavedDiagHandler)
1640 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1641 else
1642 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001643}
1644
Rafael Espindola799aacf2012-08-21 18:29:30 +00001645// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1646// difference being that that function accepts '@' as part of identifiers and
1647// we can't do that. AsmLexer.cpp should probably be changed to handle
1648// '@' as a special case when needed.
1649static bool isIdentifierChar(char c) {
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001650 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1651 c == '.';
Rafael Espindola799aacf2012-08-21 18:29:30 +00001652}
1653
Rafael Espindola761cb062012-06-03 23:57:14 +00001654bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001655 const MCAsmMacroParameters &Parameters,
1656 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001657 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001658 unsigned NParameters = Parameters.size();
1659 if (NParameters != 0 && NParameters != A.size())
1660 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001661
Preston Gurd7b6f2032012-09-19 20:36:12 +00001662 // A macro without parameters is handled differently on Darwin:
1663 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001664 while (!Body.empty()) {
1665 // Scan for the next substitution.
1666 std::size_t End = Body.size(), Pos = 0;
1667 for (; Pos != End; ++Pos) {
1668 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001669 if (!NParameters) {
1670 // This macro has no parameters, look for $0, $1, etc.
1671 if (Body[Pos] != '$' || Pos + 1 == End)
1672 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001673
Rafael Espindola65366442011-06-05 02:43:45 +00001674 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001675 if (Next == '$' || Next == 'n' ||
1676 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola65366442011-06-05 02:43:45 +00001677 break;
1678 } else {
1679 // This macro has parameters, look for \foo, \bar, etc.
1680 if (Body[Pos] == '\\' && Pos + 1 != End)
1681 break;
1682 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001683 }
1684
1685 // Add the prefix.
1686 OS << Body.slice(0, Pos);
1687
1688 // Check if we reached the end.
1689 if (Pos == End)
1690 break;
1691
Rafael Espindola65366442011-06-05 02:43:45 +00001692 if (!NParameters) {
1693 switch (Body[Pos+1]) {
1694 // $$ => $
1695 case '$':
1696 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001697 break;
1698
Rafael Espindola65366442011-06-05 02:43:45 +00001699 // $n => number of arguments
1700 case 'n':
1701 OS << A.size();
1702 break;
1703
1704 // $[0-9] => argument
1705 default: {
1706 // Missing arguments are ignored.
1707 unsigned Index = Body[Pos+1] - '0';
1708 if (Index >= A.size())
1709 break;
1710
1711 // Otherwise substitute with the token values, with spaces eliminated.
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001712 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001713 ie = A[Index].end(); it != ie; ++it)
1714 OS << it->getString();
1715 break;
1716 }
1717 }
1718 Pos += 2;
1719 } else {
1720 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001721 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001722 ++I;
1723
1724 const char *Begin = Body.data() + Pos +1;
1725 StringRef Argument(Begin, I - (Pos +1));
1726 unsigned Index = 0;
1727 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001728 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001729 break;
1730
Preston Gurd7b6f2032012-09-19 20:36:12 +00001731 if (Index == NParameters) {
1732 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1733 Pos += 3;
1734 else {
1735 OS << '\\' << Argument;
1736 Pos = I;
1737 }
1738 } else {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001739 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Preston Gurd7b6f2032012-09-19 20:36:12 +00001740 ie = A[Index].end(); it != ie; ++it)
1741 if (it->getKind() == AsmToken::String)
1742 OS << it->getStringContents();
1743 else
1744 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001745
Preston Gurd7b6f2032012-09-19 20:36:12 +00001746 Pos += 1 + Argument.size();
1747 }
Rafael Espindola65366442011-06-05 02:43:45 +00001748 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001749 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001750 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001751 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001752
Rafael Espindola65366442011-06-05 02:43:45 +00001753 return false;
1754}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001755
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001756MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001757 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001758 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001759 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1760 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001761{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001762}
1763
Preston Gurd7b6f2032012-09-19 20:36:12 +00001764static bool IsOperator(AsmToken::TokenKind kind)
1765{
1766 switch (kind)
1767 {
1768 default:
1769 return false;
1770 case AsmToken::Plus:
1771 case AsmToken::Minus:
1772 case AsmToken::Tilde:
1773 case AsmToken::Slash:
1774 case AsmToken::Star:
1775 case AsmToken::Dot:
1776 case AsmToken::Equal:
1777 case AsmToken::EqualEqual:
1778 case AsmToken::Pipe:
1779 case AsmToken::PipePipe:
1780 case AsmToken::Caret:
1781 case AsmToken::Amp:
1782 case AsmToken::AmpAmp:
1783 case AsmToken::Exclaim:
1784 case AsmToken::ExclaimEqual:
1785 case AsmToken::Percent:
1786 case AsmToken::Less:
1787 case AsmToken::LessEqual:
1788 case AsmToken::LessLess:
1789 case AsmToken::LessGreater:
1790 case AsmToken::Greater:
1791 case AsmToken::GreaterEqual:
1792 case AsmToken::GreaterGreater:
1793 return true;
1794 }
1795}
1796
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001797bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
Preston Gurd7b6f2032012-09-19 20:36:12 +00001798 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001799 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001800 unsigned AddTokens = 0;
1801
1802 // gas accepts arguments separated by whitespace, except on Darwin
1803 if (!IsDarwin)
1804 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001805
1806 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001807 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1808 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001809 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001810 }
1811
1812 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1813 // Spaces and commas cannot be mixed to delimit parameters
1814 if (ArgumentDelimiter == AsmToken::Eof)
1815 ArgumentDelimiter = AsmToken::Comma;
1816 else if (ArgumentDelimiter != AsmToken::Comma) {
1817 Lexer.setSkipSpace(true);
1818 return TokError("expected ' ' for macro argument separator");
1819 }
1820 break;
1821 }
1822
1823 if (Lexer.is(AsmToken::Space)) {
1824 Lex(); // Eat spaces
1825
1826 // Spaces can delimit parameters, but could also be part an expression.
1827 // If the token after a space is an operator, add the token and the next
1828 // one into this argument
1829 if (ArgumentDelimiter == AsmToken::Space ||
1830 ArgumentDelimiter == AsmToken::Eof) {
1831 if (IsOperator(Lexer.getKind())) {
1832 // Check to see whether the token is used as an operator,
1833 // or part of an identifier
Jordan Rose3ebe59c2013-01-07 19:00:49 +00001834 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd7b6f2032012-09-19 20:36:12 +00001835 if (*NextChar == ' ')
1836 AddTokens = 2;
1837 }
1838
1839 if (!AddTokens && ParenLevel == 0) {
1840 if (ArgumentDelimiter == AsmToken::Eof &&
1841 !IsOperator(Lexer.getKind()))
1842 ArgumentDelimiter = AsmToken::Space;
1843 break;
1844 }
1845 }
1846 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001847
1848 // HandleMacroEntry relies on not advancing the lexer here
1849 // to be able to fill in the remaining default parameter values
1850 if (Lexer.is(AsmToken::EndOfStatement))
1851 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001852
1853 // Adjust the current parentheses level.
1854 if (Lexer.is(AsmToken::LParen))
1855 ++ParenLevel;
1856 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1857 --ParenLevel;
1858
1859 // Append the token to the current argument list.
1860 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001861 if (AddTokens)
1862 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001863 Lex();
1864 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001865
1866 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001867 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001868 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001869 return false;
1870}
1871
1872// Parse the macro instantiation arguments.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001873bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001874 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001875 // Argument delimiter is initially unknown. It will be set by
1876 // ParseMacroArgument()
1877 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001878
1879 // Parse two kinds of macro invocations:
1880 // - macros defined without any parameters accept an arbitrary number of them
1881 // - macros defined with parameters accept at most that many of them
1882 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1883 ++Parameter) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001884 MCAsmMacroArgument MA;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001885
Preston Gurd7b6f2032012-09-19 20:36:12 +00001886 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001887 return true;
1888
Preston Gurd6c9176a2012-09-19 20:29:04 +00001889 if (!MA.empty() || !NParameters)
1890 A.push_back(MA);
1891 else if (NParameters) {
1892 if (!M->Parameters[Parameter].second.empty())
1893 A.push_back(M->Parameters[Parameter].second);
1894 }
Jim Grosbach97146442012-07-30 22:44:17 +00001895
Preston Gurd6c9176a2012-09-19 20:29:04 +00001896 // At the end of the statement, fill in remaining arguments that have
1897 // default values. If there aren't any, then the next argument is
1898 // required but missing
1899 if (Lexer.is(AsmToken::EndOfStatement)) {
1900 if (NParameters && Parameter < NParameters - 1) {
1901 if (M->Parameters[Parameter + 1].second.empty())
1902 return TokError("macro argument '" +
1903 Twine(M->Parameters[Parameter + 1].first) +
1904 "' is missing");
1905 else
1906 continue;
1907 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001908 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001909 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001910
1911 if (Lexer.is(AsmToken::Comma))
1912 Lex();
1913 }
1914 return TokError("Too many arguments");
1915}
1916
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001917const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1918 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1919 return (I == MacroMap.end()) ? NULL : I->getValue();
1920}
1921
1922void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1923 MacroMap[Name] = new MCAsmMacro(Macro);
1924}
1925
1926void AsmParser::UndefineMacro(StringRef Name) {
1927 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1928 if (I != MacroMap.end()) {
1929 delete I->getValue();
1930 MacroMap.erase(I);
1931 }
1932}
1933
1934bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001935 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1936 // this, although we should protect against infinite loops.
1937 if (ActiveMacros.size() == 20)
1938 return TokError("macros cannot be nested more than 20 levels deep");
1939
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001940 MCAsmMacroArguments A;
Rafael Espindola8a403d32012-08-08 14:51:03 +00001941 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001942 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001943
Jim Grosbach97146442012-07-30 22:44:17 +00001944 // Remove any trailing empty arguments. Do this after-the-fact as we have
1945 // to keep empty arguments in the middle of the list or positionality
1946 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001947 while (!A.empty() && A.back().empty())
1948 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001949
Rafael Espindola65366442011-06-05 02:43:45 +00001950 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1951 // to hold the macro body with substitutions.
1952 SmallString<256> Buf;
1953 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001954 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001955
Rafael Espindola8a403d32012-08-08 14:51:03 +00001956 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001957 return true;
1958
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001959 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola761cb062012-06-03 23:57:14 +00001960 // instantiation.
1961 OS << ".endmacro\n";
1962
Rafael Espindola65366442011-06-05 02:43:45 +00001963 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001964 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001965
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001966 // Create the macro instantiation object and add to the current macro
1967 // instantiation stack.
1968 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001969 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001970 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001971 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001972 ActiveMacros.push_back(MI);
1973
1974 // Jump to the macro instantiation and prime the lexer.
1975 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1976 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1977 Lex();
1978
1979 return false;
1980}
1981
1982void AsmParser::HandleMacroExit() {
1983 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001984 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001985 Lex();
1986
1987 // Pop the instantiation entry.
1988 delete ActiveMacros.back();
1989 ActiveMacros.pop_back();
1990}
1991
Rafael Espindolae71cc862012-01-28 05:57:00 +00001992static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001993 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001994 case MCExpr::Binary: {
1995 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1996 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001997 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001998 case MCExpr::Target:
1999 case MCExpr::Constant:
2000 return false;
2001 case MCExpr::SymbolRef: {
2002 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00002003 if (S.isVariable())
2004 return IsUsedIn(Sym, S.getVariableValue());
2005 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00002006 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002007 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00002008 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002009 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00002010
2011 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002012}
2013
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002014bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
2015 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002016 // FIXME: Use better location, we should use proper tokens.
2017 SMLoc EqualLoc = Lexer.getLoc();
2018
Daniel Dunbar821e3332009-08-31 08:09:28 +00002019 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002020 if (parseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002021 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002022
Rafael Espindolae71cc862012-01-28 05:57:00 +00002023 // Note: we don't count b as used in "a = b". This is to allow
2024 // a = b
2025 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002026
Daniel Dunbar3f872332009-07-28 16:08:33 +00002027 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002028 return TokError("unexpected token in assignment");
2029
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00002030 // Error on assignment to '.'.
2031 if (Name == ".") {
2032 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2033 "(use '.space' or '.org').)"));
2034 }
2035
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002036 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00002037 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002038
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002039 // Validate that the LHS is allowed to be a variable (either it has not been
2040 // used as a symbol, or it is an absolute symbol).
2041 MCSymbol *Sym = getContext().LookupSymbol(Name);
2042 if (Sym) {
2043 // Diagnose assignment to a label.
2044 //
2045 // FIXME: Diagnostics. Note the location of the definition as a label.
2046 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00002047 if (IsUsedIn(Sym, Value))
2048 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2049 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00002050 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00002051 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2052 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00002053 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002054 return Error(EqualLoc, "redefinition of '" + Name + "'");
2055 else if (!Sym->isVariable())
2056 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00002057 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002058 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2059 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002060
2061 // Don't count these checks as uses.
2062 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002063 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002064 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002065
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002066 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002067
2068 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00002069 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002070 if (NoDeadStrip)
2071 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2072
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002073
2074 return false;
2075}
2076
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002077/// parseIdentifier:
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002078/// ::= identifier
2079/// ::= string
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002080bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00002081 // The assembler has relaxed rules for accepting identifiers, in particular we
2082 // allow things like '.globl $foo', which would normally be separate
2083 // tokens. At this level, we have already lexed so we cannot (currently)
2084 // handle this as a context dependent token, instead we detect adjacent tokens
2085 // and return the combined identifier.
2086 if (Lexer.is(AsmToken::Dollar)) {
2087 SMLoc DollarLoc = getLexer().getLoc();
2088
2089 // Consume the dollar sign, and check for a following identifier.
2090 Lex();
2091 if (Lexer.isNot(AsmToken::Identifier))
2092 return true;
2093
2094 // We have a '$' followed by an identifier, make sure they are adjacent.
2095 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2096 return true;
2097
2098 // Construct the joined identifier and consume the token.
2099 Res = StringRef(DollarLoc.getPointer(),
2100 getTok().getIdentifier().size() + 1);
2101 Lex();
2102 return false;
2103 }
2104
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002105 if (Lexer.isNot(AsmToken::Identifier) &&
2106 Lexer.isNot(AsmToken::String))
2107 return true;
2108
Sean Callanan18b83232010-01-19 21:44:56 +00002109 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002110
Sean Callanan79ed1a82010-01-19 20:22:31 +00002111 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002112
2113 return false;
2114}
2115
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002116/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002117/// ::= .equ identifier ',' expression
2118/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002119/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002120bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002121 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002122
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002123 if (parseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002124 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002125
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002126 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002127 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002128 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002129
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002130 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002131}
2132
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002133bool AsmParser::parseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002134 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002135
2136 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002137 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002138 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2139 if (Str[i] != '\\') {
2140 Data += Str[i];
2141 continue;
2142 }
2143
2144 // Recognize escaped characters. Note that this escape semantics currently
2145 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2146 ++i;
2147 if (i == e)
2148 return TokError("unexpected backslash at end of string");
2149
2150 // Recognize octal sequences.
2151 if ((unsigned) (Str[i] - '0') <= 7) {
2152 // Consume up to three octal characters.
2153 unsigned Value = Str[i] - '0';
2154
2155 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2156 ++i;
2157 Value = Value * 8 + (Str[i] - '0');
2158
2159 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2160 ++i;
2161 Value = Value * 8 + (Str[i] - '0');
2162 }
2163 }
2164
2165 if (Value > 255)
2166 return TokError("invalid octal escape sequence (out of range)");
2167
2168 Data += (unsigned char) Value;
2169 continue;
2170 }
2171
2172 // Otherwise recognize individual escapes.
2173 switch (Str[i]) {
2174 default:
2175 // Just reject invalid escape sequences for now.
2176 return TokError("invalid escape sequence (unrecognized character)");
2177
2178 case 'b': Data += '\b'; break;
2179 case 'f': Data += '\f'; break;
2180 case 'n': Data += '\n'; break;
2181 case 'r': Data += '\r'; break;
2182 case 't': Data += '\t'; break;
2183 case '"': Data += '"'; break;
2184 case '\\': Data += '\\'; break;
2185 }
2186 }
2187
2188 return false;
2189}
2190
Daniel Dunbara0d14262009-06-24 23:30:00 +00002191/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002192/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2193bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002194 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002195 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002196
Daniel Dunbara0d14262009-06-24 23:30:00 +00002197 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002198 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002199 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002200
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002201 std::string Data;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002202 if (parseEscapedString(Data))
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002203 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002204
2205 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002206 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002207 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2208
Sean Callanan79ed1a82010-01-19 20:22:31 +00002209 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002210
2211 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002212 break;
2213
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002214 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002215 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002216 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002217 }
2218 }
2219
Sean Callanan79ed1a82010-01-19 20:22:31 +00002220 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002221 return false;
2222}
2223
2224/// ParseDirectiveValue
2225/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2226bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002227 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002228 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002229
Daniel Dunbara0d14262009-06-24 23:30:00 +00002230 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002231 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002232 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002233 if (parseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002234 return true;
2235
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002236 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002237 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2238 assert(Size <= 8 && "Invalid size");
2239 uint64_t IntValue = MCE->getValue();
2240 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2241 return Error(ExprLoc, "literal value out of range for directive");
2242 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2243 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002244 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002245
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002246 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002247 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002248
Daniel Dunbara0d14262009-06-24 23:30:00 +00002249 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002250 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002251 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002252 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002253 }
2254 }
2255
Sean Callanan79ed1a82010-01-19 20:22:31 +00002256 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002257 return false;
2258}
2259
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002260/// ParseDirectiveRealValue
2261/// ::= (.single | .double) [ expression (, expression)* ]
2262bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2263 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002264 checkForValidSection();
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002265
2266 for (;;) {
2267 // We don't truly support arithmetic on floating point expressions, so we
2268 // have to manually parse unary prefixes.
2269 bool IsNeg = false;
2270 if (getLexer().is(AsmToken::Minus)) {
2271 Lex();
2272 IsNeg = true;
2273 } else if (getLexer().is(AsmToken::Plus))
2274 Lex();
2275
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002276 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002277 getLexer().isNot(AsmToken::Real) &&
2278 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002279 return TokError("unexpected token in directive");
2280
2281 // Convert to an APFloat.
2282 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002283 StringRef IDVal = getTok().getString();
2284 if (getLexer().is(AsmToken::Identifier)) {
2285 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2286 Value = APFloat::getInf(Semantics);
2287 else if (!IDVal.compare_lower("nan"))
2288 Value = APFloat::getNaN(Semantics, false, ~0);
2289 else
2290 return TokError("invalid floating point literal");
2291 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002292 APFloat::opInvalidOp)
2293 return TokError("invalid floating point literal");
2294 if (IsNeg)
2295 Value.changeSign();
2296
2297 // Consume the numeric token.
2298 Lex();
2299
2300 // Emit the value as an integer.
2301 APInt AsInt = Value.bitcastToAPInt();
2302 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2303 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2304
2305 if (getLexer().is(AsmToken::EndOfStatement))
2306 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002307
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002308 if (getLexer().isNot(AsmToken::Comma))
2309 return TokError("unexpected token in directive");
2310 Lex();
2311 }
2312 }
2313
2314 Lex();
2315 return false;
2316}
2317
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002318/// ParseDirectiveZero
2319/// ::= .zero expression
2320bool AsmParser::ParseDirectiveZero() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002321 checkForValidSection();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002322
2323 int64_t NumBytes;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002324 if (parseAbsoluteExpression(NumBytes))
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002325 return true;
2326
Rafael Espindolae452b172010-10-05 19:42:57 +00002327 int64_t Val = 0;
2328 if (getLexer().is(AsmToken::Comma)) {
2329 Lex();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002330 if (parseAbsoluteExpression(Val))
Rafael Espindolae452b172010-10-05 19:42:57 +00002331 return true;
2332 }
2333
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002334 if (getLexer().isNot(AsmToken::EndOfStatement))
2335 return TokError("unexpected token in '.zero' directive");
2336
2337 Lex();
2338
Rafael Espindolae452b172010-10-05 19:42:57 +00002339 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002340
2341 return false;
2342}
2343
Daniel Dunbara0d14262009-06-24 23:30:00 +00002344/// ParseDirectiveFill
2345/// ::= .fill expression , expression , expression
2346bool AsmParser::ParseDirectiveFill() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002347 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002348
Daniel Dunbara0d14262009-06-24 23:30:00 +00002349 int64_t NumValues;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002350 if (parseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002351 return true;
2352
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002353 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002354 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002355 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002356
Daniel Dunbara0d14262009-06-24 23:30:00 +00002357 int64_t FillSize;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002358 if (parseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002359 return true;
2360
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002361 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002362 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002363 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002364
Daniel Dunbara0d14262009-06-24 23:30:00 +00002365 int64_t FillExpr;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002366 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002367 return true;
2368
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002369 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002370 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002371
Sean Callanan79ed1a82010-01-19 20:22:31 +00002372 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002373
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002374 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2375 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002376
2377 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002378 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002379
2380 return false;
2381}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002382
2383/// ParseDirectiveOrg
2384/// ::= .org expression [ , expression ]
2385bool AsmParser::ParseDirectiveOrg() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002386 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002387
Daniel Dunbar821e3332009-08-31 08:09:28 +00002388 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002389 SMLoc Loc = getTok().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002390 if (parseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002391 return true;
2392
2393 // Parse optional fill expression.
2394 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002395 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2396 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002397 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002398 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002399
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002400 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002401 return true;
2402
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002403 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002404 return TokError("unexpected token in '.org' directive");
2405 }
2406
Sean Callanan79ed1a82010-01-19 20:22:31 +00002407 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002408
Jim Grosbachebd4c052012-01-27 00:37:08 +00002409 // Only limited forms of relocatable expressions are accepted here, it
2410 // has to be relative to the current section. The streamer will return
2411 // 'true' if the expression wasn't evaluatable.
2412 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2413 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002414
2415 return false;
2416}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002417
2418/// ParseDirectiveAlign
2419/// ::= {.align, ...} expression [ , expression [ , expression ]]
2420bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002421 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002422
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002423 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002424 int64_t Alignment;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002425 if (parseAbsoluteExpression(Alignment))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002426 return true;
2427
2428 SMLoc MaxBytesLoc;
2429 bool HasFillExpr = false;
2430 int64_t FillExpr = 0;
2431 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002432 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2433 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002434 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002435 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002436
2437 // The fill expression can be omitted while specifying a maximum number of
2438 // alignment bytes, e.g:
2439 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002440 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002441 HasFillExpr = true;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002442 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002443 return true;
2444 }
2445
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002446 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2447 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002448 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002449 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002450
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002451 MaxBytesLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002452 if (parseAbsoluteExpression(MaxBytesToFill))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002453 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002454
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002455 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002456 return TokError("unexpected token in directive");
2457 }
2458 }
2459
Sean Callanan79ed1a82010-01-19 20:22:31 +00002460 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002461
Daniel Dunbar648ac512010-05-17 21:54:30 +00002462 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002463 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002464
2465 // Compute alignment in bytes.
2466 if (IsPow2) {
2467 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002468 if (Alignment >= 32) {
2469 Error(AlignmentLoc, "invalid alignment value");
2470 Alignment = 31;
2471 }
2472
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002473 Alignment = 1ULL << Alignment;
Benjamin Kramer8a89cf22013-02-16 15:00:16 +00002474 } else {
2475 // Reject alignments that aren't a power of two, for gas compatibility.
2476 if (!isPowerOf2_64(Alignment))
2477 Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002478 }
2479
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002480 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002481 if (MaxBytesLoc.isValid()) {
2482 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002483 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2484 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002485 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002486 }
2487
2488 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002489 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2490 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002491 MaxBytesToFill = 0;
2492 }
2493 }
2494
Daniel Dunbar648ac512010-05-17 21:54:30 +00002495 // Check whether we should use optimal code alignment for this .align
2496 // directive.
Peter Collingbournedf39be62013-04-17 21:18:16 +00002497 bool UseCodeAlign = getStreamer().getCurrentSection().first->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002498 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2499 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002500 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002501 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002502 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002503 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2504 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002505 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002506
2507 return false;
2508}
2509
Eli Bendersky6ee13082013-01-15 22:59:42 +00002510/// ParseDirectiveFile
2511/// ::= .file [number] filename
2512/// ::= .file number directory filename
2513bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2514 // FIXME: I'm not sure what this is.
2515 int64_t FileNumber = -1;
2516 SMLoc FileNumberLoc = getLexer().getLoc();
2517 if (getLexer().is(AsmToken::Integer)) {
2518 FileNumber = getTok().getIntVal();
2519 Lex();
2520
2521 if (FileNumber < 1)
2522 return TokError("file number less than one");
2523 }
2524
2525 if (getLexer().isNot(AsmToken::String))
2526 return TokError("unexpected token in '.file' directive");
2527
2528 // Usually the directory and filename together, otherwise just the directory.
2529 StringRef Path = getTok().getString();
2530 Path = Path.substr(1, Path.size()-2);
2531 Lex();
2532
2533 StringRef Directory;
2534 StringRef Filename;
2535 if (getLexer().is(AsmToken::String)) {
2536 if (FileNumber == -1)
2537 return TokError("explicit path specified, but no file number");
2538 Filename = getTok().getString();
2539 Filename = Filename.substr(1, Filename.size()-2);
2540 Directory = Path;
2541 Lex();
2542 } else {
2543 Filename = Path;
2544 }
2545
2546 if (getLexer().isNot(AsmToken::EndOfStatement))
2547 return TokError("unexpected token in '.file' directive");
2548
2549 if (FileNumber == -1)
2550 getStreamer().EmitFileDirective(Filename);
2551 else {
2552 if (getContext().getGenDwarfForAssembly() == true)
2553 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2554 "used to generate dwarf debug info for assembly code");
2555
2556 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2557 Error(FileNumberLoc, "file number already allocated");
2558 }
2559
2560 return false;
2561}
2562
2563/// ParseDirectiveLine
2564/// ::= .line [number]
2565bool AsmParser::ParseDirectiveLine() {
2566 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2567 if (getLexer().isNot(AsmToken::Integer))
2568 return TokError("unexpected token in '.line' directive");
2569
2570 int64_t LineNumber = getTok().getIntVal();
2571 (void) LineNumber;
2572 Lex();
2573
2574 // FIXME: Do something with the .line.
2575 }
2576
2577 if (getLexer().isNot(AsmToken::EndOfStatement))
2578 return TokError("unexpected token in '.line' directive");
2579
2580 return false;
2581}
2582
2583/// ParseDirectiveLoc
2584/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2585/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2586/// The first number is a file number, must have been previously assigned with
2587/// a .file directive, the second number is the line number and optionally the
2588/// third number is a column position (zero if not specified). The remaining
2589/// optional items are .loc sub-directives.
2590bool AsmParser::ParseDirectiveLoc() {
2591 if (getLexer().isNot(AsmToken::Integer))
2592 return TokError("unexpected token in '.loc' directive");
2593 int64_t FileNumber = getTok().getIntVal();
2594 if (FileNumber < 1)
2595 return TokError("file number less than one in '.loc' directive");
2596 if (!getContext().isValidDwarfFileNumber(FileNumber))
2597 return TokError("unassigned file number in '.loc' directive");
2598 Lex();
2599
2600 int64_t LineNumber = 0;
2601 if (getLexer().is(AsmToken::Integer)) {
2602 LineNumber = getTok().getIntVal();
2603 if (LineNumber < 1)
2604 return TokError("line number less than one in '.loc' directive");
2605 Lex();
2606 }
2607
2608 int64_t ColumnPos = 0;
2609 if (getLexer().is(AsmToken::Integer)) {
2610 ColumnPos = getTok().getIntVal();
2611 if (ColumnPos < 0)
2612 return TokError("column position less than zero in '.loc' directive");
2613 Lex();
2614 }
2615
2616 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2617 unsigned Isa = 0;
2618 int64_t Discriminator = 0;
2619 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2620 for (;;) {
2621 if (getLexer().is(AsmToken::EndOfStatement))
2622 break;
2623
2624 StringRef Name;
2625 SMLoc Loc = getTok().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002626 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002627 return TokError("unexpected token in '.loc' directive");
2628
2629 if (Name == "basic_block")
2630 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2631 else if (Name == "prologue_end")
2632 Flags |= DWARF2_FLAG_PROLOGUE_END;
2633 else if (Name == "epilogue_begin")
2634 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2635 else if (Name == "is_stmt") {
2636 Loc = getTok().getLoc();
2637 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002638 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002639 return true;
2640 // The expression must be the constant 0 or 1.
2641 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2642 int Value = MCE->getValue();
2643 if (Value == 0)
2644 Flags &= ~DWARF2_FLAG_IS_STMT;
2645 else if (Value == 1)
2646 Flags |= DWARF2_FLAG_IS_STMT;
2647 else
2648 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperefa703d2013-04-22 04:22:40 +00002649 } else {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002650 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2651 }
Craig Topperefa703d2013-04-22 04:22:40 +00002652 } else if (Name == "isa") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002653 Loc = getTok().getLoc();
2654 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002655 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002656 return true;
2657 // The expression must be a constant greater or equal to 0.
2658 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2659 int Value = MCE->getValue();
2660 if (Value < 0)
2661 return Error(Loc, "isa number less than zero");
2662 Isa = Value;
Craig Topperefa703d2013-04-22 04:22:40 +00002663 } else {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002664 return Error(Loc, "isa number not a constant value");
2665 }
Craig Topperefa703d2013-04-22 04:22:40 +00002666 } else if (Name == "discriminator") {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002667 if (parseAbsoluteExpression(Discriminator))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002668 return true;
Craig Topperefa703d2013-04-22 04:22:40 +00002669 } else {
Eli Bendersky6ee13082013-01-15 22:59:42 +00002670 return Error(Loc, "unknown sub-directive in '.loc' directive");
2671 }
2672
2673 if (getLexer().is(AsmToken::EndOfStatement))
2674 break;
2675 }
2676 }
2677
2678 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2679 Isa, Discriminator, StringRef());
2680
2681 return false;
2682}
2683
2684/// ParseDirectiveStabs
2685/// ::= .stabs string, number, number, number
2686bool AsmParser::ParseDirectiveStabs() {
2687 return TokError("unsupported directive '.stabs'");
2688}
2689
2690/// ParseDirectiveCFISections
2691/// ::= .cfi_sections section [, section]
2692bool AsmParser::ParseDirectiveCFISections() {
2693 StringRef Name;
2694 bool EH = false;
2695 bool Debug = false;
2696
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002697 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002698 return TokError("Expected an identifier");
2699
2700 if (Name == ".eh_frame")
2701 EH = true;
2702 else if (Name == ".debug_frame")
2703 Debug = true;
2704
2705 if (getLexer().is(AsmToken::Comma)) {
2706 Lex();
2707
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002708 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002709 return TokError("Expected an identifier");
2710
2711 if (Name == ".eh_frame")
2712 EH = true;
2713 else if (Name == ".debug_frame")
2714 Debug = true;
2715 }
2716
2717 getStreamer().EmitCFISections(EH, Debug);
2718 return false;
2719}
2720
2721/// ParseDirectiveCFIStartProc
2722/// ::= .cfi_startproc
2723bool AsmParser::ParseDirectiveCFIStartProc() {
2724 getStreamer().EmitCFIStartProc();
2725 return false;
2726}
2727
2728/// ParseDirectiveCFIEndProc
2729/// ::= .cfi_endproc
2730bool AsmParser::ParseDirectiveCFIEndProc() {
2731 getStreamer().EmitCFIEndProc();
2732 return false;
2733}
2734
2735/// ParseRegisterOrRegisterNumber - parse register name or number.
2736bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2737 SMLoc DirectiveLoc) {
2738 unsigned RegNo;
2739
2740 if (getLexer().isNot(AsmToken::Integer)) {
2741 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2742 return true;
Bill Wendling99cb6222013-06-18 07:20:20 +00002743 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky6ee13082013-01-15 22:59:42 +00002744 } else
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002745 return parseAbsoluteExpression(Register);
Eli Bendersky6ee13082013-01-15 22:59:42 +00002746
2747 return false;
2748}
2749
2750/// ParseDirectiveCFIDefCfa
2751/// ::= .cfi_def_cfa register, offset
2752bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2753 int64_t Register = 0;
2754 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2755 return true;
2756
2757 if (getLexer().isNot(AsmToken::Comma))
2758 return TokError("unexpected token in directive");
2759 Lex();
2760
2761 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002762 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002763 return true;
2764
2765 getStreamer().EmitCFIDefCfa(Register, Offset);
2766 return false;
2767}
2768
2769/// ParseDirectiveCFIDefCfaOffset
2770/// ::= .cfi_def_cfa_offset offset
2771bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
2772 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002773 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002774 return true;
2775
2776 getStreamer().EmitCFIDefCfaOffset(Offset);
2777 return false;
2778}
2779
2780/// ParseDirectiveCFIRegister
2781/// ::= .cfi_register register, register
2782bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2783 int64_t Register1 = 0;
2784 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2785 return true;
2786
2787 if (getLexer().isNot(AsmToken::Comma))
2788 return TokError("unexpected token in directive");
2789 Lex();
2790
2791 int64_t Register2 = 0;
2792 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2793 return true;
2794
2795 getStreamer().EmitCFIRegister(Register1, Register2);
2796 return false;
2797}
2798
2799/// ParseDirectiveCFIAdjustCfaOffset
2800/// ::= .cfi_adjust_cfa_offset adjustment
2801bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
2802 int64_t Adjustment = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002803 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002804 return true;
2805
2806 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2807 return false;
2808}
2809
2810/// ParseDirectiveCFIDefCfaRegister
2811/// ::= .cfi_def_cfa_register register
2812bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2813 int64_t Register = 0;
2814 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2815 return true;
2816
2817 getStreamer().EmitCFIDefCfaRegister(Register);
2818 return false;
2819}
2820
2821/// ParseDirectiveCFIOffset
2822/// ::= .cfi_offset register, offset
2823bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2824 int64_t Register = 0;
2825 int64_t Offset = 0;
2826
2827 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2828 return true;
2829
2830 if (getLexer().isNot(AsmToken::Comma))
2831 return TokError("unexpected token in directive");
2832 Lex();
2833
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002834 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002835 return true;
2836
2837 getStreamer().EmitCFIOffset(Register, Offset);
2838 return false;
2839}
2840
2841/// ParseDirectiveCFIRelOffset
2842/// ::= .cfi_rel_offset register, offset
2843bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2844 int64_t Register = 0;
2845
2846 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2847 return true;
2848
2849 if (getLexer().isNot(AsmToken::Comma))
2850 return TokError("unexpected token in directive");
2851 Lex();
2852
2853 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002854 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002855 return true;
2856
2857 getStreamer().EmitCFIRelOffset(Register, Offset);
2858 return false;
2859}
2860
2861static bool isValidEncoding(int64_t Encoding) {
2862 if (Encoding & ~0xff)
2863 return false;
2864
2865 if (Encoding == dwarf::DW_EH_PE_omit)
2866 return true;
2867
2868 const unsigned Format = Encoding & 0xf;
2869 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2870 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2871 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2872 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2873 return false;
2874
2875 const unsigned Application = Encoding & 0x70;
2876 if (Application != dwarf::DW_EH_PE_absptr &&
2877 Application != dwarf::DW_EH_PE_pcrel)
2878 return false;
2879
2880 return true;
2881}
2882
2883/// ParseDirectiveCFIPersonalityOrLsda
2884/// IsPersonality true for cfi_personality, false for cfi_lsda
2885/// ::= .cfi_personality encoding, [symbol_name]
2886/// ::= .cfi_lsda encoding, [symbol_name]
2887bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2888 int64_t Encoding = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002889 if (parseAbsoluteExpression(Encoding))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002890 return true;
2891 if (Encoding == dwarf::DW_EH_PE_omit)
2892 return false;
2893
2894 if (!isValidEncoding(Encoding))
2895 return TokError("unsupported encoding.");
2896
2897 if (getLexer().isNot(AsmToken::Comma))
2898 return TokError("unexpected token in directive");
2899 Lex();
2900
2901 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002902 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002903 return TokError("expected identifier in directive");
2904
2905 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2906
2907 if (IsPersonality)
2908 getStreamer().EmitCFIPersonality(Sym, Encoding);
2909 else
2910 getStreamer().EmitCFILsda(Sym, Encoding);
2911 return false;
2912}
2913
2914/// ParseDirectiveCFIRememberState
2915/// ::= .cfi_remember_state
2916bool AsmParser::ParseDirectiveCFIRememberState() {
2917 getStreamer().EmitCFIRememberState();
2918 return false;
2919}
2920
2921/// ParseDirectiveCFIRestoreState
2922/// ::= .cfi_remember_state
2923bool AsmParser::ParseDirectiveCFIRestoreState() {
2924 getStreamer().EmitCFIRestoreState();
2925 return false;
2926}
2927
2928/// ParseDirectiveCFISameValue
2929/// ::= .cfi_same_value register
2930bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2931 int64_t Register = 0;
2932
2933 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2934 return true;
2935
2936 getStreamer().EmitCFISameValue(Register);
2937 return false;
2938}
2939
2940/// ParseDirectiveCFIRestore
2941/// ::= .cfi_restore register
2942bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2943 int64_t Register = 0;
2944 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2945 return true;
2946
2947 getStreamer().EmitCFIRestore(Register);
2948 return false;
2949}
2950
2951/// ParseDirectiveCFIEscape
2952/// ::= .cfi_escape expression[,...]
2953bool AsmParser::ParseDirectiveCFIEscape() {
2954 std::string Values;
2955 int64_t CurrValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002956 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002957 return true;
2958
2959 Values.push_back((uint8_t)CurrValue);
2960
2961 while (getLexer().is(AsmToken::Comma)) {
2962 Lex();
2963
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002964 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002965 return true;
2966
2967 Values.push_back((uint8_t)CurrValue);
2968 }
2969
2970 getStreamer().EmitCFIEscape(Values);
2971 return false;
2972}
2973
2974/// ParseDirectiveCFISignalFrame
2975/// ::= .cfi_signal_frame
2976bool AsmParser::ParseDirectiveCFISignalFrame() {
2977 if (getLexer().isNot(AsmToken::EndOfStatement))
2978 return Error(getLexer().getLoc(),
2979 "unexpected token in '.cfi_signal_frame'");
2980
2981 getStreamer().EmitCFISignalFrame();
2982 return false;
2983}
2984
2985/// ParseDirectiveCFIUndefined
2986/// ::= .cfi_undefined register
2987bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
2988 int64_t Register = 0;
2989
2990 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2991 return true;
2992
2993 getStreamer().EmitCFIUndefined(Register);
2994 return false;
2995}
2996
2997/// ParseDirectiveMacrosOnOff
2998/// ::= .macros_on
2999/// ::= .macros_off
3000bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
3001 if (getLexer().isNot(AsmToken::EndOfStatement))
3002 return Error(getLexer().getLoc(),
3003 "unexpected token in '" + Directive + "' directive");
3004
3005 SetMacrosEnabled(Directive == ".macros_on");
3006 return false;
3007}
3008
3009/// ParseDirectiveMacro
3010/// ::= .macro name [parameters]
3011bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
3012 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003013 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003014 return TokError("expected identifier in '.macro' directive");
3015
3016 MCAsmMacroParameters Parameters;
3017 // Argument delimiter is initially unknown. It will be set by
3018 // ParseMacroArgument()
3019 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3020 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3021 for (;;) {
3022 MCAsmMacroParameter Parameter;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003023 if (parseIdentifier(Parameter.first))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003024 return TokError("expected identifier in '.macro' directive");
3025
3026 if (getLexer().is(AsmToken::Equal)) {
3027 Lex();
3028 if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3029 return true;
3030 }
3031
3032 Parameters.push_back(Parameter);
3033
3034 if (getLexer().is(AsmToken::Comma))
3035 Lex();
3036 else if (getLexer().is(AsmToken::EndOfStatement))
3037 break;
3038 }
3039 }
3040
3041 // Eat the end of statement.
3042 Lex();
3043
3044 AsmToken EndToken, StartToken = getTok();
3045
3046 // Lex the macro definition.
3047 for (;;) {
3048 // Check whether we have reached the end of the file.
3049 if (getLexer().is(AsmToken::Eof))
3050 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3051
3052 // Otherwise, check whether we have reach the .endmacro.
3053 if (getLexer().is(AsmToken::Identifier) &&
3054 (getTok().getIdentifier() == ".endm" ||
3055 getTok().getIdentifier() == ".endmacro")) {
3056 EndToken = getTok();
3057 Lex();
3058 if (getLexer().isNot(AsmToken::EndOfStatement))
3059 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3060 "' directive");
3061 break;
3062 }
3063
3064 // Otherwise, scan til the end of the statement.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003065 eatToEndOfStatement();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003066 }
3067
3068 if (LookupMacro(Name)) {
3069 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3070 }
3071
3072 const char *BodyStart = StartToken.getLoc().getPointer();
3073 const char *BodyEnd = EndToken.getLoc().getPointer();
3074 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Kevin Enderby221514e2013-01-22 21:44:53 +00003075 CheckForBadMacro(DirectiveLoc, Name, Body, Parameters);
Eli Bendersky6ee13082013-01-15 22:59:42 +00003076 DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3077 return false;
3078}
3079
Kevin Enderby221514e2013-01-22 21:44:53 +00003080/// CheckForBadMacro
3081///
3082/// With the support added for named parameters there may be code out there that
3083/// is transitioning from positional parameters. In versions of gas that did
3084/// not support named parameters they would be ignored on the macro defintion.
3085/// But to support both styles of parameters this is not possible so if a macro
3086/// defintion has named parameters but does not use them and has what appears
3087/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3088/// warning that the positional parameter found in body which have no effect.
3089/// Hoping the developer will either remove the named parameters from the macro
3090/// definiton so the positional parameters get used if that was what was
3091/// intended or change the macro to use the named parameters. It is possible
3092/// this warning will trigger when the none of the named parameters are used
3093/// and the strings like $1 are infact to simply to be passed trough unchanged.
3094void AsmParser::CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3095 StringRef Body,
3096 MCAsmMacroParameters Parameters) {
3097 // If this macro is not defined with named parameters the warning we are
3098 // checking for here doesn't apply.
3099 unsigned NParameters = Parameters.size();
3100 if (NParameters == 0)
3101 return;
3102
3103 bool NamedParametersFound = false;
3104 bool PositionalParametersFound = false;
3105
3106 // Look at the body of the macro for use of both the named parameters and what
3107 // are likely to be positional parameters. This is what expandMacro() is
3108 // doing when it finds the parameters in the body.
3109 while (!Body.empty()) {
3110 // Scan for the next possible parameter.
3111 std::size_t End = Body.size(), Pos = 0;
3112 for (; Pos != End; ++Pos) {
3113 // Check for a substitution or escape.
3114 // This macro is defined with parameters, look for \foo, \bar, etc.
3115 if (Body[Pos] == '\\' && Pos + 1 != End)
3116 break;
3117
3118 // This macro should have parameters, but look for $0, $1, ..., $n too.
3119 if (Body[Pos] != '$' || Pos + 1 == End)
3120 continue;
3121 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00003122 if (Next == '$' || Next == 'n' ||
3123 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby221514e2013-01-22 21:44:53 +00003124 break;
3125 }
3126
3127 // Check if we reached the end.
3128 if (Pos == End)
3129 break;
3130
3131 if (Body[Pos] == '$') {
3132 switch (Body[Pos+1]) {
3133 // $$ => $
3134 case '$':
3135 break;
3136
3137 // $n => number of arguments
3138 case 'n':
3139 PositionalParametersFound = true;
3140 break;
3141
3142 // $[0-9] => argument
3143 default: {
3144 PositionalParametersFound = true;
3145 break;
3146 }
3147 }
3148 Pos += 2;
3149 } else {
3150 unsigned I = Pos + 1;
3151 while (isIdentifierChar(Body[I]) && I + 1 != End)
3152 ++I;
3153
3154 const char *Begin = Body.data() + Pos +1;
3155 StringRef Argument(Begin, I - (Pos +1));
3156 unsigned Index = 0;
3157 for (; Index < NParameters; ++Index)
3158 if (Parameters[Index].first == Argument)
3159 break;
3160
3161 if (Index == NParameters) {
3162 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
3163 Pos += 3;
3164 else {
3165 Pos = I;
3166 }
3167 } else {
3168 NamedParametersFound = true;
3169 Pos += 1 + Argument.size();
3170 }
3171 }
3172 // Update the scan point.
3173 Body = Body.substr(Pos);
3174 }
3175
3176 if (!NamedParametersFound && PositionalParametersFound)
3177 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3178 "used in macro body, possible positional parameter "
3179 "found in body which will have no effect");
3180}
3181
Eli Bendersky6ee13082013-01-15 22:59:42 +00003182/// ParseDirectiveEndMacro
3183/// ::= .endm
3184/// ::= .endmacro
3185bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
3186 if (getLexer().isNot(AsmToken::EndOfStatement))
3187 return TokError("unexpected token in '" + Directive + "' directive");
3188
3189 // If we are inside a macro instantiation, terminate the current
3190 // instantiation.
3191 if (InsideMacroInstantiation()) {
3192 HandleMacroExit();
3193 return false;
3194 }
3195
3196 // Otherwise, this .endmacro is a stray entry in the file; well formed
3197 // .endmacro directives are handled during the macro definition parsing.
3198 return TokError("unexpected '" + Directive + "' in file, "
3199 "no current macro definition");
3200}
3201
3202/// ParseDirectivePurgeMacro
3203/// ::= .purgem
3204bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3205 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003206 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003207 return TokError("expected identifier in '.purgem' directive");
3208
3209 if (getLexer().isNot(AsmToken::EndOfStatement))
3210 return TokError("unexpected token in '.purgem' directive");
3211
3212 if (!LookupMacro(Name))
3213 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3214
3215 UndefineMacro(Name);
3216 return false;
3217}
Eli Bendersky4766ef42012-12-20 19:05:53 +00003218
3219/// ParseDirectiveBundleAlignMode
3220/// ::= {.bundle_align_mode} expression
3221bool AsmParser::ParseDirectiveBundleAlignMode() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003222 checkForValidSection();
Eli Bendersky4766ef42012-12-20 19:05:53 +00003223
3224 // Expect a single argument: an expression that evaluates to a constant
3225 // in the inclusive range 0-30.
3226 SMLoc ExprLoc = getLexer().getLoc();
3227 int64_t AlignSizePow2;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003228 if (parseAbsoluteExpression(AlignSizePow2))
Eli Bendersky4766ef42012-12-20 19:05:53 +00003229 return true;
3230 else if (getLexer().isNot(AsmToken::EndOfStatement))
3231 return TokError("unexpected token after expression in"
3232 " '.bundle_align_mode' directive");
3233 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3234 return Error(ExprLoc,
3235 "invalid bundle alignment size (expected between 0 and 30)");
3236
3237 Lex();
3238
3239 // Because of AlignSizePow2's verified range we can safely truncate it to
3240 // unsigned.
3241 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3242 return false;
3243}
3244
3245/// ParseDirectiveBundleLock
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003246/// ::= {.bundle_lock} [align_to_end]
Eli Bendersky4766ef42012-12-20 19:05:53 +00003247bool AsmParser::ParseDirectiveBundleLock() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003248 checkForValidSection();
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003249 bool AlignToEnd = false;
Eli Bendersky4766ef42012-12-20 19:05:53 +00003250
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003251 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3252 StringRef Option;
3253 SMLoc Loc = getTok().getLoc();
3254 const char *kInvalidOptionError =
3255 "invalid option for '.bundle_lock' directive";
3256
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003257 if (parseIdentifier(Option))
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003258 return Error(Loc, kInvalidOptionError);
3259
3260 if (Option != "align_to_end")
3261 return Error(Loc, kInvalidOptionError);
3262 else if (getLexer().isNot(AsmToken::EndOfStatement))
3263 return Error(Loc,
3264 "unexpected token after '.bundle_lock' directive option");
3265 AlignToEnd = true;
3266 }
3267
Eli Bendersky4766ef42012-12-20 19:05:53 +00003268 Lex();
3269
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003270 getStreamer().EmitBundleLock(AlignToEnd);
Eli Bendersky4766ef42012-12-20 19:05:53 +00003271 return false;
3272}
3273
3274/// ParseDirectiveBundleLock
3275/// ::= {.bundle_lock}
3276bool AsmParser::ParseDirectiveBundleUnlock() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003277 checkForValidSection();
Eli Bendersky4766ef42012-12-20 19:05:53 +00003278
3279 if (getLexer().isNot(AsmToken::EndOfStatement))
3280 return TokError("unexpected token in '.bundle_unlock' directive");
3281 Lex();
3282
3283 getStreamer().EmitBundleUnlock();
3284 return false;
3285}
3286
Eli Bendersky6ee13082013-01-15 22:59:42 +00003287/// ParseDirectiveSpace
3288/// ::= (.skip | .space) expression [ , expression ]
3289bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003290 checkForValidSection();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003291
3292 int64_t NumBytes;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003293 if (parseAbsoluteExpression(NumBytes))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003294 return true;
3295
3296 int64_t FillExpr = 0;
3297 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3298 if (getLexer().isNot(AsmToken::Comma))
3299 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3300 Lex();
3301
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003302 if (parseAbsoluteExpression(FillExpr))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003303 return true;
3304
3305 if (getLexer().isNot(AsmToken::EndOfStatement))
3306 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3307 }
3308
3309 Lex();
3310
3311 if (NumBytes <= 0)
3312 return TokError("invalid number of bytes in '" +
3313 Twine(IDVal) + "' directive");
3314
3315 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3316 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
3317
3318 return false;
3319}
3320
3321/// ParseDirectiveLEB128
3322/// ::= (.sleb128 | .uleb128) expression
3323bool AsmParser::ParseDirectiveLEB128(bool Signed) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003324 checkForValidSection();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003325 const MCExpr *Value;
3326
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003327 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003328 return true;
3329
3330 if (getLexer().isNot(AsmToken::EndOfStatement))
3331 return TokError("unexpected token in directive");
3332
3333 if (Signed)
3334 getStreamer().EmitSLEB128Value(Value);
3335 else
3336 getStreamer().EmitULEB128Value(Value);
3337
3338 return false;
3339}
3340
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003341/// ParseDirectiveSymbolAttribute
3342/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00003343bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003344 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003345 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003346 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00003347 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003348
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003349 if (parseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00003350 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003351
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003352 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003353
Jim Grosbach10ec6502011-09-15 17:56:49 +00003354 // Assembler local symbols don't make any sense here. Complain loudly.
3355 if (Sym->isTemporary())
3356 return Error(Loc, "non-local symbol required in directive");
3357
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003358 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003359
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003360 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003361 break;
3362
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003363 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003364 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003365 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003366 }
3367 }
3368
Sean Callanan79ed1a82010-01-19 20:22:31 +00003369 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00003370 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003371}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003372
3373/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00003374/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3375bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003376 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00003377
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003378 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003379 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003380 if (parseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003381 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003382
Daniel Dunbar76c4d762009-07-31 21:55:09 +00003383 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003384 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003385
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003386 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003387 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003388 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003389
3390 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003391 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003392 if (parseAbsoluteExpression(Size))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003393 return true;
3394
3395 int64_t Pow2Alignment = 0;
3396 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003397 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00003398 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003399 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003400 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003401 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003402
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003403 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3404 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00003405 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3406
Chris Lattner258281d2010-01-19 06:22:22 +00003407 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003408 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3409 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00003410 if (!isPowerOf2_64(Pow2Alignment))
3411 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3412 Pow2Alignment = Log2_64(Pow2Alignment);
3413 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003414 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003415
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003416 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00003417 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003418
Sean Callanan79ed1a82010-01-19 20:22:31 +00003419 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003420
Chris Lattner1fc3d752009-07-09 17:25:12 +00003421 // NOTE: a size of zero for a .comm should create a undefined symbol
3422 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003423 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003424 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3425 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003426
Eric Christopherc260a3e2010-05-14 01:38:54 +00003427 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003428 // may internally end up wanting an alignment in bytes.
3429 // FIXME: Diagnose overflow.
3430 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003431 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3432 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003433
Daniel Dunbar8906ff12009-08-22 07:22:36 +00003434 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003435 return Error(IDLoc, "invalid symbol redefinition");
3436
Chris Lattner1fc3d752009-07-09 17:25:12 +00003437 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003438 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00003439 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003440 return false;
3441 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003442
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003443 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003444 return false;
3445}
Chris Lattner9be3fee2009-07-10 22:20:30 +00003446
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003447/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003448/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003449bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003450 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003451 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003452
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003453 StringRef Str = parseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003454 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003455 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003456
Sean Callanan79ed1a82010-01-19 20:22:31 +00003457 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003458
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003459 if (Str.empty())
3460 Error(Loc, ".abort detected. Assembly stopping.");
3461 else
3462 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003463 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003464
3465 return false;
3466}
Kevin Enderby71148242009-07-14 21:35:03 +00003467
Kevin Enderby1f049b22009-07-14 23:21:55 +00003468/// ParseDirectiveInclude
3469/// ::= .include "filename"
3470bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003471 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003472 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003473
Sean Callanan18b83232010-01-19 21:44:56 +00003474 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003475 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00003476 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00003477
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003478 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003479 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003480
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003481 // Strip the quotes.
3482 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003483
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003484 // Attempt to switch the lexer to the included file before consuming the end
3485 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00003486 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00003487 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003488 return true;
3489 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00003490
3491 return false;
3492}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00003493
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003494/// ParseDirectiveIncbin
3495/// ::= .incbin "filename"
3496bool AsmParser::ParseDirectiveIncbin() {
3497 if (getLexer().isNot(AsmToken::String))
3498 return TokError("expected string in '.incbin' directive");
3499
3500 std::string Filename = getTok().getString();
3501 SMLoc IncbinLoc = getLexer().getLoc();
3502 Lex();
3503
3504 if (getLexer().isNot(AsmToken::EndOfStatement))
3505 return TokError("unexpected token in '.incbin' directive");
3506
3507 // Strip the quotes.
3508 Filename = Filename.substr(1, Filename.size()-2);
3509
3510 // Attempt to process the included file.
3511 if (ProcessIncbinFile(Filename)) {
3512 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3513 return true;
3514 }
3515
3516 return false;
3517}
3518
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003519/// ParseDirectiveIf
3520/// ::= .if expression
3521bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003522 TheCondStack.push_back(TheCondState);
3523 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00003524 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003525 eatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00003526 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003527 int64_t ExprValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003528 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003529 return true;
3530
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003531 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003532 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003533
Sean Callanan79ed1a82010-01-19 20:22:31 +00003534 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003535
3536 TheCondState.CondMet = ExprValue;
3537 TheCondState.Ignore = !TheCondState.CondMet;
3538 }
3539
3540 return false;
3541}
3542
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003543/// ParseDirectiveIfb
3544/// ::= .ifb string
3545bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3546 TheCondStack.push_back(TheCondState);
3547 TheCondState.TheCond = AsmCond::IfCond;
3548
Benjamin Kramer29739e72012-05-12 16:52:21 +00003549 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003550 eatToEndOfStatement();
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003551 } else {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003552 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003553
3554 if (getLexer().isNot(AsmToken::EndOfStatement))
3555 return TokError("unexpected token in '.ifb' directive");
3556
3557 Lex();
3558
3559 TheCondState.CondMet = ExpectBlank == Str.empty();
3560 TheCondState.Ignore = !TheCondState.CondMet;
3561 }
3562
3563 return false;
3564}
3565
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003566/// ParseDirectiveIfc
3567/// ::= .ifc string1, string2
3568bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3569 TheCondStack.push_back(TheCondState);
3570 TheCondState.TheCond = AsmCond::IfCond;
3571
Benjamin Kramer29739e72012-05-12 16:52:21 +00003572 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003573 eatToEndOfStatement();
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003574 } else {
3575 StringRef Str1 = ParseStringToComma();
3576
3577 if (getLexer().isNot(AsmToken::Comma))
3578 return TokError("unexpected token in '.ifc' directive");
3579
3580 Lex();
3581
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003582 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003583
3584 if (getLexer().isNot(AsmToken::EndOfStatement))
3585 return TokError("unexpected token in '.ifc' directive");
3586
3587 Lex();
3588
3589 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3590 TheCondState.Ignore = !TheCondState.CondMet;
3591 }
3592
3593 return false;
3594}
3595
3596/// ParseDirectiveIfdef
3597/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003598bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3599 StringRef Name;
3600 TheCondStack.push_back(TheCondState);
3601 TheCondState.TheCond = AsmCond::IfCond;
3602
3603 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003604 eatToEndOfStatement();
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003605 } else {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003606 if (parseIdentifier(Name))
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003607 return TokError("expected identifier after '.ifdef'");
3608
3609 Lex();
3610
3611 MCSymbol *Sym = getContext().LookupSymbol(Name);
3612
3613 if (expect_defined)
3614 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3615 else
3616 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3617 TheCondState.Ignore = !TheCondState.CondMet;
3618 }
3619
3620 return false;
3621}
3622
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003623/// ParseDirectiveElseIf
3624/// ::= .elseif expression
3625bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
3626 if (TheCondState.TheCond != AsmCond::IfCond &&
3627 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper955d1e92013-04-22 04:24:02 +00003628 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3629 " an .elseif");
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003630 TheCondState.TheCond = AsmCond::ElseIfCond;
3631
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003632 bool LastIgnoreState = false;
3633 if (!TheCondStack.empty())
Craig Topper955d1e92013-04-22 04:24:02 +00003634 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003635 if (LastIgnoreState || TheCondState.CondMet) {
3636 TheCondState.Ignore = true;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003637 eatToEndOfStatement();
Craig Topperefa703d2013-04-22 04:22:40 +00003638 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003639 int64_t ExprValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003640 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003641 return true;
3642
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003643 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003644 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003645
Sean Callanan79ed1a82010-01-19 20:22:31 +00003646 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003647 TheCondState.CondMet = ExprValue;
3648 TheCondState.Ignore = !TheCondState.CondMet;
3649 }
3650
3651 return false;
3652}
3653
3654/// ParseDirectiveElse
3655/// ::= .else
3656bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003657 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003658 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003659
Sean Callanan79ed1a82010-01-19 20:22:31 +00003660 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003661
3662 if (TheCondState.TheCond != AsmCond::IfCond &&
3663 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper955d1e92013-04-22 04:24:02 +00003664 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3665 ".elseif");
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003666 TheCondState.TheCond = AsmCond::ElseCond;
3667 bool LastIgnoreState = false;
3668 if (!TheCondStack.empty())
3669 LastIgnoreState = TheCondStack.back().Ignore;
3670 if (LastIgnoreState || TheCondState.CondMet)
3671 TheCondState.Ignore = true;
3672 else
3673 TheCondState.Ignore = false;
3674
3675 return false;
3676}
3677
3678/// ParseDirectiveEndIf
3679/// ::= .endif
3680bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003681 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003682 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003683
Sean Callanan79ed1a82010-01-19 20:22:31 +00003684 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003685
3686 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3687 TheCondStack.empty())
3688 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3689 ".else");
3690 if (!TheCondStack.empty()) {
3691 TheCondState = TheCondStack.back();
3692 TheCondStack.pop_back();
3693 }
3694
3695 return false;
3696}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003697
Eli Bendersky6ee13082013-01-15 22:59:42 +00003698void AsmParser::initializeDirectiveKindMap() {
3699 DirectiveKindMap[".set"] = DK_SET;
3700 DirectiveKindMap[".equ"] = DK_EQU;
3701 DirectiveKindMap[".equiv"] = DK_EQUIV;
3702 DirectiveKindMap[".ascii"] = DK_ASCII;
3703 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3704 DirectiveKindMap[".string"] = DK_STRING;
3705 DirectiveKindMap[".byte"] = DK_BYTE;
3706 DirectiveKindMap[".short"] = DK_SHORT;
3707 DirectiveKindMap[".value"] = DK_VALUE;
3708 DirectiveKindMap[".2byte"] = DK_2BYTE;
3709 DirectiveKindMap[".long"] = DK_LONG;
3710 DirectiveKindMap[".int"] = DK_INT;
3711 DirectiveKindMap[".4byte"] = DK_4BYTE;
3712 DirectiveKindMap[".quad"] = DK_QUAD;
3713 DirectiveKindMap[".8byte"] = DK_8BYTE;
3714 DirectiveKindMap[".single"] = DK_SINGLE;
3715 DirectiveKindMap[".float"] = DK_FLOAT;
3716 DirectiveKindMap[".double"] = DK_DOUBLE;
3717 DirectiveKindMap[".align"] = DK_ALIGN;
3718 DirectiveKindMap[".align32"] = DK_ALIGN32;
3719 DirectiveKindMap[".balign"] = DK_BALIGN;
3720 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3721 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3722 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3723 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3724 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3725 DirectiveKindMap[".org"] = DK_ORG;
3726 DirectiveKindMap[".fill"] = DK_FILL;
3727 DirectiveKindMap[".zero"] = DK_ZERO;
3728 DirectiveKindMap[".extern"] = DK_EXTERN;
3729 DirectiveKindMap[".globl"] = DK_GLOBL;
3730 DirectiveKindMap[".global"] = DK_GLOBAL;
3731 DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
3732 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3733 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3734 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3735 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3736 DirectiveKindMap[".reference"] = DK_REFERENCE;
3737 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3738 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3739 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3740 DirectiveKindMap[".comm"] = DK_COMM;
3741 DirectiveKindMap[".common"] = DK_COMMON;
3742 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3743 DirectiveKindMap[".abort"] = DK_ABORT;
3744 DirectiveKindMap[".include"] = DK_INCLUDE;
3745 DirectiveKindMap[".incbin"] = DK_INCBIN;
3746 DirectiveKindMap[".code16"] = DK_CODE16;
3747 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3748 DirectiveKindMap[".rept"] = DK_REPT;
3749 DirectiveKindMap[".irp"] = DK_IRP;
3750 DirectiveKindMap[".irpc"] = DK_IRPC;
3751 DirectiveKindMap[".endr"] = DK_ENDR;
3752 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3753 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3754 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3755 DirectiveKindMap[".if"] = DK_IF;
3756 DirectiveKindMap[".ifb"] = DK_IFB;
3757 DirectiveKindMap[".ifnb"] = DK_IFNB;
3758 DirectiveKindMap[".ifc"] = DK_IFC;
3759 DirectiveKindMap[".ifnc"] = DK_IFNC;
3760 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3761 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3762 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3763 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3764 DirectiveKindMap[".else"] = DK_ELSE;
3765 DirectiveKindMap[".endif"] = DK_ENDIF;
3766 DirectiveKindMap[".skip"] = DK_SKIP;
3767 DirectiveKindMap[".space"] = DK_SPACE;
3768 DirectiveKindMap[".file"] = DK_FILE;
3769 DirectiveKindMap[".line"] = DK_LINE;
3770 DirectiveKindMap[".loc"] = DK_LOC;
3771 DirectiveKindMap[".stabs"] = DK_STABS;
3772 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3773 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3774 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3775 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3776 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3777 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3778 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3779 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3780 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3781 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3782 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3783 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3784 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3785 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3786 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3787 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3788 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3789 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3790 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3791 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3792 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3793 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3794 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3795 DirectiveKindMap[".macro"] = DK_MACRO;
3796 DirectiveKindMap[".endm"] = DK_ENDM;
3797 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3798 DirectiveKindMap[".purgem"] = DK_PURGEM;
Eli Bendersky5d0f0612013-01-10 22:44:57 +00003799}
3800
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003801
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003802MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003803 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003804
Rafael Espindola761cb062012-06-03 23:57:14 +00003805 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003806 for (;;) {
3807 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003808 if (getLexer().is(AsmToken::Eof)) {
3809 Error(DirectiveLoc, "no matching '.endr' in definition");
3810 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003811 }
3812
Rafael Espindola761cb062012-06-03 23:57:14 +00003813 if (Lexer.is(AsmToken::Identifier) &&
3814 (getTok().getIdentifier() == ".rept")) {
3815 ++NestLevel;
3816 }
3817
3818 // Otherwise, check whether we have reached the .endr.
3819 if (Lexer.is(AsmToken::Identifier) &&
3820 getTok().getIdentifier() == ".endr") {
3821 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003822 EndToken = getTok();
3823 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003824 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3825 TokError("unexpected token in '.endr' directive");
3826 return 0;
3827 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003828 break;
3829 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003830 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003831 }
3832
Rafael Espindola761cb062012-06-03 23:57:14 +00003833 // Otherwise, scan till the end of the statement.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003834 eatToEndOfStatement();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003835 }
3836
3837 const char *BodyStart = StartToken.getLoc().getPointer();
3838 const char *BodyEnd = EndToken.getLoc().getPointer();
3839 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3840
Rafael Espindola761cb062012-06-03 23:57:14 +00003841 // We Are Anonymous.
3842 StringRef Name;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003843 MCAsmMacroParameters Parameters;
3844 return new MCAsmMacro(Name, Body, Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +00003845}
3846
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003847void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +00003848 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003849 OS << ".endr\n";
3850
3851 MemoryBuffer *Instantiation =
3852 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3853
Rafael Espindola761cb062012-06-03 23:57:14 +00003854 // Create the macro instantiation object and add to the current macro
3855 // instantiation stack.
3856 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003857 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003858 getTok().getLoc(),
3859 Instantiation);
3860 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003861
Rafael Espindola761cb062012-06-03 23:57:14 +00003862 // Jump to the macro instantiation and prime the lexer.
3863 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3864 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3865 Lex();
3866}
3867
3868bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3869 int64_t Count;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003870 if (parseAbsoluteExpression(Count))
Rafael Espindola761cb062012-06-03 23:57:14 +00003871 return TokError("unexpected token in '.rept' directive");
3872
3873 if (Count < 0)
3874 return TokError("Count is negative");
3875
3876 if (Lexer.isNot(AsmToken::EndOfStatement))
3877 return TokError("unexpected token in '.rept' directive");
3878
3879 // Eat the end of statement.
3880 Lex();
3881
3882 // Lex the rept definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003883 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindola761cb062012-06-03 23:57:14 +00003884 if (!M)
3885 return true;
3886
3887 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3888 // to hold the macro body with substitutions.
3889 SmallString<256> Buf;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003890 MCAsmMacroParameters Parameters;
3891 MCAsmMacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003892 raw_svector_ostream OS(Buf);
3893 while (Count--) {
3894 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3895 return true;
3896 }
3897 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003898
3899 return false;
3900}
3901
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003902/// ParseDirectiveIrp
3903/// ::= .irp symbol,values
3904bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003905 MCAsmMacroParameters Parameters;
3906 MCAsmMacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003907
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003908 if (parseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003909 return TokError("expected identifier in '.irp' directive");
3910
3911 Parameters.push_back(Parameter);
3912
3913 if (Lexer.isNot(AsmToken::Comma))
3914 return TokError("expected comma in '.irp' directive");
3915
3916 Lex();
3917
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003918 MCAsmMacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003919 if (ParseMacroArguments(0, A))
3920 return true;
3921
3922 // Eat the end of statement.
3923 Lex();
3924
3925 // Lex the irp definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003926 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003927 if (!M)
3928 return true;
3929
3930 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3931 // to hold the macro body with substitutions.
3932 SmallString<256> Buf;
3933 raw_svector_ostream OS(Buf);
3934
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003935 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3936 MCAsmMacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003937 Args.push_back(*i);
3938
3939 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3940 return true;
3941 }
3942
3943 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3944
3945 return false;
3946}
3947
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003948/// ParseDirectiveIrpc
3949/// ::= .irpc symbol,values
3950bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003951 MCAsmMacroParameters Parameters;
3952 MCAsmMacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003953
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003954 if (parseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003955 return TokError("expected identifier in '.irpc' directive");
3956
3957 Parameters.push_back(Parameter);
3958
3959 if (Lexer.isNot(AsmToken::Comma))
3960 return TokError("expected comma in '.irpc' directive");
3961
3962 Lex();
3963
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003964 MCAsmMacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003965 if (ParseMacroArguments(0, A))
3966 return true;
3967
3968 if (A.size() != 1 || A.front().size() != 1)
3969 return TokError("unexpected token in '.irpc' directive");
3970
3971 // Eat the end of statement.
3972 Lex();
3973
3974 // Lex the irpc definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003975 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003976 if (!M)
3977 return true;
3978
3979 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3980 // to hold the macro body with substitutions.
3981 SmallString<256> Buf;
3982 raw_svector_ostream OS(Buf);
3983
3984 StringRef Values = A.front().front().getString();
3985 std::size_t I, End = Values.size();
3986 for (I = 0; I < End; ++I) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00003987 MCAsmMacroArgument Arg;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003988 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3989
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003990 MCAsmMacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003991 Args.push_back(Arg);
3992
3993 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3994 return true;
3995 }
3996
3997 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3998
3999 return false;
4000}
4001
Rafael Espindola761cb062012-06-03 23:57:14 +00004002bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
4003 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00004004 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004005
4006 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00004007 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004008 assert(getLexer().is(AsmToken::EndOfStatement));
4009
Rafael Espindola761cb062012-06-03 23:57:14 +00004010 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004011 return false;
4012}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00004013
Benjamin Kramer75234372013-02-15 20:37:21 +00004014bool AsmParser::ParseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4015 size_t Len) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004016 const MCExpr *Value;
4017 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004018 if (parseExpression(Value))
Eli Friedman2128aae2012-10-22 23:58:19 +00004019 return true;
4020 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4021 if (!MCE)
4022 return Error(ExprLoc, "unexpected expression in _emit");
4023 uint64_t IntValue = MCE->getValue();
4024 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4025 return Error(ExprLoc, "literal value out of range for directive");
4026
Chad Rosier469b1442013-02-12 21:33:51 +00004027 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4028 return false;
4029}
4030
4031bool AsmParser::ParseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4032 const MCExpr *Value;
4033 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004034 if (parseExpression(Value))
Chad Rosier469b1442013-02-12 21:33:51 +00004035 return true;
4036 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4037 if (!MCE)
4038 return Error(ExprLoc, "unexpected expression in align");
4039 uint64_t IntValue = MCE->getValue();
4040 if (!isPowerOf2_64(IntValue))
4041 return Error(ExprLoc, "literal value not a power of two greater then zero");
4042
Benjamin Kramer75234372013-02-15 20:37:21 +00004043 Info.AsmRewrites->push_back(AsmRewrite(AOK_Align, IDLoc, 5,
4044 Log2_64(IntValue)));
Eli Friedman2128aae2012-10-22 23:58:19 +00004045 return false;
4046}
4047
Chad Rosier19aa3e32013-02-13 21:27:17 +00004048// We are comparing pointers, but the pointers are relative to a single string.
4049// Thus, this should always be deterministic.
Benjamin Kramer75234372013-02-15 20:37:21 +00004050static int RewritesSort(const void *A, const void *B) {
4051 const AsmRewrite *AsmRewriteA = static_cast<const AsmRewrite *>(A);
4052 const AsmRewrite *AsmRewriteB = static_cast<const AsmRewrite *>(B);
Chad Rosierabde6752013-02-13 18:38:58 +00004053 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4054 return -1;
4055 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4056 return 1;
Chad Rosierb54562b2013-02-15 22:54:16 +00004057
Chad Rosier6b369ce2013-04-08 17:43:47 +00004058 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4059 // rewrite to the same location. Make sure the SizeDirective rewrite is
4060 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4061 // ensures the sort algorithm is stable.
4062 if (AsmRewritePrecedence [AsmRewriteA->Kind] >
4063 AsmRewritePrecedence [AsmRewriteB->Kind])
Chad Rosierb54562b2013-02-15 22:54:16 +00004064 return -1;
Chad Rosier6b369ce2013-04-08 17:43:47 +00004065
4066 if (AsmRewritePrecedence [AsmRewriteA->Kind] <
4067 AsmRewritePrecedence [AsmRewriteB->Kind])
Chad Rosierb54562b2013-02-15 22:54:16 +00004068 return 1;
Chad Rosierb54562b2013-02-15 22:54:16 +00004069 llvm_unreachable ("Unstable rewrite sort.");
Chad Rosierb1953982013-02-13 01:03:13 +00004070}
4071
Benjamin Kramer75234372013-02-15 20:37:21 +00004072bool
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004073AsmParser::parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Benjamin Kramer75234372013-02-15 20:37:21 +00004074 unsigned &NumOutputs, unsigned &NumInputs,
4075 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4076 SmallVectorImpl<std::string> &Constraints,
4077 SmallVectorImpl<std::string> &Clobbers,
4078 const MCInstrInfo *MII,
4079 const MCInstPrinter *IP,
4080 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004081 SmallVector<void *, 4> InputDecls;
4082 SmallVector<void *, 4> OutputDecls;
Chad Rosierc1ec2072013-01-10 22:10:27 +00004083 SmallVector<bool, 4> InputDeclsAddressOf;
4084 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004085 SmallVector<std::string, 4> InputConstraints;
4086 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer75234372013-02-15 20:37:21 +00004087 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004088
Benjamin Kramer75234372013-02-15 20:37:21 +00004089 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004090
4091 // Prime the lexer.
4092 Lex();
4093
4094 // While we have input, parse each statement.
4095 unsigned InputIdx = 0;
4096 unsigned OutputIdx = 0;
4097 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004098 ParseStatementInfo Info(&AsmStrRewrites);
4099 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00004100 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004101
Chad Rosier57498012012-12-12 22:45:52 +00004102 if (Info.ParseError)
4103 return true;
4104
Benjamin Kramer75234372013-02-15 20:37:21 +00004105 if (Info.Opcode == ~0U)
4106 continue;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004107
Benjamin Kramer75234372013-02-15 20:37:21 +00004108 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004109
Benjamin Kramer75234372013-02-15 20:37:21 +00004110 // Build the list of clobbers, outputs and inputs.
4111 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4112 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004113
Benjamin Kramer75234372013-02-15 20:37:21 +00004114 // Immediate.
Chad Rosier811ddf62013-03-19 21:58:18 +00004115 if (Operand->isImm())
Benjamin Kramer75234372013-02-15 20:37:21 +00004116 continue;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004117
Benjamin Kramer75234372013-02-15 20:37:21 +00004118 // Register operand.
4119 if (Operand->isReg() && !Operand->needAddressOf()) {
4120 unsigned NumDefs = Desc.getNumDefs();
4121 // Clobber.
4122 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4123 ClobberRegs.push_back(Operand->getReg());
4124 continue;
4125 }
4126
4127 // Expr/Input or Output.
Chad Rosierb976e402013-04-09 17:53:49 +00004128 StringRef SymName = Operand->getSymName();
4129 if (SymName.empty())
4130 continue;
4131
Chad Rosier087c3092013-04-22 22:12:12 +00004132 void *OpDecl = Operand->getOpDecl();
Benjamin Kramer75234372013-02-15 20:37:21 +00004133 if (!OpDecl)
4134 continue;
4135
4136 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierb976e402013-04-09 17:53:49 +00004137 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer75234372013-02-15 20:37:21 +00004138 if (isOutput) {
4139 ++InputIdx;
4140 OutputDecls.push_back(OpDecl);
4141 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4142 OutputConstraints.push_back('=' + Operand->getConstraint().str());
Chad Rosierb976e402013-04-09 17:53:49 +00004143 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
Benjamin Kramer75234372013-02-15 20:37:21 +00004144 } else {
4145 InputDecls.push_back(OpDecl);
4146 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4147 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosierb976e402013-04-09 17:53:49 +00004148 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00004149 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004150 }
4151 }
4152
4153 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004154 NumOutputs = OutputDecls.size();
4155 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00004156
4157 // Set the unique clobbers.
Benjamin Kramer75234372013-02-15 20:37:21 +00004158 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4159 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4160 ClobberRegs.end());
4161 Clobbers.assign(ClobberRegs.size(), std::string());
4162 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4163 raw_string_ostream OS(Clobbers[I]);
4164 IP->printRegName(OS, ClobberRegs[I]);
4165 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004166
4167 // Merge the various outputs and inputs. Output are expected first.
4168 if (NumOutputs || NumInputs) {
4169 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004170 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004171 Constraints.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004172 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004173 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004174 Constraints[i] = OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004175 }
4176 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004177 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004178 Constraints[j] = InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004179 }
4180 }
4181
4182 // Build the IR assembly string.
4183 std::string AsmStringIR;
4184 raw_string_ostream OS(AsmStringIR);
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004185 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4186 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
Benjamin Kramer75234372013-02-15 20:37:21 +00004187 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), RewritesSort);
4188 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4189 E = AsmStrRewrites.end();
4190 I != E; ++I) {
Chad Rosierdda4b6b2013-04-12 16:26:42 +00004191 AsmRewriteKind Kind = (*I).Kind;
4192 if (Kind == AOK_Delete)
4193 continue;
4194
Chad Rosierb1f8c132012-10-18 15:49:34 +00004195 const char *Loc = (*I).Loc.getPointer();
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004196 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier96d58e62012-10-19 20:57:14 +00004197
Chad Rosier023c8802013-03-19 17:32:17 +00004198 // Emit everything up to the immediate/expression.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004199 unsigned Len = Loc - AsmStart;
Chad Rosierf06cc982013-04-11 21:49:30 +00004200 if (Len)
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004201 OS << StringRef(AsmStart, Len);
Chad Rosier96d58e62012-10-19 20:57:14 +00004202
Chad Rosier5a719fc2012-10-23 17:43:43 +00004203 // Skip the original expression.
4204 if (Kind == AOK_Skip) {
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004205 AsmStart = Loc + (*I).Len;
Chad Rosier5a719fc2012-10-23 17:43:43 +00004206 continue;
4207 }
4208
Chad Rosierdda4b6b2013-04-12 16:26:42 +00004209 unsigned AdditionalSkip = 0;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004210 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00004211 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004212 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004213 case AOK_Imm:
Benjamin Kramer75234372013-02-15 20:37:21 +00004214 OS << "$$" << (*I).Val;
Chad Rosierefcb3d92012-10-26 18:04:20 +00004215 break;
4216 case AOK_ImmPrefix:
Benjamin Kramer75234372013-02-15 20:37:21 +00004217 OS << "$$";
Chad Rosierb1f8c132012-10-18 15:49:34 +00004218 break;
4219 case AOK_Input:
Benjamin Kramer75234372013-02-15 20:37:21 +00004220 OS << '$' << InputIdx++;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004221 break;
4222 case AOK_Output:
Benjamin Kramer75234372013-02-15 20:37:21 +00004223 OS << '$' << OutputIdx++;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004224 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00004225 case AOK_SizeDirective:
Benjamin Kramer75234372013-02-15 20:37:21 +00004226 switch ((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00004227 default: break;
4228 case 8: OS << "byte ptr "; break;
4229 case 16: OS << "word ptr "; break;
4230 case 32: OS << "dword ptr "; break;
4231 case 64: OS << "qword ptr "; break;
4232 case 80: OS << "xword ptr "; break;
4233 case 128: OS << "xmmword ptr "; break;
4234 case 256: OS << "ymmword ptr "; break;
4235 }
Eli Friedman2128aae2012-10-22 23:58:19 +00004236 break;
4237 case AOK_Emit:
4238 OS << ".byte";
4239 break;
Chad Rosier469b1442013-02-12 21:33:51 +00004240 case AOK_Align: {
4241 unsigned Val = (*I).Val;
4242 OS << ".align " << Val;
4243
4244 // Skip the original immediate.
Benjamin Kramer75234372013-02-15 20:37:21 +00004245 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosier469b1442013-02-12 21:33:51 +00004246 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4247 break;
4248 }
Chad Rosier6a020a72012-10-25 20:41:34 +00004249 case AOK_DotOperator:
4250 OS << (*I).Val;
4251 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004252 }
Chad Rosier96d58e62012-10-19 20:57:14 +00004253
Chad Rosierb1f8c132012-10-18 15:49:34 +00004254 // Skip the original expression.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004255 AsmStart = Loc + (*I).Len + AdditionalSkip;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004256 }
4257
4258 // Emit the remainder of the asm string.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004259 if (AsmStart != AsmEnd)
4260 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004261
4262 AsmString = OS.str();
4263 return false;
4264}
4265
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004266/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004267MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004268 MCContext &C, MCStreamer &Out,
4269 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004270 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004271}