blob: 804734cea9396614897a6baa404f267c15ba8945 [file] [log] [blame]
Chris Lattner27aa7d22009-06-21 20:16:42 +00001//===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This class implements the parser for assembly files.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbarb95a0792010-09-24 01:59:56 +000014#include "llvm/ADT/APFloat.h"
Daniel Dunbar7c0a3342009-08-26 22:49:51 +000015#include "llvm/ADT/SmallString.h"
Chad Rosierabde6752013-02-13 18:38:58 +000016#include "llvm/ADT/STLExtras.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000017#include "llvm/ADT/StringMap.h"
Daniel Dunbarf9507ff2009-07-27 23:20:52 +000018#include "llvm/ADT/Twine.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000019#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000020#include "llvm/MC/MCContext.h"
Evan Cheng94b95502011-07-26 00:24:13 +000021#include "llvm/MC/MCDwarf.h"
Daniel Dunbar28c251b2009-08-31 08:06:59 +000022#include "llvm/MC/MCExpr.h"
Chad Rosierb1f8c132012-10-18 15:49:34 +000023#include "llvm/MC/MCInstPrinter.h"
24#include "llvm/MC/MCInstrInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000025#include "llvm/MC/MCParser/AsmCond.h"
26#include "llvm/MC/MCParser/AsmLexer.h"
27#include "llvm/MC/MCParser/MCAsmParser.h"
28#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Evan Chenge76a33b2011-07-20 05:58:47 +000029#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000030#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000031#include "llvm/MC/MCStreamer.h"
Daniel Dunbardce0f3c2009-06-29 23:43:14 +000032#include "llvm/MC/MCSymbol.h"
Evan Cheng94b95502011-07-26 00:24:13 +000033#include "llvm/MC/MCTargetAsmParser.h"
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000034#include "llvm/Support/CommandLine.h"
Benjamin Kramer518ff562012-01-28 15:28:41 +000035#include "llvm/Support/ErrorHandling.h"
Jim Grosbach254cf032011-06-29 16:05:14 +000036#include "llvm/Support/MathExtras.h"
Kevin Enderbyf187ac52010-06-28 21:45:58 +000037#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000038#include "llvm/Support/SourceMgr.h"
Chris Lattnerb0789ed2009-06-21 20:54:55 +000039#include "llvm/Support/raw_ostream.h"
Nick Lewycky476b2422010-12-19 20:43:38 +000040#include <cctype>
Chad Rosierb1f8c132012-10-18 15:49:34 +000041#include <set>
42#include <string>
Daniel Dunbaraef87e32010-07-18 18:31:38 +000043#include <vector>
Chris Lattner27aa7d22009-06-21 20:16:42 +000044using namespace llvm;
45
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000046static cl::opt<bool>
47FatalAssemblerWarnings("fatal-assembler-warnings",
48 cl::desc("Consider warnings as error"));
49
Eric Christopher2318ba12012-12-18 00:30:54 +000050MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
Nick Lewycky0d7d11d2012-10-19 07:00:09 +000051
Daniel Dunbar81ea00f2010-07-12 17:54:38 +000052namespace {
53
Eli Benderskyf9f40bd2013-01-16 18:56:50 +000054/// \brief Helper types for tracking macro definitions.
55typedef std::vector<AsmToken> MCAsmMacroArgument;
56typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
57typedef std::pair<StringRef, MCAsmMacroArgument> MCAsmMacroParameter;
58typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
59
60struct MCAsmMacro {
61 StringRef Name;
62 StringRef Body;
63 MCAsmMacroParameters Parameters;
64
65public:
66 MCAsmMacro(StringRef N, StringRef B, const MCAsmMacroParameters &P) :
67 Name(N), Body(B), Parameters(P) {}
68
69 MCAsmMacro(const MCAsmMacro& Other)
70 : Name(Other.Name), Body(Other.Body), Parameters(Other.Parameters) {}
71};
72
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000073/// \brief Helper class for storing information about an active macro
74/// instantiation.
75struct MacroInstantiation {
76 /// The macro being instantiated.
Eli Benderskyc0c67b02013-01-14 23:22:36 +000077 const MCAsmMacro *TheMacro;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000078
79 /// The macro instantiation with substitutions.
80 MemoryBuffer *Instantiation;
81
82 /// The location of the instantiation.
83 SMLoc InstantiationLoc;
84
Daniel Dunbar4259a1a2012-12-01 01:38:48 +000085 /// The buffer where parsing should resume upon instantiation completion.
86 int ExitBuffer;
87
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000088 /// The location where parsing should resume upon instantiation completion.
89 SMLoc ExitLoc;
90
91public:
Eli Benderskyc0c67b02013-01-14 23:22:36 +000092 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000093 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000094};
95
Eli Friedman2128aae2012-10-22 23:58:19 +000096struct ParseStatementInfo {
97 /// ParsedOperands - The parsed operands from the last parsed statement.
98 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
99
100 /// Opcode - The opcode from the last parsed instruction.
101 unsigned Opcode;
102
Chad Rosier57498012012-12-12 22:45:52 +0000103 /// Error - Was there an error parsing the inline assembly?
104 bool ParseError;
105
Eli Friedman2128aae2012-10-22 23:58:19 +0000106 SmallVectorImpl<AsmRewrite> *AsmRewrites;
107
Chad Rosier57498012012-12-12 22:45:52 +0000108 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
Eli Friedman2128aae2012-10-22 23:58:19 +0000109 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier57498012012-12-12 22:45:52 +0000110 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman2128aae2012-10-22 23:58:19 +0000111
112 ~ParseStatementInfo() {
113 // Free any parsed operands.
114 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
115 delete ParsedOperands[i];
116 ParsedOperands.clear();
117 }
118};
119
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000120/// \brief The concrete assembly parser instance.
121class AsmParser : public MCAsmParser {
Craig Topper85aadc02012-09-15 16:23:52 +0000122 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
123 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000124private:
125 AsmLexer Lexer;
126 MCContext &Ctx;
127 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000128 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000129 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +0000130 SourceMgr::DiagHandlerTy SavedDiagHandler;
131 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000132 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000133
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000134 /// This is the current buffer index we're lexing from as managed by the
135 /// SourceMgr object.
136 int CurBuffer;
137
138 AsmCond TheCondState;
139 std::vector<AsmCond> TheCondStack;
140
Eli Bendersky6ee13082013-01-15 22:59:42 +0000141 /// ExtensionDirectiveMap - maps directive names to handler methods in parser
142 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000143 /// addDirectiveHandler.
Eli Bendersky6ee13082013-01-15 22:59:42 +0000144 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000145
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000146 /// MacroMap - Map of currently defined macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000147 StringMap<MCAsmMacro*> MacroMap;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000148
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000149 /// ActiveMacros - Stack of active macro instantiations.
150 std::vector<MacroInstantiation*> ActiveMacros;
151
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000152 /// Boolean tracking whether macro substitution is enabled.
Eli Bendersky733c3362013-01-14 18:08:41 +0000153 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000154
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000155 /// Flag tracking whether any errors have been encountered.
156 unsigned HadError : 1;
157
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000158 /// The values from the last parsed cpp hash file line comment if any.
159 StringRef CppHashFilename;
160 int64_t CppHashLineNumber;
161 SMLoc CppHashLoc;
Kevin Enderby32c1a822012-11-05 21:55:41 +0000162 int CppHashBuf;
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000163
Devang Patel0db58bf2012-01-31 18:14:05 +0000164 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
165 unsigned AssemblerDialect;
166
Preston Gurd7b6f2032012-09-19 20:36:12 +0000167 /// IsDarwin - is Darwin compatibility enabled?
168 bool IsDarwin;
169
Chad Rosier8f138d12012-10-15 17:19:13 +0000170 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000171 bool ParsingInlineAsm;
172
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000173public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000174 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000175 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000176 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000177
178 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
179
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000180 virtual void addDirectiveHandler(StringRef Directive,
Eli Bendersky171192f2013-01-16 00:50:52 +0000181 ExtensionDirectiveHandler Handler) {
182 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000183 }
184
185public:
186 /// @name MCAsmParser Interface
187 /// {
188
189 virtual SourceMgr &getSourceManager() { return SrcMgr; }
190 virtual MCAsmLexer &getLexer() { return Lexer; }
191 virtual MCContext &getContext() { return Ctx; }
192 virtual MCStreamer &getStreamer() { return Out; }
Eric Christopher2318ba12012-12-18 00:30:54 +0000193 virtual unsigned getAssemblerDialect() {
Devang Patel0db58bf2012-01-31 18:14:05 +0000194 if (AssemblerDialect == ~0U)
Eric Christopher2318ba12012-12-18 00:30:54 +0000195 return MAI.getAssemblerDialect();
Devang Patel0db58bf2012-01-31 18:14:05 +0000196 else
197 return AssemblerDialect;
198 }
199 virtual void setAssemblerDialect(unsigned i) {
200 AssemblerDialect = i;
201 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000202
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000203 virtual bool Warning(SMLoc L, const Twine &Msg,
204 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
205 virtual bool Error(SMLoc L, const Twine &Msg,
206 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000207
Craig Topper345d16d2012-08-29 05:48:09 +0000208 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000209
Chad Rosier84125ca2012-10-13 00:26:04 +0000210 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosierc5ac87d2012-10-16 20:16:20 +0000211 bool isParsingInlineAsm() { return ParsingInlineAsm; }
Chad Rosierb1f8c132012-10-18 15:49:34 +0000212
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000213 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000214 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +0000215 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000216 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000217 SmallVectorImpl<std::string> &Clobbers,
218 const MCInstrInfo *MII,
219 const MCInstPrinter *IP,
220 MCAsmParserSemaCallback &SI);
Chad Rosier84125ca2012-10-13 00:26:04 +0000221
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000222 bool parseExpression(const MCExpr *&Res);
223 virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc);
224 virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
225 virtual bool parseAbsoluteExpression(int64_t &Res);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000226
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000227 /// parseIdentifier - Parse an identifier or string (as a quoted identifier)
Eli Benderskybf706b32013-01-12 00:05:00 +0000228 /// and set \p Res to the identifier contents.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000229 virtual bool parseIdentifier(StringRef &Res);
230 virtual void eatToEndOfStatement();
Eli Benderskybf706b32013-01-12 00:05:00 +0000231
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000232 virtual void checkForValidSection();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000233 /// }
234
235private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000236
Eli Friedman2128aae2012-10-22 23:58:19 +0000237 bool ParseStatement(ParseStatementInfo &Info);
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000238 void EatToEndOfLine();
239 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000240
Kevin Enderby221514e2013-01-22 21:44:53 +0000241 void CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
242 MCAsmMacroParameters Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +0000243 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000244 const MCAsmMacroParameters &Parameters,
245 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000246 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000247
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000248 /// \brief Are macros enabled in the parser?
249 bool MacrosEnabled() {return MacrosEnabledFlag;}
250
251 /// \brief Control a flag in the parser that enables or disables macros.
252 void SetMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
253
254 /// \brief Lookup a previously defined macro.
255 /// \param Name Macro name.
256 /// \returns Pointer to macro. NULL if no such macro was defined.
257 const MCAsmMacro* LookupMacro(StringRef Name);
258
259 /// \brief Define a new macro with the given name and information.
260 void DefineMacro(StringRef Name, const MCAsmMacro& Macro);
261
262 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
263 void UndefineMacro(StringRef Name);
264
265 /// \brief Are we inside a macro instantiation?
266 bool InsideMacroInstantiation() {return !ActiveMacros.empty();}
267
268 /// \brief Handle entry to macro instantiation.
269 ///
270 /// \param M The macro.
271 /// \param NameLoc Instantiation location.
272 bool HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
273
274 /// \brief Handle exit from macro instantiation.
275 void HandleMacroExit();
276
277 /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
278 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
279 /// correct delimiter by the method.
280 bool ParseMacroArgument(MCAsmMacroArgument &MA,
281 AsmToken::TokenKind &ArgumentDelimiter);
282
283 /// \brief Parse all macro arguments for a given macro.
284 bool ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
285
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000286 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000287 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000288 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
289 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000290 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000291 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000292
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000293 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
294 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000295 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
296 /// This returns true on failure.
297 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000298
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000299 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000300 /// current token is not set; clients should ensure Lex() is called
301 /// subsequently.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000302 ///
303 /// \param InBuffer If not -1, should be the known buffer id that contains the
304 /// location.
305 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000306
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000307 /// \brief Parse up to the end of statement and a return the contents from the
308 /// current token until the end of the statement; the current token on exit
309 /// will be either the EndOfStatement or EOF.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000310 virtual StringRef parseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000311
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000312 /// \brief Parse until the end of a statement or a comma is encountered,
313 /// return the contents from the current token up to the end or comma.
314 StringRef ParseStringToComma();
315
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000316 bool ParseAssignment(StringRef Name, bool allow_redef,
317 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000318
319 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
320 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
321 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000322 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000323
Eli Bendersky6ee13082013-01-15 22:59:42 +0000324 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola787c3372010-10-28 20:02:27 +0000325
Eli Bendersky6ee13082013-01-15 22:59:42 +0000326 // Generic (target and platform independent) directive parsing.
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000327 enum DirectiveKind {
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000328 DK_NO_DIRECTIVE, // Placeholder
329 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
330 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
331 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky9b1bb052013-01-11 22:55:28 +0000332 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000333 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
334 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
335 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
336 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
337 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
338 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
339 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
Eli Bendersky6ee13082013-01-15 22:59:42 +0000340 DK_ELSEIF, DK_ELSE, DK_ENDIF,
341 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
342 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
343 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
344 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
345 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
346 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
347 DK_CFI_REGISTER,
348 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
349 DK_SLEB128, DK_ULEB128
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000350 };
351
Eli Bendersky6ee13082013-01-15 22:59:42 +0000352 /// DirectiveKindMap - Maps directive name --> DirectiveKind enum, for
353 /// directives parsed by this class.
354 StringMap<DirectiveKind> DirectiveKindMap;
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000355
356 // ".ascii", ".asciz", ".string"
Rafael Espindola787c3372010-10-28 20:02:27 +0000357 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000358 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000359 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000360 bool ParseDirectiveFill(); // ".fill"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000361 bool ParseDirectiveZero(); // ".zero"
Eric Christopher2318ba12012-12-18 00:30:54 +0000362 // ".set", ".equ", ".equiv"
363 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000364 bool ParseDirectiveOrg(); // ".org"
365 // ".align{,32}", ".p2align{,w,l}"
366 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
367
Eli Bendersky6ee13082013-01-15 22:59:42 +0000368 // ".file", ".line", ".loc", ".stabs"
369 bool ParseDirectiveFile(SMLoc DirectiveLoc);
370 bool ParseDirectiveLine();
371 bool ParseDirectiveLoc();
372 bool ParseDirectiveStabs();
373
374 // .cfi directives
375 bool ParseDirectiveCFIRegister(SMLoc DirectiveLoc);
376 bool ParseDirectiveCFISections();
377 bool ParseDirectiveCFIStartProc();
378 bool ParseDirectiveCFIEndProc();
379 bool ParseDirectiveCFIDefCfaOffset();
380 bool ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
381 bool ParseDirectiveCFIAdjustCfaOffset();
382 bool ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
383 bool ParseDirectiveCFIOffset(SMLoc DirectiveLoc);
384 bool ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
385 bool ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
386 bool ParseDirectiveCFIRememberState();
387 bool ParseDirectiveCFIRestoreState();
388 bool ParseDirectiveCFISameValue(SMLoc DirectiveLoc);
389 bool ParseDirectiveCFIRestore(SMLoc DirectiveLoc);
390 bool ParseDirectiveCFIEscape();
391 bool ParseDirectiveCFISignalFrame();
392 bool ParseDirectiveCFIUndefined(SMLoc DirectiveLoc);
393
394 // macro directives
395 bool ParseDirectivePurgeMacro(SMLoc DirectiveLoc);
396 bool ParseDirectiveEndMacro(StringRef Directive);
397 bool ParseDirectiveMacro(SMLoc DirectiveLoc);
398 bool ParseDirectiveMacrosOnOff(StringRef Directive);
399
Eli Bendersky4766ef42012-12-20 19:05:53 +0000400 // ".bundle_align_mode"
401 bool ParseDirectiveBundleAlignMode();
402 // ".bundle_lock"
403 bool ParseDirectiveBundleLock();
404 // ".bundle_unlock"
405 bool ParseDirectiveBundleUnlock();
406
Eli Bendersky6ee13082013-01-15 22:59:42 +0000407 // ".space", ".skip"
408 bool ParseDirectiveSpace(StringRef IDVal);
409
410 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
411 bool ParseDirectiveLEB128(bool Signed);
412
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000413 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
414 /// accepts a single symbol (which should be a label or an external).
415 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000416
417 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
418
419 bool ParseDirectiveAbort(); // ".abort"
420 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000421 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000422
423 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000424 // ".ifb" or ".ifnb", depending on ExpectBlank.
425 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000426 // ".ifc" or ".ifnc", depending on ExpectEqual.
427 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000428 // ".ifdef" or ".ifndef", depending on expect_defined
429 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000430 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
431 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
432 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000433 virtual bool parseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000434
435 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
436 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000437
Rafael Espindola761cb062012-06-03 23:57:14 +0000438 // Macro-like directives
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000439 MCAsmMacro *ParseMacroLikeBody(SMLoc DirectiveLoc);
440 void InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +0000441 raw_svector_ostream &OS);
442 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000443 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000444 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000445 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000446
Chad Rosier469b1442013-02-12 21:33:51 +0000447 // "_emit" or "__emit"
448 bool ParseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
449 size_t Len);
450
451 // "align"
452 bool ParseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000453
Eli Bendersky6ee13082013-01-15 22:59:42 +0000454 void initializeDirectiveKindMap();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000455};
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000456}
457
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000458namespace llvm {
459
460extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000461extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000462extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000463
464}
465
Chris Lattneraaec2052010-01-19 19:46:13 +0000466enum { DEFAULT_ADDRSPACE = 0 };
467
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000468AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000469 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000470 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Eli Bendersky6ee13082013-01-15 22:59:42 +0000471 PlatformParser(0),
Eli Bendersky733c3362013-01-14 18:08:41 +0000472 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000473 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000474 // Save the old handler.
475 SavedDiagHandler = SrcMgr.getDiagHandler();
476 SavedDiagContext = SrcMgr.getDiagContext();
477 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000478 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000479 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000480
Daniel Dunbare4749702010-07-12 18:12:02 +0000481 // Initialize the platform / file format parser.
482 //
483 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
484 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000485 if (_MAI.hasMicrosoftFastStdCallMangling()) {
486 PlatformParser = createCOFFAsmParser();
487 PlatformParser->Initialize(*this);
488 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000489 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000490 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000491 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000492 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000493 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000494 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000495 }
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000496
Eli Bendersky6ee13082013-01-15 22:59:42 +0000497 initializeDirectiveKindMap();
Chris Lattnerebb89b42009-09-27 21:16:52 +0000498}
499
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000500AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000501 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
502
503 // Destroy any macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000504 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
Daniel Dunbar56491302010-07-29 01:51:55 +0000505 ie = MacroMap.end(); it != ie; ++it)
506 delete it->getValue();
507
Daniel Dunbare4749702010-07-12 18:12:02 +0000508 delete PlatformParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000509}
510
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000511void AsmParser::PrintMacroInstantiations() {
512 // Print the active macro instantiation stack.
513 for (std::vector<MacroInstantiation*>::const_reverse_iterator
514 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000515 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
516 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000517}
518
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000519bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000520 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000521 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000522 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000523 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000524 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000525}
526
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000527bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000528 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000529 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000530 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000531 return true;
532}
533
Sean Callananfd0b0282010-01-21 00:19:58 +0000534bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000535 std::string IncludedFile;
536 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000537 if (NewBuf == -1)
538 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000539
Sean Callananfd0b0282010-01-21 00:19:58 +0000540 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000541
Sean Callananfd0b0282010-01-21 00:19:58 +0000542 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000543
Sean Callananfd0b0282010-01-21 00:19:58 +0000544 return false;
545}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000546
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000547/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000548/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000549/// returns true on failure.
550bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
551 std::string IncludedFile;
552 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
553 if (NewBuf == -1)
554 return true;
555
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000556 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000557 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
558 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000559 return false;
560}
561
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000562void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
563 if (InBuffer != -1) {
564 CurBuffer = InBuffer;
565 } else {
566 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
567 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000568 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
569}
570
Sean Callananfd0b0282010-01-21 00:19:58 +0000571const AsmToken &AsmParser::Lex() {
572 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000573
Sean Callananfd0b0282010-01-21 00:19:58 +0000574 if (tok->is(AsmToken::Eof)) {
575 // If this is the end of an included file, pop the parent file off the
576 // include stack.
577 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
578 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000579 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000580 tok = &Lexer.Lex();
581 }
582 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000583
Sean Callananfd0b0282010-01-21 00:19:58 +0000584 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000585 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000586
Sean Callananfd0b0282010-01-21 00:19:58 +0000587 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000588}
589
Chris Lattner79180e22010-04-05 23:15:42 +0000590bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000591 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000592 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000593 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000594
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000595 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000596 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000597
598 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000599 AsmCond StartingCondState = TheCondState;
600
Kevin Enderby613b7572011-11-01 22:27:22 +0000601 // If we are generating dwarf for assembly source files save the initial text
602 // section and generate a .file directive.
603 if (getContext().getGenDwarfForAssembly()) {
604 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000605 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
606 getStreamer().EmitLabel(SectionStartSym);
607 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000608 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
Eric Christopher6c583142012-12-18 00:31:01 +0000609 StringRef(),
610 getContext().getMainFileName());
Kevin Enderby613b7572011-11-01 22:27:22 +0000611 }
612
Chris Lattnerb717fb02009-07-02 21:53:43 +0000613 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000614 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000615 ParseStatementInfo Info;
616 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000617
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000618 // We had an error, validate that one was emitted and recover by skipping to
619 // the next line.
620 assert(HadError && "Parse statement returned an error, but none emitted!");
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000621 eatToEndOfStatement();
Chris Lattnerb717fb02009-07-02 21:53:43 +0000622 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000623
624 if (TheCondState.TheCond != StartingCondState.TheCond ||
625 TheCondState.Ignore != StartingCondState.Ignore)
626 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000627
628 // Check to see there are no empty DwarfFile slots.
Manman Ren9e999ad2013-03-12 20:17:00 +0000629 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000630 getContext().getMCDwarfFiles();
631 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000632 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000633 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000634 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000635
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000636 // Check to see that all assembler local symbols were actually defined.
637 // Targets that don't do subsections via symbols may not want this, though,
638 // so conservatively exclude them. Only do this if we're finalizing, though,
639 // as otherwise we won't necessarilly have seen everything yet.
640 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
641 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
642 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
643 e = Symbols.end();
644 i != e; ++i) {
645 MCSymbol *Sym = i->getValue();
646 // Variable symbols may not be marked as defined, so check those
647 // explicitly. If we know it's a variable, we have a definition for
648 // the purposes of this check.
649 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
650 // FIXME: We would really like to refer back to where the symbol was
651 // first referenced for a source location. We need to add something
652 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000653 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
654 "assembler local symbol '" + Sym->getName() +
655 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000656 }
657 }
658
659
Chris Lattner79180e22010-04-05 23:15:42 +0000660 // Finalize the output stream if there are no errors and if the client wants
661 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000662 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000663 Out.Finish();
664
Chris Lattnerb717fb02009-07-02 21:53:43 +0000665 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000666}
667
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000668void AsmParser::checkForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000669 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000670 TokError("expected section directive before assembly directive");
Eli Bendersky030f63a2013-01-14 19:04:57 +0000671 Out.InitToTextSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000672 }
673}
674
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000675/// eatToEndOfStatement - Throw away the rest of the line for testing purposes.
676void AsmParser::eatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000677 while (Lexer.isNot(AsmToken::EndOfStatement) &&
678 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000679 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000680
Chris Lattner2cf5f142009-06-22 01:29:09 +0000681 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000682 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000683 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000684}
685
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000686StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000687 const char *Start = getTok().getLoc().getPointer();
688
689 while (Lexer.isNot(AsmToken::EndOfStatement) &&
690 Lexer.isNot(AsmToken::Eof))
691 Lex();
692
693 const char *End = getTok().getLoc().getPointer();
694 return StringRef(Start, End - Start);
695}
Chris Lattnerc4193832009-06-22 05:51:26 +0000696
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000697StringRef AsmParser::ParseStringToComma() {
698 const char *Start = getTok().getLoc().getPointer();
699
700 while (Lexer.isNot(AsmToken::EndOfStatement) &&
701 Lexer.isNot(AsmToken::Comma) &&
702 Lexer.isNot(AsmToken::Eof))
703 Lex();
704
705 const char *End = getTok().getLoc().getPointer();
706 return StringRef(Start, End - Start);
707}
708
Chris Lattner74ec1a32009-06-22 06:32:03 +0000709/// ParseParenExpr - Parse a paren expression and return it.
710/// NOTE: This assumes the leading '(' has already been consumed.
711///
712/// parenexpr ::= expr)
713///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000714bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000715 if (parseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000716 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000717 return TokError("expected ')' in parentheses expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000718 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000719 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000720 return false;
721}
Chris Lattnerc4193832009-06-22 05:51:26 +0000722
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000723/// ParseBracketExpr - Parse a bracket expression and return it.
724/// NOTE: This assumes the leading '[' has already been consumed.
725///
726/// bracketexpr ::= expr]
727///
728bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000729 if (parseExpression(Res)) return true;
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000730 if (Lexer.isNot(AsmToken::RBrac))
731 return TokError("expected ']' in brackets expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000732 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000733 Lex();
734 return false;
735}
736
Chris Lattner74ec1a32009-06-22 06:32:03 +0000737/// ParsePrimaryExpr - Parse a primary expression and return it.
738/// primaryexpr ::= (parenexpr
739/// primaryexpr ::= symbol
740/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000741/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000742/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000743bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby5de048e2013-01-22 21:09:20 +0000744 SMLoc FirstTokenLoc = getLexer().getLoc();
745 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
746 switch (FirstTokenKind) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000747 default:
748 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000749 // If we have an error assume that we've already handled it.
750 case AsmToken::Error:
751 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000752 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000753 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000754 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000755 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000756 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000757 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000758 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000759 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000760 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000761 StringRef Identifier;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000762 if (parseIdentifier(Identifier)) {
Kevin Enderby5de048e2013-01-22 21:09:20 +0000763 if (FirstTokenKind == AsmToken::Dollar)
764 return Error(FirstTokenLoc, "invalid token in expression");
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000765 return true;
Kevin Enderby5de048e2013-01-22 21:09:20 +0000766 }
Daniel Dunbare17edff2010-08-24 19:13:42 +0000767
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000768 EndLoc = SMLoc::getFromPointer(Identifier.end());
769
Daniel Dunbarfffff912009-10-16 01:34:54 +0000770 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000771 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000772 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000773
774 // Lookup the symbol variant if used.
775 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000776 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000777 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000778 if (Variant == MCSymbolRefExpr::VK_Invalid) {
779 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000780 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000781 }
782 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000783
Daniel Dunbarfffff912009-10-16 01:34:54 +0000784 // If this is an absolute variable reference, substitute it now to preserve
785 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000786 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000787 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000788 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000789
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000790 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000791 return false;
792 }
793
794 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000795 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000796 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000797 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000798 case AsmToken::Integer: {
799 SMLoc Loc = getTok().getLoc();
800 int64_t IntVal = getTok().getIntVal();
801 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000802 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000803 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000804 // Look for 'b' or 'f' following an Integer as a directional label
805 if (Lexer.getKind() == AsmToken::Identifier) {
806 StringRef IDVal = getTok().getString();
807 if (IDVal == "f" || IDVal == "b"){
808 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
809 IDVal == "f" ? 1 : 0);
810 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
811 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000812 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000813 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000814 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000815 Lex(); // Eat identifier.
816 }
817 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000818 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000819 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000820 case AsmToken::Real: {
821 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000822 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000823 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000824 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000825 Lex(); // Eat token.
826 return false;
827 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000828 case AsmToken::Dot: {
829 // This is a '.' reference, which references the current PC. Emit a
830 // temporary label to the streamer and refer to it.
831 MCSymbol *Sym = Ctx.CreateTempSymbol();
832 Out.EmitLabel(Sym);
833 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000834 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattnerd3050352010-04-14 04:40:28 +0000835 Lex(); // Eat identifier.
836 return false;
837 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000838 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000839 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000840 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000841 case AsmToken::LBrac:
842 if (!PlatformParser->HasBracketExpressions())
843 return TokError("brackets expression not supported on this target");
844 Lex(); // Eat the '['.
845 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000846 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000847 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000848 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000849 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000850 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000851 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000852 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000853 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000854 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000855 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000856 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000857 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000858 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000859 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000860 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000861 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000862 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000863 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000864 }
865}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000866
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000867bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000868 SMLoc EndLoc;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000869 return parseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000870}
871
Daniel Dunbarcceba832010-09-17 02:47:07 +0000872const MCExpr *
873AsmParser::ApplyModifierToExpr(const MCExpr *E,
874 MCSymbolRefExpr::VariantKind Variant) {
875 // Recurse over the given expression, rebuilding it to apply the given variant
876 // if there is exactly one symbol.
877 switch (E->getKind()) {
878 case MCExpr::Target:
879 case MCExpr::Constant:
880 return 0;
881
882 case MCExpr::SymbolRef: {
883 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
884
885 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
886 TokError("invalid variant on expression '" +
887 getTok().getIdentifier() + "' (already modified)");
888 return E;
889 }
890
891 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
892 }
893
894 case MCExpr::Unary: {
895 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
896 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
897 if (!Sub)
898 return 0;
899 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
900 }
901
902 case MCExpr::Binary: {
903 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
904 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
905 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
906
907 if (!LHS && !RHS)
908 return 0;
909
910 if (!LHS) LHS = BE->getLHS();
911 if (!RHS) RHS = BE->getRHS();
912
913 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
914 }
915 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000916
Craig Topper85814382012-02-07 05:05:23 +0000917 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000918}
919
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000920/// parseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000921///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000922/// expr ::= expr &&,|| expr -> lowest.
923/// expr ::= expr |,^,&,! expr
924/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
925/// expr ::= expr <<,>> expr
926/// expr ::= expr +,- expr
927/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000928/// expr ::= primaryexpr
929///
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000930bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000931 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000932 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000933 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
934 return true;
935
Daniel Dunbarcceba832010-09-17 02:47:07 +0000936 // As a special case, we support 'a op b @ modifier' by rewriting the
937 // expression to include the modifier. This is inefficient, but in general we
938 // expect users to use 'a@modifier op b'.
939 if (Lexer.getKind() == AsmToken::At) {
940 Lex();
941
942 if (Lexer.isNot(AsmToken::Identifier))
943 return TokError("unexpected symbol modifier following '@'");
944
945 MCSymbolRefExpr::VariantKind Variant =
946 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
947 if (Variant == MCSymbolRefExpr::VK_Invalid)
948 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
949
950 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
951 if (!ModifiedRes) {
952 return TokError("invalid modifier '" + getTok().getIdentifier() +
953 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000954 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000955
Daniel Dunbarcceba832010-09-17 02:47:07 +0000956 Res = ModifiedRes;
957 Lex();
958 }
959
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000960 // Try to constant fold it up front, if possible.
961 int64_t Value;
962 if (Res->EvaluateAsAbsolute(Value))
963 Res = MCConstantExpr::Create(Value, getContext());
964
965 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000966}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000967
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000968bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000969 Res = 0;
970 return ParseParenExpr(Res, EndLoc) ||
971 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000972}
973
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000974bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000975 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000976
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000977 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +0000978 if (parseExpression(Expr))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000979 return true;
980
Daniel Dunbare00b0112009-10-16 01:57:52 +0000981 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000982 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000983
984 return false;
985}
986
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000987static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000988 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000989 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000990 default:
991 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000992
Jim Grosbachfbe16812011-08-20 16:24:13 +0000993 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000994 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000995 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000996 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000997 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000998 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000999 return 1;
1000
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001001
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001002 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +00001003 //
1004 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +00001005 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001006 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001007 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001008 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001009 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001010 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001011 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001012 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001013 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001014
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001015 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001016 case AsmToken::EqualEqual:
1017 Kind = MCBinaryExpr::EQ;
1018 return 3;
1019 case AsmToken::ExclaimEqual:
1020 case AsmToken::LessGreater:
1021 Kind = MCBinaryExpr::NE;
1022 return 3;
1023 case AsmToken::Less:
1024 Kind = MCBinaryExpr::LT;
1025 return 3;
1026 case AsmToken::LessEqual:
1027 Kind = MCBinaryExpr::LTE;
1028 return 3;
1029 case AsmToken::Greater:
1030 Kind = MCBinaryExpr::GT;
1031 return 3;
1032 case AsmToken::GreaterEqual:
1033 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001034 return 3;
1035
Jim Grosbachfbe16812011-08-20 16:24:13 +00001036 // Intermediate Precedence: <<, >>
1037 case AsmToken::LessLess:
1038 Kind = MCBinaryExpr::Shl;
1039 return 4;
1040 case AsmToken::GreaterGreater:
1041 Kind = MCBinaryExpr::Shr;
1042 return 4;
1043
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001044 // High Intermediate Precedence: +, -
1045 case AsmToken::Plus:
1046 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001047 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001048 case AsmToken::Minus:
1049 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001050 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001051
Jim Grosbachfbe16812011-08-20 16:24:13 +00001052 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001053 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001054 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001055 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001056 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001057 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001058 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001059 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001060 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001061 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001062 }
1063}
1064
1065
1066/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1067/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001068bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1069 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001070 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001071 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001072 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001073
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001074 // If the next token is lower precedence than we are allowed to eat, return
1075 // successfully with what we ate already.
1076 if (TokPrec < Precedence)
1077 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001078
Sean Callanan79ed1a82010-01-19 20:22:31 +00001079 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001080
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001081 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001082 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001083 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001084
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001085 // If BinOp binds less tightly with RHS than the operator after RHS, let
1086 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001087 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001088 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001089 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001090 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001091 }
1092
Daniel Dunbar475839e2009-06-29 20:37:27 +00001093 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001094 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001095 }
1096}
1097
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001098/// ParseStatement:
1099/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001100/// ::= Label* Directive ...Operands... EndOfStatement
1101/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001102bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001103 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001104 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001105 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001106 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001107 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001108
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001109 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001110 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001111 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001112 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001113 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001114 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001115 if (Lexer.is(AsmToken::Hash))
1116 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001117
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001118 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001119 if (Lexer.is(AsmToken::Integer)) {
1120 LocalLabelVal = getTok().getIntVal();
1121 if (LocalLabelVal < 0) {
1122 if (!TheCondState.Ignore)
1123 return TokError("unexpected token at start of statement");
1124 IDVal = "";
Eli Benderskyed5df012013-01-16 19:32:36 +00001125 } else {
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001126 IDVal = getTok().getString();
1127 Lex(); // Consume the integer token to be used as an identifier token.
1128 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001129 if (!TheCondState.Ignore)
1130 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001131 }
1132 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001133 } else if (Lexer.is(AsmToken::Dot)) {
1134 // Treat '.' as a valid identifier in this context.
1135 Lex();
1136 IDVal = ".";
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001137 } else if (parseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001138 if (!TheCondState.Ignore)
1139 return TokError("unexpected token at start of statement");
1140 IDVal = "";
1141 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001142
Chris Lattner7834fac2010-04-17 18:14:27 +00001143 // Handle conditional assembly here before checking for skipping. We
1144 // have to do this so that .endif isn't skipped in a ".if 0" block for
1145 // example.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001146 StringMap<DirectiveKind>::const_iterator DirKindIt =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001147 DirectiveKindMap.find(IDVal);
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001148 DirectiveKind DirKind =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001149 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1150 DirKindIt->getValue();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001151 switch (DirKind) {
1152 default:
1153 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001154 case DK_IF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001155 return ParseDirectiveIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001156 case DK_IFB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001157 return ParseDirectiveIfb(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001158 case DK_IFNB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001159 return ParseDirectiveIfb(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001160 case DK_IFC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001161 return ParseDirectiveIfc(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001162 case DK_IFNC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001163 return ParseDirectiveIfc(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001164 case DK_IFDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001165 return ParseDirectiveIfdef(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001166 case DK_IFNDEF:
1167 case DK_IFNOTDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001168 return ParseDirectiveIfdef(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001169 case DK_ELSEIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001170 return ParseDirectiveElseIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001171 case DK_ELSE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001172 return ParseDirectiveElse(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001173 case DK_ENDIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001174 return ParseDirectiveEndIf(IDLoc);
1175 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001176
Eli Benderskyed5df012013-01-16 19:32:36 +00001177 // Ignore the statement if in the middle of inactive conditional
1178 // (e.g. ".if 0").
Chad Rosier17feeec2012-10-20 00:47:08 +00001179 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001180 eatToEndOfStatement();
Chris Lattner7834fac2010-04-17 18:14:27 +00001181 return false;
1182 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001183
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001184 // FIXME: Recurse on local labels?
1185
1186 // See what kind of statement we have.
1187 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001188 case AsmToken::Colon: {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001189 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001190
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001191 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001192 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001193
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001194 // Diagnose attempt to use '.' as a label.
1195 if (IDVal == ".")
1196 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1197
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001198 // Diagnose attempt to use a variable as a label.
1199 //
1200 // FIXME: Diagnostics. Note the location of the definition as a label.
1201 // FIXME: This doesn't diagnose assignment to a symbol which has been
1202 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001203 MCSymbol *Sym;
1204 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001205 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001206 else
1207 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001208 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001209 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001210
Daniel Dunbar959fd882009-08-26 22:13:22 +00001211 // Emit the label.
Chad Rosierdeb1bab2013-01-07 20:34:12 +00001212 if (!ParsingInlineAsm)
1213 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001214
Kevin Enderby94c2e852011-12-09 18:09:40 +00001215 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001216 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001217 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001218 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1219 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001220
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001221 // Consume any end of statement token, if present, to avoid spurious
1222 // AddBlankLine calls().
1223 if (Lexer.is(AsmToken::EndOfStatement)) {
1224 Lex();
1225 if (Lexer.is(AsmToken::Eof))
1226 return false;
1227 }
1228
Eli Friedman2128aae2012-10-22 23:58:19 +00001229 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001230 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001231
Daniel Dunbar3f872332009-07-28 16:08:33 +00001232 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001233 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001234 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001235
Nico Weber4c4c7322011-01-28 03:04:41 +00001236 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001237
1238 default: // Normal instruction or directive.
1239 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001240 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001241
1242 // If macros are enabled, check to see if this is a macro instantiation.
Eli Bendersky733c3362013-01-14 18:08:41 +00001243 if (MacrosEnabled())
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001244 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1245 return HandleMacroEntry(M, IDLoc);
1246 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001247
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001248 // Otherwise, we have a normal instruction or directive.
Eli Bendersky6ee13082013-01-15 22:59:42 +00001249
1250 // Directives start with "."
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001251 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00001252 // There are several entities interested in parsing directives:
1253 //
1254 // 1. The target-specific assembly parser. Some directives are target
1255 // specific or may potentially behave differently on certain targets.
1256 // 2. Asm parser extensions. For example, platform-specific parsers
1257 // (like the ELF parser) register themselves as extensions.
1258 // 3. The generic directive parser implemented by this class. These are
1259 // all the directives that behave in a target and platform independent
1260 // manner, or at least have a default behavior that's shared between
1261 // all targets and platforms.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001262
Eli Bendersky6ee13082013-01-15 22:59:42 +00001263 // First query the target-specific parser. It will return 'true' if it
1264 // isn't interested in this directive.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001265 if (!getTargetParser().ParseDirective(ID))
1266 return false;
1267
Eli Bendersky6ee13082013-01-15 22:59:42 +00001268 // Next, check the extention directive map to see if any extension has
1269 // registered itself to parse this directive.
1270 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1271 ExtensionDirectiveMap.lookup(IDVal);
1272 if (Handler.first)
1273 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1274
1275 // Finally, if no one else is interested in this directive, it must be
1276 // generic and familiar to this class.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001277 switch (DirKind) {
1278 default:
1279 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001280 case DK_SET:
1281 case DK_EQU:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001282 return ParseDirectiveSet(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001283 case DK_EQUIV:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001284 return ParseDirectiveSet(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001285 case DK_ASCII:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001286 return ParseDirectiveAscii(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001287 case DK_ASCIZ:
1288 case DK_STRING:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001289 return ParseDirectiveAscii(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001290 case DK_BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001291 return ParseDirectiveValue(1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001292 case DK_SHORT:
1293 case DK_VALUE:
1294 case DK_2BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001295 return ParseDirectiveValue(2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001296 case DK_LONG:
1297 case DK_INT:
1298 case DK_4BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001299 return ParseDirectiveValue(4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001300 case DK_QUAD:
1301 case DK_8BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001302 return ParseDirectiveValue(8);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001303 case DK_SINGLE:
1304 case DK_FLOAT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001305 return ParseDirectiveRealValue(APFloat::IEEEsingle);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001306 case DK_DOUBLE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001307 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001308 case DK_ALIGN: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001309 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1310 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1311 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001312 case DK_ALIGN32: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001313 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1314 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1315 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001316 case DK_BALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001317 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001318 case DK_BALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001319 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001320 case DK_BALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001321 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001322 case DK_P2ALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001323 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001324 case DK_P2ALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001325 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001326 case DK_P2ALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001327 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001328 case DK_ORG:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001329 return ParseDirectiveOrg();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001330 case DK_FILL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001331 return ParseDirectiveFill();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001332 case DK_ZERO:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001333 return ParseDirectiveZero();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001334 case DK_EXTERN:
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001335 eatToEndOfStatement(); // .extern is the default, ignore it.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001336 return false;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001337 case DK_GLOBL:
1338 case DK_GLOBAL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001339 return ParseDirectiveSymbolAttribute(MCSA_Global);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001340 case DK_INDIRECT_SYMBOL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001341 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001342 case DK_LAZY_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001343 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001344 case DK_NO_DEAD_STRIP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001345 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001346 case DK_SYMBOL_RESOLVER:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001347 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001348 case DK_PRIVATE_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001349 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001350 case DK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001351 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001352 case DK_WEAK_DEFINITION:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001353 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001354 case DK_WEAK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001355 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001356 case DK_WEAK_DEF_CAN_BE_HIDDEN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001357 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001358 case DK_COMM:
1359 case DK_COMMON:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001360 return ParseDirectiveComm(/*IsLocal=*/false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001361 case DK_LCOMM:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001362 return ParseDirectiveComm(/*IsLocal=*/true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001363 case DK_ABORT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001364 return ParseDirectiveAbort();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001365 case DK_INCLUDE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001366 return ParseDirectiveInclude();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001367 case DK_INCBIN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001368 return ParseDirectiveIncbin();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001369 case DK_CODE16:
1370 case DK_CODE16GCC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001371 return TokError(Twine(IDVal) + " not supported yet");
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001372 case DK_REPT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001373 return ParseDirectiveRept(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001374 case DK_IRP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001375 return ParseDirectiveIrp(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001376 case DK_IRPC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001377 return ParseDirectiveIrpc(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001378 case DK_ENDR:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001379 return ParseDirectiveEndr(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001380 case DK_BUNDLE_ALIGN_MODE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001381 return ParseDirectiveBundleAlignMode();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001382 case DK_BUNDLE_LOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001383 return ParseDirectiveBundleLock();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001384 case DK_BUNDLE_UNLOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001385 return ParseDirectiveBundleUnlock();
Eli Bendersky6ee13082013-01-15 22:59:42 +00001386 case DK_SLEB128:
1387 return ParseDirectiveLEB128(true);
1388 case DK_ULEB128:
1389 return ParseDirectiveLEB128(false);
1390 case DK_SPACE:
1391 case DK_SKIP:
1392 return ParseDirectiveSpace(IDVal);
1393 case DK_FILE:
1394 return ParseDirectiveFile(IDLoc);
1395 case DK_LINE:
1396 return ParseDirectiveLine();
1397 case DK_LOC:
1398 return ParseDirectiveLoc();
1399 case DK_STABS:
1400 return ParseDirectiveStabs();
1401 case DK_CFI_SECTIONS:
1402 return ParseDirectiveCFISections();
1403 case DK_CFI_STARTPROC:
1404 return ParseDirectiveCFIStartProc();
1405 case DK_CFI_ENDPROC:
1406 return ParseDirectiveCFIEndProc();
1407 case DK_CFI_DEF_CFA:
1408 return ParseDirectiveCFIDefCfa(IDLoc);
1409 case DK_CFI_DEF_CFA_OFFSET:
1410 return ParseDirectiveCFIDefCfaOffset();
1411 case DK_CFI_ADJUST_CFA_OFFSET:
1412 return ParseDirectiveCFIAdjustCfaOffset();
1413 case DK_CFI_DEF_CFA_REGISTER:
1414 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1415 case DK_CFI_OFFSET:
1416 return ParseDirectiveCFIOffset(IDLoc);
1417 case DK_CFI_REL_OFFSET:
1418 return ParseDirectiveCFIRelOffset(IDLoc);
1419 case DK_CFI_PERSONALITY:
1420 return ParseDirectiveCFIPersonalityOrLsda(true);
1421 case DK_CFI_LSDA:
1422 return ParseDirectiveCFIPersonalityOrLsda(false);
1423 case DK_CFI_REMEMBER_STATE:
1424 return ParseDirectiveCFIRememberState();
1425 case DK_CFI_RESTORE_STATE:
1426 return ParseDirectiveCFIRestoreState();
1427 case DK_CFI_SAME_VALUE:
1428 return ParseDirectiveCFISameValue(IDLoc);
1429 case DK_CFI_RESTORE:
1430 return ParseDirectiveCFIRestore(IDLoc);
1431 case DK_CFI_ESCAPE:
1432 return ParseDirectiveCFIEscape();
1433 case DK_CFI_SIGNAL_FRAME:
1434 return ParseDirectiveCFISignalFrame();
1435 case DK_CFI_UNDEFINED:
1436 return ParseDirectiveCFIUndefined(IDLoc);
1437 case DK_CFI_REGISTER:
1438 return ParseDirectiveCFIRegister(IDLoc);
1439 case DK_MACROS_ON:
1440 case DK_MACROS_OFF:
1441 return ParseDirectiveMacrosOnOff(IDVal);
1442 case DK_MACRO:
1443 return ParseDirectiveMacro(IDLoc);
1444 case DK_ENDM:
1445 case DK_ENDMACRO:
1446 return ParseDirectiveEndMacro(IDVal);
1447 case DK_PURGEM:
1448 return ParseDirectivePurgeMacro(IDLoc);
Eli Friedman5d68ec22010-07-19 04:17:25 +00001449 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001450
Jim Grosbach686c0182012-05-01 18:38:27 +00001451 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001452 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001453
Chad Rosier469b1442013-02-12 21:33:51 +00001454 // __asm _emit or __asm __emit
1455 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1456 IDVal == "_EMIT" || IDVal == "__EMIT"))
1457 return ParseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1458
1459 // __asm align
1460 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1461 return ParseDirectiveMSAlign(IDLoc, Info);
Eli Friedman2128aae2012-10-22 23:58:19 +00001462
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00001463 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001464
Chris Lattnera7f13542010-05-19 23:34:33 +00001465 // Canonicalize the opcode to lower case.
Eli Benderskyed5df012013-01-16 19:32:36 +00001466 std::string OpcodeStr = IDVal.lower();
Chad Rosier6a020a72012-10-25 20:41:34 +00001467 ParseInstructionInfo IInfo(Info.AsmRewrites);
Eli Benderskyed5df012013-01-16 19:32:36 +00001468 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr,
1469 IDLoc, Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001470 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001471
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001472 // Dump the parsed representation, if requested.
1473 if (getShowParsedOperands()) {
1474 SmallString<256> Str;
1475 raw_svector_ostream OS(Str);
1476 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001477 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001478 if (i != 0)
1479 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001480 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001481 }
1482 OS << "]";
1483
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001484 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001485 }
1486
Kevin Enderby613b7572011-11-01 22:27:22 +00001487 // If we are generating dwarf for assembly source files and the current
1488 // section is the initial text section then generate a .loc directive for
1489 // the instruction.
1490 if (!HadError && getContext().getGenDwarfForAssembly() &&
Eric Christopher2318ba12012-12-18 00:30:54 +00001491 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001492
Eli Benderskyed5df012013-01-16 19:32:36 +00001493 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
Kevin Enderby938482f2012-11-01 17:31:35 +00001494
Eli Benderskyed5df012013-01-16 19:32:36 +00001495 // If we previously parsed a cpp hash file line comment then make sure the
1496 // current Dwarf File is for the CppHashFilename if not then emit the
1497 // Dwarf File table for it and adjust the line number for the .loc.
Manman Ren9e999ad2013-03-12 20:17:00 +00001498 const SmallVectorImpl<MCDwarfFile *> &MCDwarfFiles =
Eli Benderskyed5df012013-01-16 19:32:36 +00001499 getContext().getMCDwarfFiles();
1500 if (CppHashFilename.size() != 0) {
1501 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
Kevin Enderby938482f2012-11-01 17:31:35 +00001502 CppHashFilename)
Eli Benderskyed5df012013-01-16 19:32:36 +00001503 getStreamer().EmitDwarfFileDirective(
1504 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001505
Kevin Enderby32c1a822012-11-05 21:55:41 +00001506 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
Kevin Enderby938482f2012-11-01 17:31:35 +00001507 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
Eli Benderskyed5df012013-01-16 19:32:36 +00001508 }
Kevin Enderby938482f2012-11-01 17:31:35 +00001509
Kevin Enderby613b7572011-11-01 22:27:22 +00001510 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001511 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001512 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001513 StringRef());
1514 }
1515
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001516 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001517 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001518 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001519 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1520 Info.ParsedOperands,
1521 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001522 ParsingInlineAsm);
1523 }
Chris Lattner98986712010-01-14 22:21:20 +00001524
Chris Lattnercbf8a982010-09-11 16:18:25 +00001525 // Don't skip the rest of the line, the instruction parser is responsible for
1526 // that.
1527 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001528}
Chris Lattner9a023f72009-06-24 04:43:34 +00001529
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001530/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1531/// since they may not be able to be tokenized to get to the end of line token.
1532void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001533 if (!Lexer.is(AsmToken::EndOfStatement))
1534 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001535 // Eat EOL.
1536 Lex();
1537}
1538
1539/// ParseCppHashLineFilenameComment as this:
1540/// ::= # number "filename"
1541/// or just as a full line comment if it doesn't have a number and a string.
1542bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1543 Lex(); // Eat the hash token.
1544
1545 if (getLexer().isNot(AsmToken::Integer)) {
1546 // Consume the line since in cases it is not a well-formed line directive,
1547 // as if were simply a full line comment.
1548 EatToEndOfLine();
1549 return false;
1550 }
1551
1552 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001553 Lex();
1554
1555 if (getLexer().isNot(AsmToken::String)) {
1556 EatToEndOfLine();
1557 return false;
1558 }
1559
1560 StringRef Filename = getTok().getString();
1561 // Get rid of the enclosing quotes.
1562 Filename = Filename.substr(1, Filename.size()-2);
1563
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001564 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1565 CppHashLoc = L;
1566 CppHashFilename = Filename;
1567 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001568 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001569
1570 // Ignore any trailing characters, they're just comment.
1571 EatToEndOfLine();
1572 return false;
1573}
1574
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001575/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001576/// for the Filename and LineNo if any in the diagnostic.
1577void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1578 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1579 raw_ostream &OS = errs();
1580
1581 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1582 const SMLoc &DiagLoc = Diag.getLoc();
1583 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1584 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1585
1586 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1587 // before printing the message.
1588 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001589 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001590 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1591 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1592 }
1593
Eric Christopher2318ba12012-12-18 00:30:54 +00001594 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001595 // manager changed or buffer changed (like in a nested include) then just
1596 // print the normal diagnostic using its Filename and LineNo.
1597 if (!Parser->CppHashLineNumber ||
1598 &DiagSrcMgr != &Parser->SrcMgr ||
1599 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001600 if (Parser->SavedDiagHandler)
1601 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1602 else
1603 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001604 return;
1605 }
1606
Eric Christopher2318ba12012-12-18 00:30:54 +00001607 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001608 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1609 // the diagnostic.
1610 const std::string Filename = Parser->CppHashFilename;
1611
1612 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1613 int CppHashLocLineNo =
1614 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1615 int LineNo = Parser->CppHashLineNumber - 1 +
1616 (DiagLocLineNo - CppHashLocLineNo);
1617
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001618 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1619 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001620 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001621 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001622
Benjamin Kramer04a04262011-10-16 10:48:29 +00001623 if (Parser->SavedDiagHandler)
1624 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1625 else
1626 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001627}
1628
Rafael Espindola799aacf2012-08-21 18:29:30 +00001629// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1630// difference being that that function accepts '@' as part of identifiers and
1631// we can't do that. AsmLexer.cpp should probably be changed to handle
1632// '@' as a special case when needed.
1633static bool isIdentifierChar(char c) {
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001634 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1635 c == '.';
Rafael Espindola799aacf2012-08-21 18:29:30 +00001636}
1637
Rafael Espindola761cb062012-06-03 23:57:14 +00001638bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001639 const MCAsmMacroParameters &Parameters,
1640 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001641 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001642 unsigned NParameters = Parameters.size();
1643 if (NParameters != 0 && NParameters != A.size())
1644 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001645
Preston Gurd7b6f2032012-09-19 20:36:12 +00001646 // A macro without parameters is handled differently on Darwin:
1647 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001648 while (!Body.empty()) {
1649 // Scan for the next substitution.
1650 std::size_t End = Body.size(), Pos = 0;
1651 for (; Pos != End; ++Pos) {
1652 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001653 if (!NParameters) {
1654 // This macro has no parameters, look for $0, $1, etc.
1655 if (Body[Pos] != '$' || Pos + 1 == End)
1656 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001657
Rafael Espindola65366442011-06-05 02:43:45 +00001658 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001659 if (Next == '$' || Next == 'n' ||
1660 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola65366442011-06-05 02:43:45 +00001661 break;
1662 } else {
1663 // This macro has parameters, look for \foo, \bar, etc.
1664 if (Body[Pos] == '\\' && Pos + 1 != End)
1665 break;
1666 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001667 }
1668
1669 // Add the prefix.
1670 OS << Body.slice(0, Pos);
1671
1672 // Check if we reached the end.
1673 if (Pos == End)
1674 break;
1675
Rafael Espindola65366442011-06-05 02:43:45 +00001676 if (!NParameters) {
1677 switch (Body[Pos+1]) {
1678 // $$ => $
1679 case '$':
1680 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001681 break;
1682
Rafael Espindola65366442011-06-05 02:43:45 +00001683 // $n => number of arguments
1684 case 'n':
1685 OS << A.size();
1686 break;
1687
1688 // $[0-9] => argument
1689 default: {
1690 // Missing arguments are ignored.
1691 unsigned Index = Body[Pos+1] - '0';
1692 if (Index >= A.size())
1693 break;
1694
1695 // Otherwise substitute with the token values, with spaces eliminated.
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001696 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001697 ie = A[Index].end(); it != ie; ++it)
1698 OS << it->getString();
1699 break;
1700 }
1701 }
1702 Pos += 2;
1703 } else {
1704 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001705 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001706 ++I;
1707
1708 const char *Begin = Body.data() + Pos +1;
1709 StringRef Argument(Begin, I - (Pos +1));
1710 unsigned Index = 0;
1711 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001712 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001713 break;
1714
Preston Gurd7b6f2032012-09-19 20:36:12 +00001715 if (Index == NParameters) {
1716 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1717 Pos += 3;
1718 else {
1719 OS << '\\' << Argument;
1720 Pos = I;
1721 }
1722 } else {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001723 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Preston Gurd7b6f2032012-09-19 20:36:12 +00001724 ie = A[Index].end(); it != ie; ++it)
1725 if (it->getKind() == AsmToken::String)
1726 OS << it->getStringContents();
1727 else
1728 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001729
Preston Gurd7b6f2032012-09-19 20:36:12 +00001730 Pos += 1 + Argument.size();
1731 }
Rafael Espindola65366442011-06-05 02:43:45 +00001732 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001733 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001734 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001735 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001736
Rafael Espindola65366442011-06-05 02:43:45 +00001737 return false;
1738}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001739
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001740MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001741 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001742 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001743 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1744 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001745{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001746}
1747
Preston Gurd7b6f2032012-09-19 20:36:12 +00001748static bool IsOperator(AsmToken::TokenKind kind)
1749{
1750 switch (kind)
1751 {
1752 default:
1753 return false;
1754 case AsmToken::Plus:
1755 case AsmToken::Minus:
1756 case AsmToken::Tilde:
1757 case AsmToken::Slash:
1758 case AsmToken::Star:
1759 case AsmToken::Dot:
1760 case AsmToken::Equal:
1761 case AsmToken::EqualEqual:
1762 case AsmToken::Pipe:
1763 case AsmToken::PipePipe:
1764 case AsmToken::Caret:
1765 case AsmToken::Amp:
1766 case AsmToken::AmpAmp:
1767 case AsmToken::Exclaim:
1768 case AsmToken::ExclaimEqual:
1769 case AsmToken::Percent:
1770 case AsmToken::Less:
1771 case AsmToken::LessEqual:
1772 case AsmToken::LessLess:
1773 case AsmToken::LessGreater:
1774 case AsmToken::Greater:
1775 case AsmToken::GreaterEqual:
1776 case AsmToken::GreaterGreater:
1777 return true;
1778 }
1779}
1780
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001781bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
Preston Gurd7b6f2032012-09-19 20:36:12 +00001782 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001783 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001784 unsigned AddTokens = 0;
1785
1786 // gas accepts arguments separated by whitespace, except on Darwin
1787 if (!IsDarwin)
1788 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001789
1790 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001791 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1792 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001793 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001794 }
1795
1796 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1797 // Spaces and commas cannot be mixed to delimit parameters
1798 if (ArgumentDelimiter == AsmToken::Eof)
1799 ArgumentDelimiter = AsmToken::Comma;
1800 else if (ArgumentDelimiter != AsmToken::Comma) {
1801 Lexer.setSkipSpace(true);
1802 return TokError("expected ' ' for macro argument separator");
1803 }
1804 break;
1805 }
1806
1807 if (Lexer.is(AsmToken::Space)) {
1808 Lex(); // Eat spaces
1809
1810 // Spaces can delimit parameters, but could also be part an expression.
1811 // If the token after a space is an operator, add the token and the next
1812 // one into this argument
1813 if (ArgumentDelimiter == AsmToken::Space ||
1814 ArgumentDelimiter == AsmToken::Eof) {
1815 if (IsOperator(Lexer.getKind())) {
1816 // Check to see whether the token is used as an operator,
1817 // or part of an identifier
Jordan Rose3ebe59c2013-01-07 19:00:49 +00001818 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd7b6f2032012-09-19 20:36:12 +00001819 if (*NextChar == ' ')
1820 AddTokens = 2;
1821 }
1822
1823 if (!AddTokens && ParenLevel == 0) {
1824 if (ArgumentDelimiter == AsmToken::Eof &&
1825 !IsOperator(Lexer.getKind()))
1826 ArgumentDelimiter = AsmToken::Space;
1827 break;
1828 }
1829 }
1830 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001831
1832 // HandleMacroEntry relies on not advancing the lexer here
1833 // to be able to fill in the remaining default parameter values
1834 if (Lexer.is(AsmToken::EndOfStatement))
1835 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001836
1837 // Adjust the current parentheses level.
1838 if (Lexer.is(AsmToken::LParen))
1839 ++ParenLevel;
1840 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1841 --ParenLevel;
1842
1843 // Append the token to the current argument list.
1844 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001845 if (AddTokens)
1846 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001847 Lex();
1848 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001849
1850 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001851 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001852 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001853 return false;
1854}
1855
1856// Parse the macro instantiation arguments.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001857bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001858 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001859 // Argument delimiter is initially unknown. It will be set by
1860 // ParseMacroArgument()
1861 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001862
1863 // Parse two kinds of macro invocations:
1864 // - macros defined without any parameters accept an arbitrary number of them
1865 // - macros defined with parameters accept at most that many of them
1866 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1867 ++Parameter) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001868 MCAsmMacroArgument MA;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001869
Preston Gurd7b6f2032012-09-19 20:36:12 +00001870 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001871 return true;
1872
Preston Gurd6c9176a2012-09-19 20:29:04 +00001873 if (!MA.empty() || !NParameters)
1874 A.push_back(MA);
1875 else if (NParameters) {
1876 if (!M->Parameters[Parameter].second.empty())
1877 A.push_back(M->Parameters[Parameter].second);
1878 }
Jim Grosbach97146442012-07-30 22:44:17 +00001879
Preston Gurd6c9176a2012-09-19 20:29:04 +00001880 // At the end of the statement, fill in remaining arguments that have
1881 // default values. If there aren't any, then the next argument is
1882 // required but missing
1883 if (Lexer.is(AsmToken::EndOfStatement)) {
1884 if (NParameters && Parameter < NParameters - 1) {
1885 if (M->Parameters[Parameter + 1].second.empty())
1886 return TokError("macro argument '" +
1887 Twine(M->Parameters[Parameter + 1].first) +
1888 "' is missing");
1889 else
1890 continue;
1891 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001892 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001893 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001894
1895 if (Lexer.is(AsmToken::Comma))
1896 Lex();
1897 }
1898 return TokError("Too many arguments");
1899}
1900
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001901const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1902 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1903 return (I == MacroMap.end()) ? NULL : I->getValue();
1904}
1905
1906void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1907 MacroMap[Name] = new MCAsmMacro(Macro);
1908}
1909
1910void AsmParser::UndefineMacro(StringRef Name) {
1911 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1912 if (I != MacroMap.end()) {
1913 delete I->getValue();
1914 MacroMap.erase(I);
1915 }
1916}
1917
1918bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001919 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1920 // this, although we should protect against infinite loops.
1921 if (ActiveMacros.size() == 20)
1922 return TokError("macros cannot be nested more than 20 levels deep");
1923
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001924 MCAsmMacroArguments A;
Rafael Espindola8a403d32012-08-08 14:51:03 +00001925 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001926 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001927
Jim Grosbach97146442012-07-30 22:44:17 +00001928 // Remove any trailing empty arguments. Do this after-the-fact as we have
1929 // to keep empty arguments in the middle of the list or positionality
1930 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001931 while (!A.empty() && A.back().empty())
1932 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001933
Rafael Espindola65366442011-06-05 02:43:45 +00001934 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1935 // to hold the macro body with substitutions.
1936 SmallString<256> Buf;
1937 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001938 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001939
Rafael Espindola8a403d32012-08-08 14:51:03 +00001940 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001941 return true;
1942
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001943 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola761cb062012-06-03 23:57:14 +00001944 // instantiation.
1945 OS << ".endmacro\n";
1946
Rafael Espindola65366442011-06-05 02:43:45 +00001947 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001948 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001949
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001950 // Create the macro instantiation object and add to the current macro
1951 // instantiation stack.
1952 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001953 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001954 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001955 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001956 ActiveMacros.push_back(MI);
1957
1958 // Jump to the macro instantiation and prime the lexer.
1959 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1960 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1961 Lex();
1962
1963 return false;
1964}
1965
1966void AsmParser::HandleMacroExit() {
1967 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001968 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001969 Lex();
1970
1971 // Pop the instantiation entry.
1972 delete ActiveMacros.back();
1973 ActiveMacros.pop_back();
1974}
1975
Rafael Espindolae71cc862012-01-28 05:57:00 +00001976static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001977 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001978 case MCExpr::Binary: {
1979 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1980 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001981 break;
1982 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001983 case MCExpr::Target:
1984 case MCExpr::Constant:
1985 return false;
1986 case MCExpr::SymbolRef: {
1987 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001988 if (S.isVariable())
1989 return IsUsedIn(Sym, S.getVariableValue());
1990 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001991 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001992 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001993 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001994 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001995
1996 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001997}
1998
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001999bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
2000 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002001 // FIXME: Use better location, we should use proper tokens.
2002 SMLoc EqualLoc = Lexer.getLoc();
2003
Daniel Dunbar821e3332009-08-31 08:09:28 +00002004 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002005 if (parseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002006 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002007
Rafael Espindolae71cc862012-01-28 05:57:00 +00002008 // Note: we don't count b as used in "a = b". This is to allow
2009 // a = b
2010 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002011
Daniel Dunbar3f872332009-07-28 16:08:33 +00002012 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002013 return TokError("unexpected token in assignment");
2014
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00002015 // Error on assignment to '.'.
2016 if (Name == ".") {
2017 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2018 "(use '.space' or '.org').)"));
2019 }
2020
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002021 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00002022 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002023
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002024 // Validate that the LHS is allowed to be a variable (either it has not been
2025 // used as a symbol, or it is an absolute symbol).
2026 MCSymbol *Sym = getContext().LookupSymbol(Name);
2027 if (Sym) {
2028 // Diagnose assignment to a label.
2029 //
2030 // FIXME: Diagnostics. Note the location of the definition as a label.
2031 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00002032 if (IsUsedIn(Sym, Value))
2033 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2034 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00002035 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00002036 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2037 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00002038 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002039 return Error(EqualLoc, "redefinition of '" + Name + "'");
2040 else if (!Sym->isVariable())
2041 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00002042 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002043 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2044 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002045
2046 // Don't count these checks as uses.
2047 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002048 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002049 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002050
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002051 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002052
2053 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00002054 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002055 if (NoDeadStrip)
2056 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2057
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002058
2059 return false;
2060}
2061
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002062/// parseIdentifier:
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002063/// ::= identifier
2064/// ::= string
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002065bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00002066 // The assembler has relaxed rules for accepting identifiers, in particular we
2067 // allow things like '.globl $foo', which would normally be separate
2068 // tokens. At this level, we have already lexed so we cannot (currently)
2069 // handle this as a context dependent token, instead we detect adjacent tokens
2070 // and return the combined identifier.
2071 if (Lexer.is(AsmToken::Dollar)) {
2072 SMLoc DollarLoc = getLexer().getLoc();
2073
2074 // Consume the dollar sign, and check for a following identifier.
2075 Lex();
2076 if (Lexer.isNot(AsmToken::Identifier))
2077 return true;
2078
2079 // We have a '$' followed by an identifier, make sure they are adjacent.
2080 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2081 return true;
2082
2083 // Construct the joined identifier and consume the token.
2084 Res = StringRef(DollarLoc.getPointer(),
2085 getTok().getIdentifier().size() + 1);
2086 Lex();
2087 return false;
2088 }
2089
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002090 if (Lexer.isNot(AsmToken::Identifier) &&
2091 Lexer.isNot(AsmToken::String))
2092 return true;
2093
Sean Callanan18b83232010-01-19 21:44:56 +00002094 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002095
Sean Callanan79ed1a82010-01-19 20:22:31 +00002096 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002097
2098 return false;
2099}
2100
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002101/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002102/// ::= .equ identifier ',' expression
2103/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002104/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002105bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002106 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002107
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002108 if (parseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002109 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002110
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002111 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002112 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002113 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002114
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002115 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002116}
2117
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002118bool AsmParser::parseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002119 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002120
2121 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002122 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002123 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2124 if (Str[i] != '\\') {
2125 Data += Str[i];
2126 continue;
2127 }
2128
2129 // Recognize escaped characters. Note that this escape semantics currently
2130 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2131 ++i;
2132 if (i == e)
2133 return TokError("unexpected backslash at end of string");
2134
2135 // Recognize octal sequences.
2136 if ((unsigned) (Str[i] - '0') <= 7) {
2137 // Consume up to three octal characters.
2138 unsigned Value = Str[i] - '0';
2139
2140 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2141 ++i;
2142 Value = Value * 8 + (Str[i] - '0');
2143
2144 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2145 ++i;
2146 Value = Value * 8 + (Str[i] - '0');
2147 }
2148 }
2149
2150 if (Value > 255)
2151 return TokError("invalid octal escape sequence (out of range)");
2152
2153 Data += (unsigned char) Value;
2154 continue;
2155 }
2156
2157 // Otherwise recognize individual escapes.
2158 switch (Str[i]) {
2159 default:
2160 // Just reject invalid escape sequences for now.
2161 return TokError("invalid escape sequence (unrecognized character)");
2162
2163 case 'b': Data += '\b'; break;
2164 case 'f': Data += '\f'; break;
2165 case 'n': Data += '\n'; break;
2166 case 'r': Data += '\r'; break;
2167 case 't': Data += '\t'; break;
2168 case '"': Data += '"'; break;
2169 case '\\': Data += '\\'; break;
2170 }
2171 }
2172
2173 return false;
2174}
2175
Daniel Dunbara0d14262009-06-24 23:30:00 +00002176/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002177/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2178bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002179 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002180 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002181
Daniel Dunbara0d14262009-06-24 23:30:00 +00002182 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002183 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002184 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002185
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002186 std::string Data;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002187 if (parseEscapedString(Data))
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002188 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002189
2190 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002191 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002192 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2193
Sean Callanan79ed1a82010-01-19 20:22:31 +00002194 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002195
2196 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002197 break;
2198
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002199 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002200 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002201 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002202 }
2203 }
2204
Sean Callanan79ed1a82010-01-19 20:22:31 +00002205 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002206 return false;
2207}
2208
2209/// ParseDirectiveValue
2210/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2211bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002212 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002213 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002214
Daniel Dunbara0d14262009-06-24 23:30:00 +00002215 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002216 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002217 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002218 if (parseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002219 return true;
2220
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002221 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002222 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2223 assert(Size <= 8 && "Invalid size");
2224 uint64_t IntValue = MCE->getValue();
2225 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2226 return Error(ExprLoc, "literal value out of range for directive");
2227 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2228 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002229 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002230
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002231 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002232 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002233
Daniel Dunbara0d14262009-06-24 23:30:00 +00002234 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002235 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002236 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002237 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002238 }
2239 }
2240
Sean Callanan79ed1a82010-01-19 20:22:31 +00002241 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002242 return false;
2243}
2244
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002245/// ParseDirectiveRealValue
2246/// ::= (.single | .double) [ expression (, expression)* ]
2247bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2248 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002249 checkForValidSection();
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002250
2251 for (;;) {
2252 // We don't truly support arithmetic on floating point expressions, so we
2253 // have to manually parse unary prefixes.
2254 bool IsNeg = false;
2255 if (getLexer().is(AsmToken::Minus)) {
2256 Lex();
2257 IsNeg = true;
2258 } else if (getLexer().is(AsmToken::Plus))
2259 Lex();
2260
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002261 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002262 getLexer().isNot(AsmToken::Real) &&
2263 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002264 return TokError("unexpected token in directive");
2265
2266 // Convert to an APFloat.
2267 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002268 StringRef IDVal = getTok().getString();
2269 if (getLexer().is(AsmToken::Identifier)) {
2270 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2271 Value = APFloat::getInf(Semantics);
2272 else if (!IDVal.compare_lower("nan"))
2273 Value = APFloat::getNaN(Semantics, false, ~0);
2274 else
2275 return TokError("invalid floating point literal");
2276 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002277 APFloat::opInvalidOp)
2278 return TokError("invalid floating point literal");
2279 if (IsNeg)
2280 Value.changeSign();
2281
2282 // Consume the numeric token.
2283 Lex();
2284
2285 // Emit the value as an integer.
2286 APInt AsInt = Value.bitcastToAPInt();
2287 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2288 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2289
2290 if (getLexer().is(AsmToken::EndOfStatement))
2291 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002292
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002293 if (getLexer().isNot(AsmToken::Comma))
2294 return TokError("unexpected token in directive");
2295 Lex();
2296 }
2297 }
2298
2299 Lex();
2300 return false;
2301}
2302
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002303/// ParseDirectiveZero
2304/// ::= .zero expression
2305bool AsmParser::ParseDirectiveZero() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002306 checkForValidSection();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002307
2308 int64_t NumBytes;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002309 if (parseAbsoluteExpression(NumBytes))
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002310 return true;
2311
Rafael Espindolae452b172010-10-05 19:42:57 +00002312 int64_t Val = 0;
2313 if (getLexer().is(AsmToken::Comma)) {
2314 Lex();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002315 if (parseAbsoluteExpression(Val))
Rafael Espindolae452b172010-10-05 19:42:57 +00002316 return true;
2317 }
2318
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002319 if (getLexer().isNot(AsmToken::EndOfStatement))
2320 return TokError("unexpected token in '.zero' directive");
2321
2322 Lex();
2323
Rafael Espindolae452b172010-10-05 19:42:57 +00002324 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002325
2326 return false;
2327}
2328
Daniel Dunbara0d14262009-06-24 23:30:00 +00002329/// ParseDirectiveFill
2330/// ::= .fill expression , expression , expression
2331bool AsmParser::ParseDirectiveFill() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002332 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002333
Daniel Dunbara0d14262009-06-24 23:30:00 +00002334 int64_t NumValues;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002335 if (parseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002336 return true;
2337
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002338 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002339 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002340 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002341
Daniel Dunbara0d14262009-06-24 23:30:00 +00002342 int64_t FillSize;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002343 if (parseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002344 return true;
2345
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002346 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002347 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002348 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002349
Daniel Dunbara0d14262009-06-24 23:30:00 +00002350 int64_t FillExpr;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002351 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002352 return true;
2353
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002354 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002355 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002356
Sean Callanan79ed1a82010-01-19 20:22:31 +00002357 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002358
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002359 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2360 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002361
2362 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002363 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002364
2365 return false;
2366}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002367
2368/// ParseDirectiveOrg
2369/// ::= .org expression [ , expression ]
2370bool AsmParser::ParseDirectiveOrg() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002371 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002372
Daniel Dunbar821e3332009-08-31 08:09:28 +00002373 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002374 SMLoc Loc = getTok().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002375 if (parseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002376 return true;
2377
2378 // Parse optional fill expression.
2379 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002380 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2381 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002382 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002383 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002384
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002385 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002386 return true;
2387
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002388 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002389 return TokError("unexpected token in '.org' directive");
2390 }
2391
Sean Callanan79ed1a82010-01-19 20:22:31 +00002392 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002393
Jim Grosbachebd4c052012-01-27 00:37:08 +00002394 // Only limited forms of relocatable expressions are accepted here, it
2395 // has to be relative to the current section. The streamer will return
2396 // 'true' if the expression wasn't evaluatable.
2397 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2398 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002399
2400 return false;
2401}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002402
2403/// ParseDirectiveAlign
2404/// ::= {.align, ...} expression [ , expression [ , expression ]]
2405bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002406 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002407
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002408 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002409 int64_t Alignment;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002410 if (parseAbsoluteExpression(Alignment))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002411 return true;
2412
2413 SMLoc MaxBytesLoc;
2414 bool HasFillExpr = false;
2415 int64_t FillExpr = 0;
2416 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002417 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2418 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002419 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002420 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002421
2422 // The fill expression can be omitted while specifying a maximum number of
2423 // alignment bytes, e.g:
2424 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002425 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002426 HasFillExpr = true;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002427 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002428 return true;
2429 }
2430
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002431 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2432 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002433 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002434 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002435
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002436 MaxBytesLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002437 if (parseAbsoluteExpression(MaxBytesToFill))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002438 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002439
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002440 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002441 return TokError("unexpected token in directive");
2442 }
2443 }
2444
Sean Callanan79ed1a82010-01-19 20:22:31 +00002445 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002446
Daniel Dunbar648ac512010-05-17 21:54:30 +00002447 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002448 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002449
2450 // Compute alignment in bytes.
2451 if (IsPow2) {
2452 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002453 if (Alignment >= 32) {
2454 Error(AlignmentLoc, "invalid alignment value");
2455 Alignment = 31;
2456 }
2457
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002458 Alignment = 1ULL << Alignment;
Benjamin Kramer8a89cf22013-02-16 15:00:16 +00002459 } else {
2460 // Reject alignments that aren't a power of two, for gas compatibility.
2461 if (!isPowerOf2_64(Alignment))
2462 Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002463 }
2464
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002465 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002466 if (MaxBytesLoc.isValid()) {
2467 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002468 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2469 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002470 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002471 }
2472
2473 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002474 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2475 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002476 MaxBytesToFill = 0;
2477 }
2478 }
2479
Daniel Dunbar648ac512010-05-17 21:54:30 +00002480 // Check whether we should use optimal code alignment for this .align
2481 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002482 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002483 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2484 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002485 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002486 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002487 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002488 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2489 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002490 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002491
2492 return false;
2493}
2494
Eli Bendersky6ee13082013-01-15 22:59:42 +00002495/// ParseDirectiveFile
2496/// ::= .file [number] filename
2497/// ::= .file number directory filename
2498bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2499 // FIXME: I'm not sure what this is.
2500 int64_t FileNumber = -1;
2501 SMLoc FileNumberLoc = getLexer().getLoc();
2502 if (getLexer().is(AsmToken::Integer)) {
2503 FileNumber = getTok().getIntVal();
2504 Lex();
2505
2506 if (FileNumber < 1)
2507 return TokError("file number less than one");
2508 }
2509
2510 if (getLexer().isNot(AsmToken::String))
2511 return TokError("unexpected token in '.file' directive");
2512
2513 // Usually the directory and filename together, otherwise just the directory.
2514 StringRef Path = getTok().getString();
2515 Path = Path.substr(1, Path.size()-2);
2516 Lex();
2517
2518 StringRef Directory;
2519 StringRef Filename;
2520 if (getLexer().is(AsmToken::String)) {
2521 if (FileNumber == -1)
2522 return TokError("explicit path specified, but no file number");
2523 Filename = getTok().getString();
2524 Filename = Filename.substr(1, Filename.size()-2);
2525 Directory = Path;
2526 Lex();
2527 } else {
2528 Filename = Path;
2529 }
2530
2531 if (getLexer().isNot(AsmToken::EndOfStatement))
2532 return TokError("unexpected token in '.file' directive");
2533
2534 if (FileNumber == -1)
2535 getStreamer().EmitFileDirective(Filename);
2536 else {
2537 if (getContext().getGenDwarfForAssembly() == true)
2538 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2539 "used to generate dwarf debug info for assembly code");
2540
2541 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2542 Error(FileNumberLoc, "file number already allocated");
2543 }
2544
2545 return false;
2546}
2547
2548/// ParseDirectiveLine
2549/// ::= .line [number]
2550bool AsmParser::ParseDirectiveLine() {
2551 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2552 if (getLexer().isNot(AsmToken::Integer))
2553 return TokError("unexpected token in '.line' directive");
2554
2555 int64_t LineNumber = getTok().getIntVal();
2556 (void) LineNumber;
2557 Lex();
2558
2559 // FIXME: Do something with the .line.
2560 }
2561
2562 if (getLexer().isNot(AsmToken::EndOfStatement))
2563 return TokError("unexpected token in '.line' directive");
2564
2565 return false;
2566}
2567
2568/// ParseDirectiveLoc
2569/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2570/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2571/// The first number is a file number, must have been previously assigned with
2572/// a .file directive, the second number is the line number and optionally the
2573/// third number is a column position (zero if not specified). The remaining
2574/// optional items are .loc sub-directives.
2575bool AsmParser::ParseDirectiveLoc() {
2576 if (getLexer().isNot(AsmToken::Integer))
2577 return TokError("unexpected token in '.loc' directive");
2578 int64_t FileNumber = getTok().getIntVal();
2579 if (FileNumber < 1)
2580 return TokError("file number less than one in '.loc' directive");
2581 if (!getContext().isValidDwarfFileNumber(FileNumber))
2582 return TokError("unassigned file number in '.loc' directive");
2583 Lex();
2584
2585 int64_t LineNumber = 0;
2586 if (getLexer().is(AsmToken::Integer)) {
2587 LineNumber = getTok().getIntVal();
2588 if (LineNumber < 1)
2589 return TokError("line number less than one in '.loc' directive");
2590 Lex();
2591 }
2592
2593 int64_t ColumnPos = 0;
2594 if (getLexer().is(AsmToken::Integer)) {
2595 ColumnPos = getTok().getIntVal();
2596 if (ColumnPos < 0)
2597 return TokError("column position less than zero in '.loc' directive");
2598 Lex();
2599 }
2600
2601 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2602 unsigned Isa = 0;
2603 int64_t Discriminator = 0;
2604 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2605 for (;;) {
2606 if (getLexer().is(AsmToken::EndOfStatement))
2607 break;
2608
2609 StringRef Name;
2610 SMLoc Loc = getTok().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002611 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002612 return TokError("unexpected token in '.loc' directive");
2613
2614 if (Name == "basic_block")
2615 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2616 else if (Name == "prologue_end")
2617 Flags |= DWARF2_FLAG_PROLOGUE_END;
2618 else if (Name == "epilogue_begin")
2619 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2620 else if (Name == "is_stmt") {
2621 Loc = getTok().getLoc();
2622 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002623 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002624 return true;
2625 // The expression must be the constant 0 or 1.
2626 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2627 int Value = MCE->getValue();
2628 if (Value == 0)
2629 Flags &= ~DWARF2_FLAG_IS_STMT;
2630 else if (Value == 1)
2631 Flags |= DWARF2_FLAG_IS_STMT;
2632 else
2633 return Error(Loc, "is_stmt value not 0 or 1");
2634 }
2635 else {
2636 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2637 }
2638 }
2639 else if (Name == "isa") {
2640 Loc = getTok().getLoc();
2641 const MCExpr *Value;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002642 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002643 return true;
2644 // The expression must be a constant greater or equal to 0.
2645 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2646 int Value = MCE->getValue();
2647 if (Value < 0)
2648 return Error(Loc, "isa number less than zero");
2649 Isa = Value;
2650 }
2651 else {
2652 return Error(Loc, "isa number not a constant value");
2653 }
2654 }
2655 else if (Name == "discriminator") {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002656 if (parseAbsoluteExpression(Discriminator))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002657 return true;
2658 }
2659 else {
2660 return Error(Loc, "unknown sub-directive in '.loc' directive");
2661 }
2662
2663 if (getLexer().is(AsmToken::EndOfStatement))
2664 break;
2665 }
2666 }
2667
2668 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2669 Isa, Discriminator, StringRef());
2670
2671 return false;
2672}
2673
2674/// ParseDirectiveStabs
2675/// ::= .stabs string, number, number, number
2676bool AsmParser::ParseDirectiveStabs() {
2677 return TokError("unsupported directive '.stabs'");
2678}
2679
2680/// ParseDirectiveCFISections
2681/// ::= .cfi_sections section [, section]
2682bool AsmParser::ParseDirectiveCFISections() {
2683 StringRef Name;
2684 bool EH = false;
2685 bool Debug = false;
2686
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002687 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002688 return TokError("Expected an identifier");
2689
2690 if (Name == ".eh_frame")
2691 EH = true;
2692 else if (Name == ".debug_frame")
2693 Debug = true;
2694
2695 if (getLexer().is(AsmToken::Comma)) {
2696 Lex();
2697
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002698 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002699 return TokError("Expected an identifier");
2700
2701 if (Name == ".eh_frame")
2702 EH = true;
2703 else if (Name == ".debug_frame")
2704 Debug = true;
2705 }
2706
2707 getStreamer().EmitCFISections(EH, Debug);
2708 return false;
2709}
2710
2711/// ParseDirectiveCFIStartProc
2712/// ::= .cfi_startproc
2713bool AsmParser::ParseDirectiveCFIStartProc() {
2714 getStreamer().EmitCFIStartProc();
2715 return false;
2716}
2717
2718/// ParseDirectiveCFIEndProc
2719/// ::= .cfi_endproc
2720bool AsmParser::ParseDirectiveCFIEndProc() {
2721 getStreamer().EmitCFIEndProc();
2722 return false;
2723}
2724
2725/// ParseRegisterOrRegisterNumber - parse register name or number.
2726bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2727 SMLoc DirectiveLoc) {
2728 unsigned RegNo;
2729
2730 if (getLexer().isNot(AsmToken::Integer)) {
2731 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2732 return true;
2733 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2734 } else
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002735 return parseAbsoluteExpression(Register);
Eli Bendersky6ee13082013-01-15 22:59:42 +00002736
2737 return false;
2738}
2739
2740/// ParseDirectiveCFIDefCfa
2741/// ::= .cfi_def_cfa register, offset
2742bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2743 int64_t Register = 0;
2744 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2745 return true;
2746
2747 if (getLexer().isNot(AsmToken::Comma))
2748 return TokError("unexpected token in directive");
2749 Lex();
2750
2751 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002752 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002753 return true;
2754
2755 getStreamer().EmitCFIDefCfa(Register, Offset);
2756 return false;
2757}
2758
2759/// ParseDirectiveCFIDefCfaOffset
2760/// ::= .cfi_def_cfa_offset offset
2761bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
2762 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002763 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002764 return true;
2765
2766 getStreamer().EmitCFIDefCfaOffset(Offset);
2767 return false;
2768}
2769
2770/// ParseDirectiveCFIRegister
2771/// ::= .cfi_register register, register
2772bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2773 int64_t Register1 = 0;
2774 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2775 return true;
2776
2777 if (getLexer().isNot(AsmToken::Comma))
2778 return TokError("unexpected token in directive");
2779 Lex();
2780
2781 int64_t Register2 = 0;
2782 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2783 return true;
2784
2785 getStreamer().EmitCFIRegister(Register1, Register2);
2786 return false;
2787}
2788
2789/// ParseDirectiveCFIAdjustCfaOffset
2790/// ::= .cfi_adjust_cfa_offset adjustment
2791bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
2792 int64_t Adjustment = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002793 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002794 return true;
2795
2796 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2797 return false;
2798}
2799
2800/// ParseDirectiveCFIDefCfaRegister
2801/// ::= .cfi_def_cfa_register register
2802bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2803 int64_t Register = 0;
2804 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2805 return true;
2806
2807 getStreamer().EmitCFIDefCfaRegister(Register);
2808 return false;
2809}
2810
2811/// ParseDirectiveCFIOffset
2812/// ::= .cfi_offset register, offset
2813bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2814 int64_t Register = 0;
2815 int64_t Offset = 0;
2816
2817 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2818 return true;
2819
2820 if (getLexer().isNot(AsmToken::Comma))
2821 return TokError("unexpected token in directive");
2822 Lex();
2823
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002824 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002825 return true;
2826
2827 getStreamer().EmitCFIOffset(Register, Offset);
2828 return false;
2829}
2830
2831/// ParseDirectiveCFIRelOffset
2832/// ::= .cfi_rel_offset register, offset
2833bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2834 int64_t Register = 0;
2835
2836 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2837 return true;
2838
2839 if (getLexer().isNot(AsmToken::Comma))
2840 return TokError("unexpected token in directive");
2841 Lex();
2842
2843 int64_t Offset = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002844 if (parseAbsoluteExpression(Offset))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002845 return true;
2846
2847 getStreamer().EmitCFIRelOffset(Register, Offset);
2848 return false;
2849}
2850
2851static bool isValidEncoding(int64_t Encoding) {
2852 if (Encoding & ~0xff)
2853 return false;
2854
2855 if (Encoding == dwarf::DW_EH_PE_omit)
2856 return true;
2857
2858 const unsigned Format = Encoding & 0xf;
2859 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2860 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2861 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2862 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2863 return false;
2864
2865 const unsigned Application = Encoding & 0x70;
2866 if (Application != dwarf::DW_EH_PE_absptr &&
2867 Application != dwarf::DW_EH_PE_pcrel)
2868 return false;
2869
2870 return true;
2871}
2872
2873/// ParseDirectiveCFIPersonalityOrLsda
2874/// IsPersonality true for cfi_personality, false for cfi_lsda
2875/// ::= .cfi_personality encoding, [symbol_name]
2876/// ::= .cfi_lsda encoding, [symbol_name]
2877bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2878 int64_t Encoding = 0;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002879 if (parseAbsoluteExpression(Encoding))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002880 return true;
2881 if (Encoding == dwarf::DW_EH_PE_omit)
2882 return false;
2883
2884 if (!isValidEncoding(Encoding))
2885 return TokError("unsupported encoding.");
2886
2887 if (getLexer().isNot(AsmToken::Comma))
2888 return TokError("unexpected token in directive");
2889 Lex();
2890
2891 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002892 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002893 return TokError("expected identifier in directive");
2894
2895 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2896
2897 if (IsPersonality)
2898 getStreamer().EmitCFIPersonality(Sym, Encoding);
2899 else
2900 getStreamer().EmitCFILsda(Sym, Encoding);
2901 return false;
2902}
2903
2904/// ParseDirectiveCFIRememberState
2905/// ::= .cfi_remember_state
2906bool AsmParser::ParseDirectiveCFIRememberState() {
2907 getStreamer().EmitCFIRememberState();
2908 return false;
2909}
2910
2911/// ParseDirectiveCFIRestoreState
2912/// ::= .cfi_remember_state
2913bool AsmParser::ParseDirectiveCFIRestoreState() {
2914 getStreamer().EmitCFIRestoreState();
2915 return false;
2916}
2917
2918/// ParseDirectiveCFISameValue
2919/// ::= .cfi_same_value register
2920bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2921 int64_t Register = 0;
2922
2923 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2924 return true;
2925
2926 getStreamer().EmitCFISameValue(Register);
2927 return false;
2928}
2929
2930/// ParseDirectiveCFIRestore
2931/// ::= .cfi_restore register
2932bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2933 int64_t Register = 0;
2934 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2935 return true;
2936
2937 getStreamer().EmitCFIRestore(Register);
2938 return false;
2939}
2940
2941/// ParseDirectiveCFIEscape
2942/// ::= .cfi_escape expression[,...]
2943bool AsmParser::ParseDirectiveCFIEscape() {
2944 std::string Values;
2945 int64_t CurrValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002946 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002947 return true;
2948
2949 Values.push_back((uint8_t)CurrValue);
2950
2951 while (getLexer().is(AsmToken::Comma)) {
2952 Lex();
2953
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00002954 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky6ee13082013-01-15 22:59:42 +00002955 return true;
2956
2957 Values.push_back((uint8_t)CurrValue);
2958 }
2959
2960 getStreamer().EmitCFIEscape(Values);
2961 return false;
2962}
2963
2964/// ParseDirectiveCFISignalFrame
2965/// ::= .cfi_signal_frame
2966bool AsmParser::ParseDirectiveCFISignalFrame() {
2967 if (getLexer().isNot(AsmToken::EndOfStatement))
2968 return Error(getLexer().getLoc(),
2969 "unexpected token in '.cfi_signal_frame'");
2970
2971 getStreamer().EmitCFISignalFrame();
2972 return false;
2973}
2974
2975/// ParseDirectiveCFIUndefined
2976/// ::= .cfi_undefined register
2977bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
2978 int64_t Register = 0;
2979
2980 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2981 return true;
2982
2983 getStreamer().EmitCFIUndefined(Register);
2984 return false;
2985}
2986
2987/// ParseDirectiveMacrosOnOff
2988/// ::= .macros_on
2989/// ::= .macros_off
2990bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
2991 if (getLexer().isNot(AsmToken::EndOfStatement))
2992 return Error(getLexer().getLoc(),
2993 "unexpected token in '" + Directive + "' directive");
2994
2995 SetMacrosEnabled(Directive == ".macros_on");
2996 return false;
2997}
2998
2999/// ParseDirectiveMacro
3000/// ::= .macro name [parameters]
3001bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
3002 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003003 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003004 return TokError("expected identifier in '.macro' directive");
3005
3006 MCAsmMacroParameters Parameters;
3007 // Argument delimiter is initially unknown. It will be set by
3008 // ParseMacroArgument()
3009 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3010 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3011 for (;;) {
3012 MCAsmMacroParameter Parameter;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003013 if (parseIdentifier(Parameter.first))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003014 return TokError("expected identifier in '.macro' directive");
3015
3016 if (getLexer().is(AsmToken::Equal)) {
3017 Lex();
3018 if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3019 return true;
3020 }
3021
3022 Parameters.push_back(Parameter);
3023
3024 if (getLexer().is(AsmToken::Comma))
3025 Lex();
3026 else if (getLexer().is(AsmToken::EndOfStatement))
3027 break;
3028 }
3029 }
3030
3031 // Eat the end of statement.
3032 Lex();
3033
3034 AsmToken EndToken, StartToken = getTok();
3035
3036 // Lex the macro definition.
3037 for (;;) {
3038 // Check whether we have reached the end of the file.
3039 if (getLexer().is(AsmToken::Eof))
3040 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3041
3042 // Otherwise, check whether we have reach the .endmacro.
3043 if (getLexer().is(AsmToken::Identifier) &&
3044 (getTok().getIdentifier() == ".endm" ||
3045 getTok().getIdentifier() == ".endmacro")) {
3046 EndToken = getTok();
3047 Lex();
3048 if (getLexer().isNot(AsmToken::EndOfStatement))
3049 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3050 "' directive");
3051 break;
3052 }
3053
3054 // Otherwise, scan til the end of the statement.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003055 eatToEndOfStatement();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003056 }
3057
3058 if (LookupMacro(Name)) {
3059 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3060 }
3061
3062 const char *BodyStart = StartToken.getLoc().getPointer();
3063 const char *BodyEnd = EndToken.getLoc().getPointer();
3064 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Kevin Enderby221514e2013-01-22 21:44:53 +00003065 CheckForBadMacro(DirectiveLoc, Name, Body, Parameters);
Eli Bendersky6ee13082013-01-15 22:59:42 +00003066 DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3067 return false;
3068}
3069
Kevin Enderby221514e2013-01-22 21:44:53 +00003070/// CheckForBadMacro
3071///
3072/// With the support added for named parameters there may be code out there that
3073/// is transitioning from positional parameters. In versions of gas that did
3074/// not support named parameters they would be ignored on the macro defintion.
3075/// But to support both styles of parameters this is not possible so if a macro
3076/// defintion has named parameters but does not use them and has what appears
3077/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3078/// warning that the positional parameter found in body which have no effect.
3079/// Hoping the developer will either remove the named parameters from the macro
3080/// definiton so the positional parameters get used if that was what was
3081/// intended or change the macro to use the named parameters. It is possible
3082/// this warning will trigger when the none of the named parameters are used
3083/// and the strings like $1 are infact to simply to be passed trough unchanged.
3084void AsmParser::CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3085 StringRef Body,
3086 MCAsmMacroParameters Parameters) {
3087 // If this macro is not defined with named parameters the warning we are
3088 // checking for here doesn't apply.
3089 unsigned NParameters = Parameters.size();
3090 if (NParameters == 0)
3091 return;
3092
3093 bool NamedParametersFound = false;
3094 bool PositionalParametersFound = false;
3095
3096 // Look at the body of the macro for use of both the named parameters and what
3097 // are likely to be positional parameters. This is what expandMacro() is
3098 // doing when it finds the parameters in the body.
3099 while (!Body.empty()) {
3100 // Scan for the next possible parameter.
3101 std::size_t End = Body.size(), Pos = 0;
3102 for (; Pos != End; ++Pos) {
3103 // Check for a substitution or escape.
3104 // This macro is defined with parameters, look for \foo, \bar, etc.
3105 if (Body[Pos] == '\\' && Pos + 1 != End)
3106 break;
3107
3108 // This macro should have parameters, but look for $0, $1, ..., $n too.
3109 if (Body[Pos] != '$' || Pos + 1 == End)
3110 continue;
3111 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00003112 if (Next == '$' || Next == 'n' ||
3113 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby221514e2013-01-22 21:44:53 +00003114 break;
3115 }
3116
3117 // Check if we reached the end.
3118 if (Pos == End)
3119 break;
3120
3121 if (Body[Pos] == '$') {
3122 switch (Body[Pos+1]) {
3123 // $$ => $
3124 case '$':
3125 break;
3126
3127 // $n => number of arguments
3128 case 'n':
3129 PositionalParametersFound = true;
3130 break;
3131
3132 // $[0-9] => argument
3133 default: {
3134 PositionalParametersFound = true;
3135 break;
3136 }
3137 }
3138 Pos += 2;
3139 } else {
3140 unsigned I = Pos + 1;
3141 while (isIdentifierChar(Body[I]) && I + 1 != End)
3142 ++I;
3143
3144 const char *Begin = Body.data() + Pos +1;
3145 StringRef Argument(Begin, I - (Pos +1));
3146 unsigned Index = 0;
3147 for (; Index < NParameters; ++Index)
3148 if (Parameters[Index].first == Argument)
3149 break;
3150
3151 if (Index == NParameters) {
3152 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
3153 Pos += 3;
3154 else {
3155 Pos = I;
3156 }
3157 } else {
3158 NamedParametersFound = true;
3159 Pos += 1 + Argument.size();
3160 }
3161 }
3162 // Update the scan point.
3163 Body = Body.substr(Pos);
3164 }
3165
3166 if (!NamedParametersFound && PositionalParametersFound)
3167 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3168 "used in macro body, possible positional parameter "
3169 "found in body which will have no effect");
3170}
3171
Eli Bendersky6ee13082013-01-15 22:59:42 +00003172/// ParseDirectiveEndMacro
3173/// ::= .endm
3174/// ::= .endmacro
3175bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
3176 if (getLexer().isNot(AsmToken::EndOfStatement))
3177 return TokError("unexpected token in '" + Directive + "' directive");
3178
3179 // If we are inside a macro instantiation, terminate the current
3180 // instantiation.
3181 if (InsideMacroInstantiation()) {
3182 HandleMacroExit();
3183 return false;
3184 }
3185
3186 // Otherwise, this .endmacro is a stray entry in the file; well formed
3187 // .endmacro directives are handled during the macro definition parsing.
3188 return TokError("unexpected '" + Directive + "' in file, "
3189 "no current macro definition");
3190}
3191
3192/// ParseDirectivePurgeMacro
3193/// ::= .purgem
3194bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3195 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003196 if (parseIdentifier(Name))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003197 return TokError("expected identifier in '.purgem' directive");
3198
3199 if (getLexer().isNot(AsmToken::EndOfStatement))
3200 return TokError("unexpected token in '.purgem' directive");
3201
3202 if (!LookupMacro(Name))
3203 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3204
3205 UndefineMacro(Name);
3206 return false;
3207}
Eli Bendersky4766ef42012-12-20 19:05:53 +00003208
3209/// ParseDirectiveBundleAlignMode
3210/// ::= {.bundle_align_mode} expression
3211bool AsmParser::ParseDirectiveBundleAlignMode() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003212 checkForValidSection();
Eli Bendersky4766ef42012-12-20 19:05:53 +00003213
3214 // Expect a single argument: an expression that evaluates to a constant
3215 // in the inclusive range 0-30.
3216 SMLoc ExprLoc = getLexer().getLoc();
3217 int64_t AlignSizePow2;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003218 if (parseAbsoluteExpression(AlignSizePow2))
Eli Bendersky4766ef42012-12-20 19:05:53 +00003219 return true;
3220 else if (getLexer().isNot(AsmToken::EndOfStatement))
3221 return TokError("unexpected token after expression in"
3222 " '.bundle_align_mode' directive");
3223 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3224 return Error(ExprLoc,
3225 "invalid bundle alignment size (expected between 0 and 30)");
3226
3227 Lex();
3228
3229 // Because of AlignSizePow2's verified range we can safely truncate it to
3230 // unsigned.
3231 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3232 return false;
3233}
3234
3235/// ParseDirectiveBundleLock
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003236/// ::= {.bundle_lock} [align_to_end]
Eli Bendersky4766ef42012-12-20 19:05:53 +00003237bool AsmParser::ParseDirectiveBundleLock() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003238 checkForValidSection();
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003239 bool AlignToEnd = false;
Eli Bendersky4766ef42012-12-20 19:05:53 +00003240
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003241 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3242 StringRef Option;
3243 SMLoc Loc = getTok().getLoc();
3244 const char *kInvalidOptionError =
3245 "invalid option for '.bundle_lock' directive";
3246
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003247 if (parseIdentifier(Option))
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003248 return Error(Loc, kInvalidOptionError);
3249
3250 if (Option != "align_to_end")
3251 return Error(Loc, kInvalidOptionError);
3252 else if (getLexer().isNot(AsmToken::EndOfStatement))
3253 return Error(Loc,
3254 "unexpected token after '.bundle_lock' directive option");
3255 AlignToEnd = true;
3256 }
3257
Eli Bendersky4766ef42012-12-20 19:05:53 +00003258 Lex();
3259
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003260 getStreamer().EmitBundleLock(AlignToEnd);
Eli Bendersky4766ef42012-12-20 19:05:53 +00003261 return false;
3262}
3263
3264/// ParseDirectiveBundleLock
3265/// ::= {.bundle_lock}
3266bool AsmParser::ParseDirectiveBundleUnlock() {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003267 checkForValidSection();
Eli Bendersky4766ef42012-12-20 19:05:53 +00003268
3269 if (getLexer().isNot(AsmToken::EndOfStatement))
3270 return TokError("unexpected token in '.bundle_unlock' directive");
3271 Lex();
3272
3273 getStreamer().EmitBundleUnlock();
3274 return false;
3275}
3276
Eli Bendersky6ee13082013-01-15 22:59:42 +00003277/// ParseDirectiveSpace
3278/// ::= (.skip | .space) expression [ , expression ]
3279bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003280 checkForValidSection();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003281
3282 int64_t NumBytes;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003283 if (parseAbsoluteExpression(NumBytes))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003284 return true;
3285
3286 int64_t FillExpr = 0;
3287 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3288 if (getLexer().isNot(AsmToken::Comma))
3289 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3290 Lex();
3291
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003292 if (parseAbsoluteExpression(FillExpr))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003293 return true;
3294
3295 if (getLexer().isNot(AsmToken::EndOfStatement))
3296 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3297 }
3298
3299 Lex();
3300
3301 if (NumBytes <= 0)
3302 return TokError("invalid number of bytes in '" +
3303 Twine(IDVal) + "' directive");
3304
3305 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3306 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
3307
3308 return false;
3309}
3310
3311/// ParseDirectiveLEB128
3312/// ::= (.sleb128 | .uleb128) expression
3313bool AsmParser::ParseDirectiveLEB128(bool Signed) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003314 checkForValidSection();
Eli Bendersky6ee13082013-01-15 22:59:42 +00003315 const MCExpr *Value;
3316
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003317 if (parseExpression(Value))
Eli Bendersky6ee13082013-01-15 22:59:42 +00003318 return true;
3319
3320 if (getLexer().isNot(AsmToken::EndOfStatement))
3321 return TokError("unexpected token in directive");
3322
3323 if (Signed)
3324 getStreamer().EmitSLEB128Value(Value);
3325 else
3326 getStreamer().EmitULEB128Value(Value);
3327
3328 return false;
3329}
3330
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003331/// ParseDirectiveSymbolAttribute
3332/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00003333bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003334 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003335 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003336 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00003337 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003338
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003339 if (parseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00003340 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003341
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003342 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003343
Jim Grosbach10ec6502011-09-15 17:56:49 +00003344 // Assembler local symbols don't make any sense here. Complain loudly.
3345 if (Sym->isTemporary())
3346 return Error(Loc, "non-local symbol required in directive");
3347
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003348 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003349
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003350 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003351 break;
3352
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003353 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003354 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003355 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003356 }
3357 }
3358
Sean Callanan79ed1a82010-01-19 20:22:31 +00003359 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00003360 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003361}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003362
3363/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00003364/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3365bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003366 checkForValidSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00003367
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003368 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003369 StringRef Name;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003370 if (parseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003371 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003372
Daniel Dunbar76c4d762009-07-31 21:55:09 +00003373 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003374 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003375
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003376 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003377 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003378 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003379
3380 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003381 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003382 if (parseAbsoluteExpression(Size))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003383 return true;
3384
3385 int64_t Pow2Alignment = 0;
3386 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003387 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00003388 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003389 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003390 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003391 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003392
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003393 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3394 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00003395 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3396
Chris Lattner258281d2010-01-19 06:22:22 +00003397 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003398 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3399 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00003400 if (!isPowerOf2_64(Pow2Alignment))
3401 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3402 Pow2Alignment = Log2_64(Pow2Alignment);
3403 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003404 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003405
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003406 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00003407 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003408
Sean Callanan79ed1a82010-01-19 20:22:31 +00003409 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003410
Chris Lattner1fc3d752009-07-09 17:25:12 +00003411 // NOTE: a size of zero for a .comm should create a undefined symbol
3412 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003413 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003414 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3415 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003416
Eric Christopherc260a3e2010-05-14 01:38:54 +00003417 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003418 // may internally end up wanting an alignment in bytes.
3419 // FIXME: Diagnose overflow.
3420 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003421 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3422 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003423
Daniel Dunbar8906ff12009-08-22 07:22:36 +00003424 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003425 return Error(IDLoc, "invalid symbol redefinition");
3426
Chris Lattner1fc3d752009-07-09 17:25:12 +00003427 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003428 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00003429 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003430 return false;
3431 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003432
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003433 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003434 return false;
3435}
Chris Lattner9be3fee2009-07-10 22:20:30 +00003436
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003437/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003438/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003439bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003440 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003441 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003442
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003443 StringRef Str = parseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003444 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003445 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003446
Sean Callanan79ed1a82010-01-19 20:22:31 +00003447 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003448
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003449 if (Str.empty())
3450 Error(Loc, ".abort detected. Assembly stopping.");
3451 else
3452 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003453 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003454
3455 return false;
3456}
Kevin Enderby71148242009-07-14 21:35:03 +00003457
Kevin Enderby1f049b22009-07-14 23:21:55 +00003458/// ParseDirectiveInclude
3459/// ::= .include "filename"
3460bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003461 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003462 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003463
Sean Callanan18b83232010-01-19 21:44:56 +00003464 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003465 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00003466 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00003467
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003468 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003469 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003470
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003471 // Strip the quotes.
3472 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003473
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003474 // Attempt to switch the lexer to the included file before consuming the end
3475 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00003476 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00003477 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003478 return true;
3479 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00003480
3481 return false;
3482}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00003483
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003484/// ParseDirectiveIncbin
3485/// ::= .incbin "filename"
3486bool AsmParser::ParseDirectiveIncbin() {
3487 if (getLexer().isNot(AsmToken::String))
3488 return TokError("expected string in '.incbin' directive");
3489
3490 std::string Filename = getTok().getString();
3491 SMLoc IncbinLoc = getLexer().getLoc();
3492 Lex();
3493
3494 if (getLexer().isNot(AsmToken::EndOfStatement))
3495 return TokError("unexpected token in '.incbin' directive");
3496
3497 // Strip the quotes.
3498 Filename = Filename.substr(1, Filename.size()-2);
3499
3500 // Attempt to process the included file.
3501 if (ProcessIncbinFile(Filename)) {
3502 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3503 return true;
3504 }
3505
3506 return false;
3507}
3508
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003509/// ParseDirectiveIf
3510/// ::= .if expression
3511bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003512 TheCondStack.push_back(TheCondState);
3513 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00003514 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003515 eatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00003516 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003517 int64_t ExprValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003518 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003519 return true;
3520
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003521 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003522 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003523
Sean Callanan79ed1a82010-01-19 20:22:31 +00003524 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003525
3526 TheCondState.CondMet = ExprValue;
3527 TheCondState.Ignore = !TheCondState.CondMet;
3528 }
3529
3530 return false;
3531}
3532
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003533/// ParseDirectiveIfb
3534/// ::= .ifb string
3535bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3536 TheCondStack.push_back(TheCondState);
3537 TheCondState.TheCond = AsmCond::IfCond;
3538
Benjamin Kramer29739e72012-05-12 16:52:21 +00003539 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003540 eatToEndOfStatement();
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003541 } else {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003542 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003543
3544 if (getLexer().isNot(AsmToken::EndOfStatement))
3545 return TokError("unexpected token in '.ifb' directive");
3546
3547 Lex();
3548
3549 TheCondState.CondMet = ExpectBlank == Str.empty();
3550 TheCondState.Ignore = !TheCondState.CondMet;
3551 }
3552
3553 return false;
3554}
3555
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003556/// ParseDirectiveIfc
3557/// ::= .ifc string1, string2
3558bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3559 TheCondStack.push_back(TheCondState);
3560 TheCondState.TheCond = AsmCond::IfCond;
3561
Benjamin Kramer29739e72012-05-12 16:52:21 +00003562 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003563 eatToEndOfStatement();
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003564 } else {
3565 StringRef Str1 = ParseStringToComma();
3566
3567 if (getLexer().isNot(AsmToken::Comma))
3568 return TokError("unexpected token in '.ifc' directive");
3569
3570 Lex();
3571
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003572 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003573
3574 if (getLexer().isNot(AsmToken::EndOfStatement))
3575 return TokError("unexpected token in '.ifc' directive");
3576
3577 Lex();
3578
3579 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3580 TheCondState.Ignore = !TheCondState.CondMet;
3581 }
3582
3583 return false;
3584}
3585
3586/// ParseDirectiveIfdef
3587/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003588bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3589 StringRef Name;
3590 TheCondStack.push_back(TheCondState);
3591 TheCondState.TheCond = AsmCond::IfCond;
3592
3593 if (TheCondState.Ignore) {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003594 eatToEndOfStatement();
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003595 } else {
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003596 if (parseIdentifier(Name))
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003597 return TokError("expected identifier after '.ifdef'");
3598
3599 Lex();
3600
3601 MCSymbol *Sym = getContext().LookupSymbol(Name);
3602
3603 if (expect_defined)
3604 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3605 else
3606 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3607 TheCondState.Ignore = !TheCondState.CondMet;
3608 }
3609
3610 return false;
3611}
3612
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003613/// ParseDirectiveElseIf
3614/// ::= .elseif expression
3615bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
3616 if (TheCondState.TheCond != AsmCond::IfCond &&
3617 TheCondState.TheCond != AsmCond::ElseIfCond)
3618 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3619 " an .elseif");
3620 TheCondState.TheCond = AsmCond::ElseIfCond;
3621
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003622 bool LastIgnoreState = false;
3623 if (!TheCondStack.empty())
3624 LastIgnoreState = TheCondStack.back().Ignore;
3625 if (LastIgnoreState || TheCondState.CondMet) {
3626 TheCondState.Ignore = true;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003627 eatToEndOfStatement();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003628 }
3629 else {
3630 int64_t ExprValue;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003631 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003632 return true;
3633
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003634 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003635 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003636
Sean Callanan79ed1a82010-01-19 20:22:31 +00003637 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003638 TheCondState.CondMet = ExprValue;
3639 TheCondState.Ignore = !TheCondState.CondMet;
3640 }
3641
3642 return false;
3643}
3644
3645/// ParseDirectiveElse
3646/// ::= .else
3647bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003648 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003649 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003650
Sean Callanan79ed1a82010-01-19 20:22:31 +00003651 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003652
3653 if (TheCondState.TheCond != AsmCond::IfCond &&
3654 TheCondState.TheCond != AsmCond::ElseIfCond)
3655 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3656 ".elseif");
3657 TheCondState.TheCond = AsmCond::ElseCond;
3658 bool LastIgnoreState = false;
3659 if (!TheCondStack.empty())
3660 LastIgnoreState = TheCondStack.back().Ignore;
3661 if (LastIgnoreState || TheCondState.CondMet)
3662 TheCondState.Ignore = true;
3663 else
3664 TheCondState.Ignore = false;
3665
3666 return false;
3667}
3668
3669/// ParseDirectiveEndIf
3670/// ::= .endif
3671bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003672 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003673 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003674
Sean Callanan79ed1a82010-01-19 20:22:31 +00003675 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003676
3677 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3678 TheCondStack.empty())
3679 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3680 ".else");
3681 if (!TheCondStack.empty()) {
3682 TheCondState = TheCondStack.back();
3683 TheCondStack.pop_back();
3684 }
3685
3686 return false;
3687}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003688
Eli Bendersky6ee13082013-01-15 22:59:42 +00003689void AsmParser::initializeDirectiveKindMap() {
3690 DirectiveKindMap[".set"] = DK_SET;
3691 DirectiveKindMap[".equ"] = DK_EQU;
3692 DirectiveKindMap[".equiv"] = DK_EQUIV;
3693 DirectiveKindMap[".ascii"] = DK_ASCII;
3694 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3695 DirectiveKindMap[".string"] = DK_STRING;
3696 DirectiveKindMap[".byte"] = DK_BYTE;
3697 DirectiveKindMap[".short"] = DK_SHORT;
3698 DirectiveKindMap[".value"] = DK_VALUE;
3699 DirectiveKindMap[".2byte"] = DK_2BYTE;
3700 DirectiveKindMap[".long"] = DK_LONG;
3701 DirectiveKindMap[".int"] = DK_INT;
3702 DirectiveKindMap[".4byte"] = DK_4BYTE;
3703 DirectiveKindMap[".quad"] = DK_QUAD;
3704 DirectiveKindMap[".8byte"] = DK_8BYTE;
3705 DirectiveKindMap[".single"] = DK_SINGLE;
3706 DirectiveKindMap[".float"] = DK_FLOAT;
3707 DirectiveKindMap[".double"] = DK_DOUBLE;
3708 DirectiveKindMap[".align"] = DK_ALIGN;
3709 DirectiveKindMap[".align32"] = DK_ALIGN32;
3710 DirectiveKindMap[".balign"] = DK_BALIGN;
3711 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3712 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3713 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3714 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3715 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3716 DirectiveKindMap[".org"] = DK_ORG;
3717 DirectiveKindMap[".fill"] = DK_FILL;
3718 DirectiveKindMap[".zero"] = DK_ZERO;
3719 DirectiveKindMap[".extern"] = DK_EXTERN;
3720 DirectiveKindMap[".globl"] = DK_GLOBL;
3721 DirectiveKindMap[".global"] = DK_GLOBAL;
3722 DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
3723 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3724 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3725 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3726 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3727 DirectiveKindMap[".reference"] = DK_REFERENCE;
3728 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3729 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3730 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3731 DirectiveKindMap[".comm"] = DK_COMM;
3732 DirectiveKindMap[".common"] = DK_COMMON;
3733 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3734 DirectiveKindMap[".abort"] = DK_ABORT;
3735 DirectiveKindMap[".include"] = DK_INCLUDE;
3736 DirectiveKindMap[".incbin"] = DK_INCBIN;
3737 DirectiveKindMap[".code16"] = DK_CODE16;
3738 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3739 DirectiveKindMap[".rept"] = DK_REPT;
3740 DirectiveKindMap[".irp"] = DK_IRP;
3741 DirectiveKindMap[".irpc"] = DK_IRPC;
3742 DirectiveKindMap[".endr"] = DK_ENDR;
3743 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3744 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3745 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3746 DirectiveKindMap[".if"] = DK_IF;
3747 DirectiveKindMap[".ifb"] = DK_IFB;
3748 DirectiveKindMap[".ifnb"] = DK_IFNB;
3749 DirectiveKindMap[".ifc"] = DK_IFC;
3750 DirectiveKindMap[".ifnc"] = DK_IFNC;
3751 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3752 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3753 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3754 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3755 DirectiveKindMap[".else"] = DK_ELSE;
3756 DirectiveKindMap[".endif"] = DK_ENDIF;
3757 DirectiveKindMap[".skip"] = DK_SKIP;
3758 DirectiveKindMap[".space"] = DK_SPACE;
3759 DirectiveKindMap[".file"] = DK_FILE;
3760 DirectiveKindMap[".line"] = DK_LINE;
3761 DirectiveKindMap[".loc"] = DK_LOC;
3762 DirectiveKindMap[".stabs"] = DK_STABS;
3763 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3764 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3765 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3766 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3767 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3768 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3769 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3770 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3771 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3772 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3773 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3774 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3775 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3776 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3777 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3778 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3779 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3780 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3781 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3782 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3783 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3784 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3785 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3786 DirectiveKindMap[".macro"] = DK_MACRO;
3787 DirectiveKindMap[".endm"] = DK_ENDM;
3788 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3789 DirectiveKindMap[".purgem"] = DK_PURGEM;
Eli Bendersky5d0f0612013-01-10 22:44:57 +00003790}
3791
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003792
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003793MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003794 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003795
Rafael Espindola761cb062012-06-03 23:57:14 +00003796 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003797 for (;;) {
3798 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003799 if (getLexer().is(AsmToken::Eof)) {
3800 Error(DirectiveLoc, "no matching '.endr' in definition");
3801 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003802 }
3803
Rafael Espindola761cb062012-06-03 23:57:14 +00003804 if (Lexer.is(AsmToken::Identifier) &&
3805 (getTok().getIdentifier() == ".rept")) {
3806 ++NestLevel;
3807 }
3808
3809 // Otherwise, check whether we have reached the .endr.
3810 if (Lexer.is(AsmToken::Identifier) &&
3811 getTok().getIdentifier() == ".endr") {
3812 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003813 EndToken = getTok();
3814 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003815 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3816 TokError("unexpected token in '.endr' directive");
3817 return 0;
3818 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003819 break;
3820 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003821 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003822 }
3823
Rafael Espindola761cb062012-06-03 23:57:14 +00003824 // Otherwise, scan till the end of the statement.
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003825 eatToEndOfStatement();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003826 }
3827
3828 const char *BodyStart = StartToken.getLoc().getPointer();
3829 const char *BodyEnd = EndToken.getLoc().getPointer();
3830 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3831
Rafael Espindola761cb062012-06-03 23:57:14 +00003832 // We Are Anonymous.
3833 StringRef Name;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003834 MCAsmMacroParameters Parameters;
3835 return new MCAsmMacro(Name, Body, Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +00003836}
3837
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003838void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +00003839 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003840 OS << ".endr\n";
3841
3842 MemoryBuffer *Instantiation =
3843 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3844
Rafael Espindola761cb062012-06-03 23:57:14 +00003845 // Create the macro instantiation object and add to the current macro
3846 // instantiation stack.
3847 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003848 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003849 getTok().getLoc(),
3850 Instantiation);
3851 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003852
Rafael Espindola761cb062012-06-03 23:57:14 +00003853 // Jump to the macro instantiation and prime the lexer.
3854 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3855 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3856 Lex();
3857}
3858
3859bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3860 int64_t Count;
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003861 if (parseAbsoluteExpression(Count))
Rafael Espindola761cb062012-06-03 23:57:14 +00003862 return TokError("unexpected token in '.rept' directive");
3863
3864 if (Count < 0)
3865 return TokError("Count is negative");
3866
3867 if (Lexer.isNot(AsmToken::EndOfStatement))
3868 return TokError("unexpected token in '.rept' directive");
3869
3870 // Eat the end of statement.
3871 Lex();
3872
3873 // Lex the rept definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003874 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindola761cb062012-06-03 23:57:14 +00003875 if (!M)
3876 return true;
3877
3878 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3879 // to hold the macro body with substitutions.
3880 SmallString<256> Buf;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003881 MCAsmMacroParameters Parameters;
3882 MCAsmMacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003883 raw_svector_ostream OS(Buf);
3884 while (Count--) {
3885 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3886 return true;
3887 }
3888 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003889
3890 return false;
3891}
3892
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003893/// ParseDirectiveIrp
3894/// ::= .irp symbol,values
3895bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003896 MCAsmMacroParameters Parameters;
3897 MCAsmMacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003898
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003899 if (parseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003900 return TokError("expected identifier in '.irp' directive");
3901
3902 Parameters.push_back(Parameter);
3903
3904 if (Lexer.isNot(AsmToken::Comma))
3905 return TokError("expected comma in '.irp' directive");
3906
3907 Lex();
3908
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003909 MCAsmMacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003910 if (ParseMacroArguments(0, A))
3911 return true;
3912
3913 // Eat the end of statement.
3914 Lex();
3915
3916 // Lex the irp definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003917 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003918 if (!M)
3919 return true;
3920
3921 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3922 // to hold the macro body with substitutions.
3923 SmallString<256> Buf;
3924 raw_svector_ostream OS(Buf);
3925
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003926 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3927 MCAsmMacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003928 Args.push_back(*i);
3929
3930 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3931 return true;
3932 }
3933
3934 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3935
3936 return false;
3937}
3938
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003939/// ParseDirectiveIrpc
3940/// ::= .irpc symbol,values
3941bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003942 MCAsmMacroParameters Parameters;
3943 MCAsmMacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003944
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00003945 if (parseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003946 return TokError("expected identifier in '.irpc' directive");
3947
3948 Parameters.push_back(Parameter);
3949
3950 if (Lexer.isNot(AsmToken::Comma))
3951 return TokError("expected comma in '.irpc' directive");
3952
3953 Lex();
3954
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003955 MCAsmMacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003956 if (ParseMacroArguments(0, A))
3957 return true;
3958
3959 if (A.size() != 1 || A.front().size() != 1)
3960 return TokError("unexpected token in '.irpc' directive");
3961
3962 // Eat the end of statement.
3963 Lex();
3964
3965 // Lex the irpc definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003966 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003967 if (!M)
3968 return true;
3969
3970 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3971 // to hold the macro body with substitutions.
3972 SmallString<256> Buf;
3973 raw_svector_ostream OS(Buf);
3974
3975 StringRef Values = A.front().front().getString();
3976 std::size_t I, End = Values.size();
3977 for (I = 0; I < End; ++I) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00003978 MCAsmMacroArgument Arg;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003979 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3980
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003981 MCAsmMacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003982 Args.push_back(Arg);
3983
3984 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3985 return true;
3986 }
3987
3988 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3989
3990 return false;
3991}
3992
Rafael Espindola761cb062012-06-03 23:57:14 +00003993bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3994 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003995 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003996
3997 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003998 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003999 assert(getLexer().is(AsmToken::EndOfStatement));
4000
Rafael Espindola761cb062012-06-03 23:57:14 +00004001 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00004002 return false;
4003}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00004004
Benjamin Kramer75234372013-02-15 20:37:21 +00004005bool AsmParser::ParseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4006 size_t Len) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004007 const MCExpr *Value;
4008 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004009 if (parseExpression(Value))
Eli Friedman2128aae2012-10-22 23:58:19 +00004010 return true;
4011 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4012 if (!MCE)
4013 return Error(ExprLoc, "unexpected expression in _emit");
4014 uint64_t IntValue = MCE->getValue();
4015 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4016 return Error(ExprLoc, "literal value out of range for directive");
4017
Chad Rosier469b1442013-02-12 21:33:51 +00004018 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4019 return false;
4020}
4021
4022bool AsmParser::ParseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4023 const MCExpr *Value;
4024 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004025 if (parseExpression(Value))
Chad Rosier469b1442013-02-12 21:33:51 +00004026 return true;
4027 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4028 if (!MCE)
4029 return Error(ExprLoc, "unexpected expression in align");
4030 uint64_t IntValue = MCE->getValue();
4031 if (!isPowerOf2_64(IntValue))
4032 return Error(ExprLoc, "literal value not a power of two greater then zero");
4033
Benjamin Kramer75234372013-02-15 20:37:21 +00004034 Info.AsmRewrites->push_back(AsmRewrite(AOK_Align, IDLoc, 5,
4035 Log2_64(IntValue)));
Eli Friedman2128aae2012-10-22 23:58:19 +00004036 return false;
4037}
4038
Chad Rosier19aa3e32013-02-13 21:27:17 +00004039// We are comparing pointers, but the pointers are relative to a single string.
4040// Thus, this should always be deterministic.
Benjamin Kramer75234372013-02-15 20:37:21 +00004041static int RewritesSort(const void *A, const void *B) {
4042 const AsmRewrite *AsmRewriteA = static_cast<const AsmRewrite *>(A);
4043 const AsmRewrite *AsmRewriteB = static_cast<const AsmRewrite *>(B);
Chad Rosierabde6752013-02-13 18:38:58 +00004044 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4045 return -1;
4046 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4047 return 1;
Chad Rosierb54562b2013-02-15 22:54:16 +00004048
4049 // It's possible to have a SizeDirective rewrite and an Input/Output rewrite
4050 // to the same location. Make sure the SizeDirective rewrite is performed
4051 // first. This also ensure the sort algorithm is stable.
4052 if (AsmRewriteA->Kind == AOK_SizeDirective) {
4053 assert ((AsmRewriteB->Kind == AOK_Input || AsmRewriteB->Kind == AOK_Output) &&
4054 "Expected an Input/Output rewrite!");
4055 return -1;
4056 }
4057 if (AsmRewriteB->Kind == AOK_SizeDirective) {
4058 assert ((AsmRewriteA->Kind == AOK_Input || AsmRewriteA->Kind == AOK_Output) &&
4059 "Expected an Input/Output rewrite!");
4060 return 1;
4061 }
4062 llvm_unreachable ("Unstable rewrite sort.");
Chad Rosierb1953982013-02-13 01:03:13 +00004063}
4064
Benjamin Kramer75234372013-02-15 20:37:21 +00004065bool
Jim Grosbachcb2ae3d2013-02-20 22:21:35 +00004066AsmParser::parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Benjamin Kramer75234372013-02-15 20:37:21 +00004067 unsigned &NumOutputs, unsigned &NumInputs,
4068 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4069 SmallVectorImpl<std::string> &Constraints,
4070 SmallVectorImpl<std::string> &Clobbers,
4071 const MCInstrInfo *MII,
4072 const MCInstPrinter *IP,
4073 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004074 SmallVector<void *, 4> InputDecls;
4075 SmallVector<void *, 4> OutputDecls;
Chad Rosierc1ec2072013-01-10 22:10:27 +00004076 SmallVector<bool, 4> InputDeclsAddressOf;
4077 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004078 SmallVector<std::string, 4> InputConstraints;
4079 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer75234372013-02-15 20:37:21 +00004080 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004081
Benjamin Kramer75234372013-02-15 20:37:21 +00004082 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004083
4084 // Prime the lexer.
4085 Lex();
4086
4087 // While we have input, parse each statement.
4088 unsigned InputIdx = 0;
4089 unsigned OutputIdx = 0;
4090 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004091 ParseStatementInfo Info(&AsmStrRewrites);
4092 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00004093 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004094
Chad Rosier57498012012-12-12 22:45:52 +00004095 if (Info.ParseError)
4096 return true;
4097
Benjamin Kramer75234372013-02-15 20:37:21 +00004098 if (Info.Opcode == ~0U)
4099 continue;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004100
Benjamin Kramer75234372013-02-15 20:37:21 +00004101 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004102
Benjamin Kramer75234372013-02-15 20:37:21 +00004103 // Build the list of clobbers, outputs and inputs.
4104 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4105 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004106
Benjamin Kramer75234372013-02-15 20:37:21 +00004107 // Immediate.
Chad Rosier811ddf62013-03-19 21:58:18 +00004108 if (Operand->isImm())
Benjamin Kramer75234372013-02-15 20:37:21 +00004109 continue;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004110
Benjamin Kramer75234372013-02-15 20:37:21 +00004111 // Register operand.
4112 if (Operand->isReg() && !Operand->needAddressOf()) {
4113 unsigned NumDefs = Desc.getNumDefs();
4114 // Clobber.
4115 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4116 ClobberRegs.push_back(Operand->getReg());
4117 continue;
4118 }
4119
4120 // Expr/Input or Output.
4121 bool IsVarDecl;
4122 unsigned Length, Size, Type;
4123 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
4124 Length, Size, Type,
4125 IsVarDecl);
4126 if (!OpDecl)
4127 continue;
4128
4129 bool isOutput = (i == 1) && Desc.mayStore();
Benjamin Kramer75234372013-02-15 20:37:21 +00004130 if (isOutput) {
4131 ++InputIdx;
4132 OutputDecls.push_back(OpDecl);
4133 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4134 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4135 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Operand->getStartLoc(),
4136 Operand->getNameLen()));
4137 } else {
4138 InputDecls.push_back(OpDecl);
4139 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4140 InputConstraints.push_back(Operand->getConstraint().str());
4141 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Operand->getStartLoc(),
4142 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00004143 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004144 }
4145 }
4146
4147 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004148 NumOutputs = OutputDecls.size();
4149 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00004150
4151 // Set the unique clobbers.
Benjamin Kramer75234372013-02-15 20:37:21 +00004152 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4153 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4154 ClobberRegs.end());
4155 Clobbers.assign(ClobberRegs.size(), std::string());
4156 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4157 raw_string_ostream OS(Clobbers[I]);
4158 IP->printRegName(OS, ClobberRegs[I]);
4159 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004160
4161 // Merge the various outputs and inputs. Output are expected first.
4162 if (NumOutputs || NumInputs) {
4163 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004164 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004165 Constraints.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004166 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004167 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004168 Constraints[i] = OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004169 }
4170 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004171 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004172 Constraints[j] = InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004173 }
4174 }
4175
4176 // Build the IR assembly string.
4177 std::string AsmStringIR;
4178 raw_string_ostream OS(AsmStringIR);
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004179 const char *AsmStart = SrcMgr.getMemoryBuffer(0)->getBufferStart();
4180 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
Benjamin Kramer75234372013-02-15 20:37:21 +00004181 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), RewritesSort);
4182 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4183 E = AsmStrRewrites.end();
4184 I != E; ++I) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00004185 const char *Loc = (*I).Loc.getPointer();
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004186 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier96d58e62012-10-19 20:57:14 +00004187
Chad Rosier469b1442013-02-12 21:33:51 +00004188 unsigned AdditionalSkip = 0;
Chad Rosier4e472d22012-10-20 01:02:45 +00004189 AsmRewriteKind Kind = (*I).Kind;
Chad Rosier96d58e62012-10-19 20:57:14 +00004190
Chad Rosier023c8802013-03-19 17:32:17 +00004191 // Emit everything up to the immediate/expression.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004192 unsigned Len = Loc - AsmStart;
4193 if (Len) {
4194 // For Input/Output operands we need to remove the brackets, if present.
4195 if ((Kind == AOK_Input || Kind == AOK_Output) && Loc[-1] == '[')
4196 --Len;
4197 OS << StringRef(AsmStart, Len);
4198 }
Chad Rosier96d58e62012-10-19 20:57:14 +00004199
Chad Rosier5a719fc2012-10-23 17:43:43 +00004200 // Skip the original expression.
4201 if (Kind == AOK_Skip) {
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004202 AsmStart = Loc + (*I).Len;
Chad Rosier5a719fc2012-10-23 17:43:43 +00004203 continue;
4204 }
4205
Chad Rosierb1f8c132012-10-18 15:49:34 +00004206 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00004207 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004208 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004209 case AOK_Imm:
Benjamin Kramer75234372013-02-15 20:37:21 +00004210 OS << "$$" << (*I).Val;
Chad Rosierefcb3d92012-10-26 18:04:20 +00004211 break;
4212 case AOK_ImmPrefix:
Benjamin Kramer75234372013-02-15 20:37:21 +00004213 OS << "$$";
Chad Rosierb1f8c132012-10-18 15:49:34 +00004214 break;
4215 case AOK_Input:
Benjamin Kramer75234372013-02-15 20:37:21 +00004216 OS << '$' << InputIdx++;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004217 break;
4218 case AOK_Output:
Benjamin Kramer75234372013-02-15 20:37:21 +00004219 OS << '$' << OutputIdx++;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004220 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00004221 case AOK_SizeDirective:
Benjamin Kramer75234372013-02-15 20:37:21 +00004222 switch ((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00004223 default: break;
4224 case 8: OS << "byte ptr "; break;
4225 case 16: OS << "word ptr "; break;
4226 case 32: OS << "dword ptr "; break;
4227 case 64: OS << "qword ptr "; break;
4228 case 80: OS << "xword ptr "; break;
4229 case 128: OS << "xmmword ptr "; break;
4230 case 256: OS << "ymmword ptr "; break;
4231 }
Eli Friedman2128aae2012-10-22 23:58:19 +00004232 break;
4233 case AOK_Emit:
4234 OS << ".byte";
4235 break;
Chad Rosier469b1442013-02-12 21:33:51 +00004236 case AOK_Align: {
4237 unsigned Val = (*I).Val;
4238 OS << ".align " << Val;
4239
4240 // Skip the original immediate.
Benjamin Kramer75234372013-02-15 20:37:21 +00004241 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosier469b1442013-02-12 21:33:51 +00004242 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4243 break;
4244 }
Chad Rosier6a020a72012-10-25 20:41:34 +00004245 case AOK_DotOperator:
4246 OS << (*I).Val;
4247 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004248 }
Chad Rosier96d58e62012-10-19 20:57:14 +00004249
Chad Rosierb1f8c132012-10-18 15:49:34 +00004250 // Skip the original expression.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004251 AsmStart = Loc + (*I).Len + AdditionalSkip;
4252
4253 // For Input/Output operands we need to remove the brackets, if present.
4254 if ((Kind == AOK_Input || Kind == AOK_Output) && AsmStart != AsmEnd &&
4255 *AsmStart == ']')
4256 ++AsmStart;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004257 }
4258
4259 // Emit the remainder of the asm string.
Chad Rosier0f7ccd22013-03-19 21:12:14 +00004260 if (AsmStart != AsmEnd)
4261 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004262
4263 AsmString = OS.str();
4264 return false;
4265}
4266
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004267/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004268MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004269 MCContext &C, MCStreamer &Out,
4270 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004271 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004272}