blob: a5d0666317648c00f71a26596c277b47d0d47ef3 [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"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000016#include "llvm/ADT/StringMap.h"
Daniel Dunbarf9507ff2009-07-27 23:20:52 +000017#include "llvm/ADT/Twine.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000018#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000019#include "llvm/MC/MCContext.h"
Evan Cheng94b95502011-07-26 00:24:13 +000020#include "llvm/MC/MCDwarf.h"
Daniel Dunbar28c251b2009-08-31 08:06:59 +000021#include "llvm/MC/MCExpr.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000022#include "llvm/MC/MCParser/AsmCond.h"
23#include "llvm/MC/MCParser/AsmLexer.h"
24#include "llvm/MC/MCParser/MCAsmParser.h"
25#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Evan Chenge76a33b2011-07-20 05:58:47 +000026#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000027#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000028#include "llvm/MC/MCStreamer.h"
Daniel Dunbardce0f3c2009-06-29 23:43:14 +000029#include "llvm/MC/MCSymbol.h"
Evan Cheng94b95502011-07-26 00:24:13 +000030#include "llvm/MC/MCTargetAsmParser.h"
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000031#include "llvm/Support/CommandLine.h"
Benjamin Kramer518ff562012-01-28 15:28:41 +000032#include "llvm/Support/ErrorHandling.h"
Jim Grosbach254cf032011-06-29 16:05:14 +000033#include "llvm/Support/MathExtras.h"
Kevin Enderbyf187ac52010-06-28 21:45:58 +000034#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000035#include "llvm/Support/SourceMgr.h"
Chris Lattnerb0789ed2009-06-21 20:54:55 +000036#include "llvm/Support/raw_ostream.h"
Nick Lewycky476b2422010-12-19 20:43:38 +000037#include <cctype>
Daniel Dunbaraef87e32010-07-18 18:31:38 +000038#include <vector>
Chris Lattner27aa7d22009-06-21 20:16:42 +000039using namespace llvm;
40
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000041static cl::opt<bool>
42FatalAssemblerWarnings("fatal-assembler-warnings",
43 cl::desc("Consider warnings as error"));
44
Daniel Dunbar81ea00f2010-07-12 17:54:38 +000045namespace {
46
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000047/// \brief Helper class for tracking macro definitions.
Rafael Espindola28c1f6662012-06-03 22:41:23 +000048typedef std::vector<AsmToken> MacroArgument;
Rafael Espindola8a403d32012-08-08 14:51:03 +000049typedef std::vector<MacroArgument> MacroArguments;
Preston Gurd6c9176a2012-09-19 20:29:04 +000050typedef std::pair<StringRef, MacroArgument> MacroParameter;
Rafael Espindola8a403d32012-08-08 14:51:03 +000051typedef std::vector<MacroParameter> MacroParameters;
Rafael Espindola28c1f6662012-06-03 22:41:23 +000052
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000053struct Macro {
54 StringRef Name;
55 StringRef Body;
Rafael Espindola8a403d32012-08-08 14:51:03 +000056 MacroParameters Parameters;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000057
58public:
Rafael Espindola8a403d32012-08-08 14:51:03 +000059 Macro(StringRef N, StringRef B, const MacroParameters &P) :
Rafael Espindola65366442011-06-05 02:43:45 +000060 Name(N), Body(B), Parameters(P) {}
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000061};
62
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000063/// \brief Helper class for storing information about an active macro
64/// instantiation.
65struct MacroInstantiation {
66 /// The macro being instantiated.
67 const Macro *TheMacro;
68
69 /// The macro instantiation with substitutions.
70 MemoryBuffer *Instantiation;
71
72 /// The location of the instantiation.
73 SMLoc InstantiationLoc;
74
75 /// The location where parsing should resume upon instantiation completion.
76 SMLoc ExitLoc;
77
78public:
Daniel Dunbar7a570d02010-07-18 19:00:10 +000079 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000080 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000081};
82
Daniel Dunbaraef87e32010-07-18 18:31:38 +000083/// \brief The concrete assembly parser instance.
84class AsmParser : public MCAsmParser {
Daniel Dunbar3c802de2010-07-18 18:38:02 +000085 friend class GenericAsmParser;
86
Craig Topper85aadc02012-09-15 16:23:52 +000087 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
88 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
Daniel Dunbaraef87e32010-07-18 18:31:38 +000089private:
90 AsmLexer Lexer;
91 MCContext &Ctx;
92 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +000093 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +000094 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +000095 SourceMgr::DiagHandlerTy SavedDiagHandler;
96 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +000097 MCAsmParserExtension *GenericParser;
98 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +000099
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000100 /// This is the current buffer index we're lexing from as managed by the
101 /// SourceMgr object.
102 int CurBuffer;
103
104 AsmCond TheCondState;
105 std::vector<AsmCond> TheCondStack;
106
107 /// DirectiveMap - This is a table handlers for directives. Each handler is
108 /// invoked after the directive identifier is read and is responsible for
109 /// parsing and validating the rest of the directive. The handler is passed
110 /// in the directive name and the location of the directive keyword.
111 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000112
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000113 /// MacroMap - Map of currently defined macros.
114 StringMap<Macro*> MacroMap;
115
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000116 /// ActiveMacros - Stack of active macro instantiations.
117 std::vector<MacroInstantiation*> ActiveMacros;
118
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000119 /// Boolean tracking whether macro substitution is enabled.
120 unsigned MacrosEnabled : 1;
121
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000122 /// Flag tracking whether any errors have been encountered.
123 unsigned HadError : 1;
124
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000125 /// The values from the last parsed cpp hash file line comment if any.
126 StringRef CppHashFilename;
127 int64_t CppHashLineNumber;
128 SMLoc CppHashLoc;
129
Devang Patel0db58bf2012-01-31 18:14:05 +0000130 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
131 unsigned AssemblerDialect;
132
Preston Gurd7b6f2032012-09-19 20:36:12 +0000133 /// IsDarwin - is Darwin compatibility enabled?
134 bool IsDarwin;
135
Chad Rosier8f138d12012-10-15 17:19:13 +0000136 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000137 bool ParsingInlineAsm;
138
Chad Rosier8f138d12012-10-15 17:19:13 +0000139 /// ParsedOperands - The parsed operands from the last parsed statement.
140 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
141
142 /// Opcode - The opcode from the last parsed instruction.
143 unsigned Opcode;
144
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000145public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000146 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000147 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000148 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000149
150 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
151
Craig Topper345d16d2012-08-29 05:48:09 +0000152 virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
153 StringRef Directive,
154 DirectiveHandler Handler) {
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000155 DirectiveMap[Directive] = std::make_pair(Object, Handler);
156 }
157
158public:
159 /// @name MCAsmParser Interface
160 /// {
161
162 virtual SourceMgr &getSourceManager() { return SrcMgr; }
163 virtual MCAsmLexer &getLexer() { return Lexer; }
164 virtual MCContext &getContext() { return Ctx; }
165 virtual MCStreamer &getStreamer() { return Out; }
Devang Patel0db58bf2012-01-31 18:14:05 +0000166 virtual unsigned getAssemblerDialect() {
167 if (AssemblerDialect == ~0U)
168 return MAI.getAssemblerDialect();
169 else
170 return AssemblerDialect;
171 }
172 virtual void setAssemblerDialect(unsigned i) {
173 AssemblerDialect = i;
174 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000175
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000176 virtual bool Warning(SMLoc L, const Twine &Msg,
177 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
178 virtual bool Error(SMLoc L, const Twine &Msg,
179 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000180
Craig Topper345d16d2012-08-29 05:48:09 +0000181 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000182
Chad Rosier8f138d12012-10-15 17:19:13 +0000183 bool ParseStatement();
Chad Rosier84125ca2012-10-13 00:26:04 +0000184 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosierc5ac87d2012-10-16 20:16:20 +0000185 bool isParsingInlineAsm() { return ParsingInlineAsm; }
Chad Rosier8f138d12012-10-15 17:19:13 +0000186 unsigned getNumParsedOperands() { return ParsedOperands.size(); }
187 MCParsedAsmOperand &getParsedOperand(unsigned OpNum) {
188 assert (ParsedOperands.size() > OpNum);
189 return *ParsedOperands[OpNum];
190 }
191 void freeParsedOperands() {
192 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
193 delete ParsedOperands[i];
194 ParsedOperands.clear();
195 }
Chad Rosier127f5ed2012-10-15 19:08:18 +0000196 bool isInstruction() { return Opcode != (unsigned)~0x0; }
Chad Rosier8f138d12012-10-15 17:19:13 +0000197 unsigned getOpcode() { return Opcode; }
Chad Rosier84125ca2012-10-13 00:26:04 +0000198
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000199 bool ParseExpression(const MCExpr *&Res);
200 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
201 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
202 virtual bool ParseAbsoluteExpression(int64_t &Res);
203
204 /// }
205
206private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000207 void CheckForValidSection();
208
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000209 void EatToEndOfLine();
210 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000211
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000212 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
Rafael Espindola761cb062012-06-03 23:57:14 +0000213 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +0000214 const MacroParameters &Parameters,
215 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000216 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000217 void HandleMacroExit();
218
219 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000220 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000221 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
222 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000223 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000224 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000225
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000226 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
227 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000228 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
229 /// This returns true on failure.
230 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000231
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000232 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000233 /// current token is not set; clients should ensure Lex() is called
234 /// subsequently.
235 void JumpToLoc(SMLoc Loc);
236
Craig Topper345d16d2012-08-29 05:48:09 +0000237 virtual void EatToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000238
Preston Gurd7b6f2032012-09-19 20:36:12 +0000239 bool ParseMacroArgument(MacroArgument &MA,
240 AsmToken::TokenKind &ArgumentDelimiter);
Rafael Espindola8a403d32012-08-08 14:51:03 +0000241 bool ParseMacroArguments(const Macro *M, MacroArguments &A);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000242
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000243 /// \brief Parse up to the end of statement and a return the contents from the
244 /// current token until the end of the statement; the current token on exit
245 /// will be either the EndOfStatement or EOF.
Craig Topper345d16d2012-08-29 05:48:09 +0000246 virtual StringRef ParseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000247
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000248 /// \brief Parse until the end of a statement or a comma is encountered,
249 /// return the contents from the current token up to the end or comma.
250 StringRef ParseStringToComma();
251
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000252 bool ParseAssignment(StringRef Name, bool allow_redef,
253 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000254
255 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
256 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
257 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000258 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000259
260 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000261 /// and set \p Res to the identifier contents.
Craig Topper345d16d2012-08-29 05:48:09 +0000262 virtual bool ParseIdentifier(StringRef &Res);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000263
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000264 // Directive Parsing.
Rafael Espindola787c3372010-10-28 20:02:27 +0000265
266 // ".ascii", ".asciiz", ".string"
267 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000268 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000269 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000270 bool ParseDirectiveFill(); // ".fill"
271 bool ParseDirectiveSpace(); // ".space"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000272 bool ParseDirectiveZero(); // ".zero"
Nico Weber4c4c7322011-01-28 03:04:41 +0000273 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000274 bool ParseDirectiveOrg(); // ".org"
275 // ".align{,32}", ".p2align{,w,l}"
276 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
277
278 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
279 /// accepts a single symbol (which should be a label or an external).
280 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000281
282 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
283
284 bool ParseDirectiveAbort(); // ".abort"
285 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000286 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000287
288 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000289 // ".ifb" or ".ifnb", depending on ExpectBlank.
290 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000291 // ".ifc" or ".ifnc", depending on ExpectEqual.
292 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000293 // ".ifdef" or ".ifndef", depending on expect_defined
294 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000295 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
296 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
297 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
298
299 /// ParseEscapedString - Parse the current token as a string which may include
300 /// escaped characters and return the string contents.
301 bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000302
303 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
304 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000305
Rafael Espindola761cb062012-06-03 23:57:14 +0000306 // Macro-like directives
307 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
308 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
309 raw_svector_ostream &OS);
310 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000311 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000312 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000313 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000314};
315
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000316/// \brief Generic implementations of directive handling, etc. which is shared
317/// (or the default, at least) for all assembler parser.
318class GenericAsmParser : public MCAsmParserExtension {
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000319 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
320 void AddDirectiveHandler(StringRef Directive) {
321 getParser().AddDirectiveHandler(this, Directive,
322 HandleDirective<GenericAsmParser, Handler>);
323 }
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000324public:
325 GenericAsmParser() {}
326
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000327 AsmParser &getParser() {
328 return (AsmParser&) this->MCAsmParserExtension::getParser();
329 }
330
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000331 virtual void Initialize(MCAsmParser &Parser) {
332 // Call the base implementation.
333 this->MCAsmParserExtension::Initialize(Parser);
334
335 // Debugging directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000336 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
337 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
338 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
Daniel Dunbar138abae2010-10-16 04:56:42 +0000339 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000340
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000341 // CFI directives.
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000342 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
343 ".cfi_sections");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000344 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
345 ".cfi_startproc");
346 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
347 ".cfi_endproc");
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000348 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
349 ".cfi_def_cfa");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000350 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
351 ".cfi_def_cfa_offset");
Rafael Espindola53abbe52011-04-11 20:29:16 +0000352 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
353 ".cfi_adjust_cfa_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000354 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
355 ".cfi_def_cfa_register");
356 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
357 ".cfi_offset");
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000358 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
359 ".cfi_rel_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000360 AddDirectiveHandler<
361 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
362 AddDirectiveHandler<
363 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
Rafael Espindolafe024d02010-12-28 18:36:23 +0000364 AddDirectiveHandler<
365 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
366 AddDirectiveHandler<
367 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
Rafael Espindolac5754392011-04-12 15:31:05 +0000368 AddDirectiveHandler<
369 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000370 AddDirectiveHandler<
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000371 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
372 AddDirectiveHandler<
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000373 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
Rafael Espindola16d7d432012-01-23 21:51:52 +0000374 AddDirectiveHandler<
375 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000376
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000377 // Macro directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000378 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
379 ".macros_on");
380 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
381 ".macros_off");
382 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
383 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
384 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000385 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000386
387 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
388 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000389 }
390
Roman Divacky54b0f4f2011-01-27 17:16:37 +0000391 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
392
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000393 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
394 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
395 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar138abae2010-10-16 04:56:42 +0000396 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000397 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000398 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
399 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000400 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000401 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola53abbe52011-04-11 20:29:16 +0000402 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000403 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
404 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000405 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000406 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
Rafael Espindolafe024d02010-12-28 18:36:23 +0000407 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
408 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac5754392011-04-12 15:31:05 +0000409 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000410 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000411 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
Rafael Espindola16d7d432012-01-23 21:51:52 +0000412 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000413
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000414 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000415 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
416 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000417 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000418
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000419 bool ParseDirectiveLEB128(StringRef, SMLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000420};
421
422}
423
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000424namespace llvm {
425
426extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000427extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000428extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000429
430}
431
Chris Lattneraaec2052010-01-19 19:46:13 +0000432enum { DEFAULT_ADDRSPACE = 0 };
433
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000434AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000435 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000436 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Rafael Espindola5d7dcd32011-04-12 18:53:30 +0000437 GenericParser(new GenericAsmParser), PlatformParser(0),
Preston Gurd7b6f2032012-09-19 20:36:12 +0000438 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
Chad Rosier8f138d12012-10-15 17:19:13 +0000439 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false),
Chad Rosier127f5ed2012-10-15 19:08:18 +0000440 Opcode(~0x0) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000441 // Save the old handler.
442 SavedDiagHandler = SrcMgr.getDiagHandler();
443 SavedDiagContext = SrcMgr.getDiagContext();
444 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000445 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000446 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000447
448 // Initialize the generic parser.
449 GenericParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000450
451 // Initialize the platform / file format parser.
452 //
453 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
454 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000455 if (_MAI.hasMicrosoftFastStdCallMangling()) {
456 PlatformParser = createCOFFAsmParser();
457 PlatformParser->Initialize(*this);
458 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000459 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000460 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000461 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000462 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000463 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000464 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000465 }
Chris Lattnerebb89b42009-09-27 21:16:52 +0000466}
467
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000468AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000469 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
470
471 // Destroy any macros.
472 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
473 ie = MacroMap.end(); it != ie; ++it)
474 delete it->getValue();
475
Daniel Dunbare4749702010-07-12 18:12:02 +0000476 delete PlatformParser;
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000477 delete GenericParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000478}
479
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000480void AsmParser::PrintMacroInstantiations() {
481 // Print the active macro instantiation stack.
482 for (std::vector<MacroInstantiation*>::const_reverse_iterator
483 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000484 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
485 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000486}
487
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000488bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000489 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000490 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000491 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000492 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000493 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000494}
495
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000496bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000497 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000498 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000499 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000500 return true;
501}
502
Sean Callananfd0b0282010-01-21 00:19:58 +0000503bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000504 std::string IncludedFile;
505 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000506 if (NewBuf == -1)
507 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000508
Sean Callananfd0b0282010-01-21 00:19:58 +0000509 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000510
Sean Callananfd0b0282010-01-21 00:19:58 +0000511 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000512
Sean Callananfd0b0282010-01-21 00:19:58 +0000513 return false;
514}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000515
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000516/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000517/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000518/// returns true on failure.
519bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
520 std::string IncludedFile;
521 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
522 if (NewBuf == -1)
523 return true;
524
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000525 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000526 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
527 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000528 return false;
529}
530
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000531void AsmParser::JumpToLoc(SMLoc Loc) {
532 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
533 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
534}
535
Sean Callananfd0b0282010-01-21 00:19:58 +0000536const AsmToken &AsmParser::Lex() {
537 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000538
Sean Callananfd0b0282010-01-21 00:19:58 +0000539 if (tok->is(AsmToken::Eof)) {
540 // If this is the end of an included file, pop the parent file off the
541 // include stack.
542 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
543 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000544 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000545 tok = &Lexer.Lex();
546 }
547 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000548
Sean Callananfd0b0282010-01-21 00:19:58 +0000549 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000550 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000551
Sean Callananfd0b0282010-01-21 00:19:58 +0000552 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000553}
554
Chris Lattner79180e22010-04-05 23:15:42 +0000555bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000556 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000557 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000558 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000559
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000560 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000561 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000562
563 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000564 AsmCond StartingCondState = TheCondState;
565
Kevin Enderby613b7572011-11-01 22:27:22 +0000566 // If we are generating dwarf for assembly source files save the initial text
567 // section and generate a .file directive.
568 if (getContext().getGenDwarfForAssembly()) {
569 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000570 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
571 getStreamer().EmitLabel(SectionStartSym);
572 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000573 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
574 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
575 }
576
Chris Lattnerb717fb02009-07-02 21:53:43 +0000577 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000578 while (Lexer.isNot(AsmToken::Eof)) {
Chris Lattnerb717fb02009-07-02 21:53:43 +0000579 if (!ParseStatement()) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000580
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000581 // We had an error, validate that one was emitted and recover by skipping to
582 // the next line.
583 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000584 EatToEndOfStatement();
585 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000586
587 if (TheCondState.TheCond != StartingCondState.TheCond ||
588 TheCondState.Ignore != StartingCondState.Ignore)
589 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000590
591 // Check to see there are no empty DwarfFile slots.
592 const std::vector<MCDwarfFile *> &MCDwarfFiles =
593 getContext().getMCDwarfFiles();
594 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000595 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000596 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000597 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000598
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000599 // Check to see that all assembler local symbols were actually defined.
600 // Targets that don't do subsections via symbols may not want this, though,
601 // so conservatively exclude them. Only do this if we're finalizing, though,
602 // as otherwise we won't necessarilly have seen everything yet.
603 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
604 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
605 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
606 e = Symbols.end();
607 i != e; ++i) {
608 MCSymbol *Sym = i->getValue();
609 // Variable symbols may not be marked as defined, so check those
610 // explicitly. If we know it's a variable, we have a definition for
611 // the purposes of this check.
612 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
613 // FIXME: We would really like to refer back to where the symbol was
614 // first referenced for a source location. We need to add something
615 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000616 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
617 "assembler local symbol '" + Sym->getName() +
618 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000619 }
620 }
621
622
Chris Lattner79180e22010-04-05 23:15:42 +0000623 // Finalize the output stream if there are no errors and if the client wants
624 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000625 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000626 Out.Finish();
627
Chris Lattnerb717fb02009-07-02 21:53:43 +0000628 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000629}
630
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000631void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000632 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000633 TokError("expected section directive before assembly directive");
634 Out.SwitchSection(Ctx.getMachOSection(
635 "__TEXT", "__text",
636 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
637 0, SectionKind::getText()));
638 }
639}
640
Chris Lattner2cf5f142009-06-22 01:29:09 +0000641/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
642void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000643 while (Lexer.isNot(AsmToken::EndOfStatement) &&
644 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000645 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000646
Chris Lattner2cf5f142009-06-22 01:29:09 +0000647 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000648 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000649 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000650}
651
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000652StringRef AsmParser::ParseStringToEndOfStatement() {
653 const char *Start = getTok().getLoc().getPointer();
654
655 while (Lexer.isNot(AsmToken::EndOfStatement) &&
656 Lexer.isNot(AsmToken::Eof))
657 Lex();
658
659 const char *End = getTok().getLoc().getPointer();
660 return StringRef(Start, End - Start);
661}
Chris Lattnerc4193832009-06-22 05:51:26 +0000662
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000663StringRef AsmParser::ParseStringToComma() {
664 const char *Start = getTok().getLoc().getPointer();
665
666 while (Lexer.isNot(AsmToken::EndOfStatement) &&
667 Lexer.isNot(AsmToken::Comma) &&
668 Lexer.isNot(AsmToken::Eof))
669 Lex();
670
671 const char *End = getTok().getLoc().getPointer();
672 return StringRef(Start, End - Start);
673}
674
Chris Lattner74ec1a32009-06-22 06:32:03 +0000675/// ParseParenExpr - Parse a paren expression and return it.
676/// NOTE: This assumes the leading '(' has already been consumed.
677///
678/// parenexpr ::= expr)
679///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000680bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000681 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000682 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000683 return TokError("expected ')' in parentheses expression");
Chris Lattnerb4307b32010-01-15 19:28:38 +0000684 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000685 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000686 return false;
687}
Chris Lattnerc4193832009-06-22 05:51:26 +0000688
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000689/// ParseBracketExpr - Parse a bracket expression and return it.
690/// NOTE: This assumes the leading '[' has already been consumed.
691///
692/// bracketexpr ::= expr]
693///
694bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
695 if (ParseExpression(Res)) return true;
696 if (Lexer.isNot(AsmToken::RBrac))
697 return TokError("expected ']' in brackets expression");
698 EndLoc = Lexer.getLoc();
699 Lex();
700 return false;
701}
702
Chris Lattner74ec1a32009-06-22 06:32:03 +0000703/// ParsePrimaryExpr - Parse a primary expression and return it.
704/// primaryexpr ::= (parenexpr
705/// primaryexpr ::= symbol
706/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000707/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000708/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000709bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000710 switch (Lexer.getKind()) {
711 default:
712 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000713 // If we have an error assume that we've already handled it.
714 case AsmToken::Error:
715 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000716 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000717 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000718 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000719 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000720 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000721 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000722 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000723 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000724 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000725 EndLoc = Lexer.getLoc();
726
727 StringRef Identifier;
728 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000729 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000730
Daniel Dunbarfffff912009-10-16 01:34:54 +0000731 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000732 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000733 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000734
735 // Lookup the symbol variant if used.
736 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000737 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000738 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000739 if (Variant == MCSymbolRefExpr::VK_Invalid) {
740 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000741 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000742 }
743 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000744
Daniel Dunbarfffff912009-10-16 01:34:54 +0000745 // If this is an absolute variable reference, substitute it now to preserve
746 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000747 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000748 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000749 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000750
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000751 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000752 return false;
753 }
754
755 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000756 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000757 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000758 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000759 case AsmToken::Integer: {
760 SMLoc Loc = getTok().getLoc();
761 int64_t IntVal = getTok().getIntVal();
762 Res = MCConstantExpr::Create(IntVal, getContext());
Chris Lattnerb4307b32010-01-15 19:28:38 +0000763 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000764 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000765 // Look for 'b' or 'f' following an Integer as a directional label
766 if (Lexer.getKind() == AsmToken::Identifier) {
767 StringRef IDVal = getTok().getString();
768 if (IDVal == "f" || IDVal == "b"){
769 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
770 IDVal == "f" ? 1 : 0);
771 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
772 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000773 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000774 return Error(Loc, "invalid reference to undefined symbol");
775 EndLoc = Lexer.getLoc();
776 Lex(); // Eat identifier.
777 }
778 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000779 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000780 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000781 case AsmToken::Real: {
782 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000783 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000784 Res = MCConstantExpr::Create(IntVal, getContext());
785 Lex(); // Eat token.
786 return false;
787 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000788 case AsmToken::Dot: {
789 // This is a '.' reference, which references the current PC. Emit a
790 // temporary label to the streamer and refer to it.
791 MCSymbol *Sym = Ctx.CreateTempSymbol();
792 Out.EmitLabel(Sym);
793 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
794 EndLoc = Lexer.getLoc();
795 Lex(); // Eat identifier.
796 return false;
797 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000798 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000799 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000800 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000801 case AsmToken::LBrac:
802 if (!PlatformParser->HasBracketExpressions())
803 return TokError("brackets expression not supported on this target");
804 Lex(); // Eat the '['.
805 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000806 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000807 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000808 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000809 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000810 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000811 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000812 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000813 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000814 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000815 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000816 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000817 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000818 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000819 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000820 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000821 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000822 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000823 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000824 }
825}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000826
Chris Lattnerb4307b32010-01-15 19:28:38 +0000827bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000828 SMLoc EndLoc;
829 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000830}
831
Daniel Dunbarcceba832010-09-17 02:47:07 +0000832const MCExpr *
833AsmParser::ApplyModifierToExpr(const MCExpr *E,
834 MCSymbolRefExpr::VariantKind Variant) {
835 // Recurse over the given expression, rebuilding it to apply the given variant
836 // if there is exactly one symbol.
837 switch (E->getKind()) {
838 case MCExpr::Target:
839 case MCExpr::Constant:
840 return 0;
841
842 case MCExpr::SymbolRef: {
843 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
844
845 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
846 TokError("invalid variant on expression '" +
847 getTok().getIdentifier() + "' (already modified)");
848 return E;
849 }
850
851 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
852 }
853
854 case MCExpr::Unary: {
855 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
856 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
857 if (!Sub)
858 return 0;
859 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
860 }
861
862 case MCExpr::Binary: {
863 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
864 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
865 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
866
867 if (!LHS && !RHS)
868 return 0;
869
870 if (!LHS) LHS = BE->getLHS();
871 if (!RHS) RHS = BE->getRHS();
872
873 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
874 }
875 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000876
Craig Topper85814382012-02-07 05:05:23 +0000877 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000878}
879
Chris Lattner74ec1a32009-06-22 06:32:03 +0000880/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000881///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000882/// expr ::= expr &&,|| expr -> lowest.
883/// expr ::= expr |,^,&,! expr
884/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
885/// expr ::= expr <<,>> expr
886/// expr ::= expr +,- expr
887/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000888/// expr ::= primaryexpr
889///
Chris Lattner54482b42010-01-15 19:39:23 +0000890bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000891 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000892 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000893 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
894 return true;
895
Daniel Dunbarcceba832010-09-17 02:47:07 +0000896 // As a special case, we support 'a op b @ modifier' by rewriting the
897 // expression to include the modifier. This is inefficient, but in general we
898 // expect users to use 'a@modifier op b'.
899 if (Lexer.getKind() == AsmToken::At) {
900 Lex();
901
902 if (Lexer.isNot(AsmToken::Identifier))
903 return TokError("unexpected symbol modifier following '@'");
904
905 MCSymbolRefExpr::VariantKind Variant =
906 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
907 if (Variant == MCSymbolRefExpr::VK_Invalid)
908 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
909
910 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
911 if (!ModifiedRes) {
912 return TokError("invalid modifier '" + getTok().getIdentifier() +
913 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000914 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000915
Daniel Dunbarcceba832010-09-17 02:47:07 +0000916 Res = ModifiedRes;
917 Lex();
918 }
919
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000920 // Try to constant fold it up front, if possible.
921 int64_t Value;
922 if (Res->EvaluateAsAbsolute(Value))
923 Res = MCConstantExpr::Create(Value, getContext());
924
925 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000926}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000927
Chris Lattnerb4307b32010-01-15 19:28:38 +0000928bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000929 Res = 0;
930 return ParseParenExpr(Res, EndLoc) ||
931 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000932}
933
Daniel Dunbar475839e2009-06-29 20:37:27 +0000934bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000935 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000936
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000937 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000938 if (ParseExpression(Expr))
939 return true;
940
Daniel Dunbare00b0112009-10-16 01:57:52 +0000941 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000942 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000943
944 return false;
945}
946
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000947static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000948 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000949 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000950 default:
951 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000952
Jim Grosbachfbe16812011-08-20 16:24:13 +0000953 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000954 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000955 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000956 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000957 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000958 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000959 return 1;
960
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000961
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000962 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +0000963 //
964 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +0000965 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000966 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000967 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000968 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000969 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000970 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000971 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000972 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000973 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000974
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000975 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000976 case AsmToken::EqualEqual:
977 Kind = MCBinaryExpr::EQ;
978 return 3;
979 case AsmToken::ExclaimEqual:
980 case AsmToken::LessGreater:
981 Kind = MCBinaryExpr::NE;
982 return 3;
983 case AsmToken::Less:
984 Kind = MCBinaryExpr::LT;
985 return 3;
986 case AsmToken::LessEqual:
987 Kind = MCBinaryExpr::LTE;
988 return 3;
989 case AsmToken::Greater:
990 Kind = MCBinaryExpr::GT;
991 return 3;
992 case AsmToken::GreaterEqual:
993 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000994 return 3;
995
Jim Grosbachfbe16812011-08-20 16:24:13 +0000996 // Intermediate Precedence: <<, >>
997 case AsmToken::LessLess:
998 Kind = MCBinaryExpr::Shl;
999 return 4;
1000 case AsmToken::GreaterGreater:
1001 Kind = MCBinaryExpr::Shr;
1002 return 4;
1003
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001004 // High Intermediate Precedence: +, -
1005 case AsmToken::Plus:
1006 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001007 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001008 case AsmToken::Minus:
1009 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001010 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001011
Jim Grosbachfbe16812011-08-20 16:24:13 +00001012 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001013 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001014 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001015 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001016 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001017 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001018 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001019 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001020 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001021 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001022 }
1023}
1024
1025
1026/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1027/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001028bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1029 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001030 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001031 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001032 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001033
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001034 // If the next token is lower precedence than we are allowed to eat, return
1035 // successfully with what we ate already.
1036 if (TokPrec < Precedence)
1037 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001038
Sean Callanan79ed1a82010-01-19 20:22:31 +00001039 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001040
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001041 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001042 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001043 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001044
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001045 // If BinOp binds less tightly with RHS than the operator after RHS, let
1046 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001047 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001048 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001049 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001050 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001051 }
1052
Daniel Dunbar475839e2009-06-29 20:37:27 +00001053 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001054 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001055 }
1056}
1057
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001058/// ParseStatement:
1059/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001060/// ::= Label* Directive ...Operands... EndOfStatement
1061/// ::= Label* Identifier OperandList* EndOfStatement
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001062bool AsmParser::ParseStatement() {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001063 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001064 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001065 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001066 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001067 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001068
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001069 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001070 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001071 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001072 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001073 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001074 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001075 if (Lexer.is(AsmToken::Hash))
1076 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001077
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001078 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001079 if (Lexer.is(AsmToken::Integer)) {
1080 LocalLabelVal = getTok().getIntVal();
1081 if (LocalLabelVal < 0) {
1082 if (!TheCondState.Ignore)
1083 return TokError("unexpected token at start of statement");
1084 IDVal = "";
1085 }
1086 else {
1087 IDVal = getTok().getString();
1088 Lex(); // Consume the integer token to be used as an identifier token.
1089 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001090 if (!TheCondState.Ignore)
1091 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001092 }
1093 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001094
1095 } else if (Lexer.is(AsmToken::Dot)) {
1096 // Treat '.' as a valid identifier in this context.
1097 Lex();
1098 IDVal = ".";
1099
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001100 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001101 if (!TheCondState.Ignore)
1102 return TokError("unexpected token at start of statement");
1103 IDVal = "";
1104 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001105
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001106
Chris Lattner7834fac2010-04-17 18:14:27 +00001107 // Handle conditional assembly here before checking for skipping. We
1108 // have to do this so that .endif isn't skipped in a ".if 0" block for
1109 // example.
1110 if (IDVal == ".if")
1111 return ParseDirectiveIf(IDLoc);
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00001112 if (IDVal == ".ifb")
1113 return ParseDirectiveIfb(IDLoc, true);
1114 if (IDVal == ".ifnb")
1115 return ParseDirectiveIfb(IDLoc, false);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00001116 if (IDVal == ".ifc")
1117 return ParseDirectiveIfc(IDLoc, true);
1118 if (IDVal == ".ifnc")
1119 return ParseDirectiveIfc(IDLoc, false);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00001120 if (IDVal == ".ifdef")
1121 return ParseDirectiveIfdef(IDLoc, true);
1122 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1123 return ParseDirectiveIfdef(IDLoc, false);
Chris Lattner7834fac2010-04-17 18:14:27 +00001124 if (IDVal == ".elseif")
1125 return ParseDirectiveElseIf(IDLoc);
1126 if (IDVal == ".else")
1127 return ParseDirectiveElse(IDLoc);
1128 if (IDVal == ".endif")
1129 return ParseDirectiveEndIf(IDLoc);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001130
Chris Lattner7834fac2010-04-17 18:14:27 +00001131 // If we are in a ".if 0" block, ignore this statement.
1132 if (TheCondState.Ignore) {
1133 EatToEndOfStatement();
1134 return false;
1135 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001136
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001137 // FIXME: Recurse on local labels?
1138
1139 // See what kind of statement we have.
1140 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001141 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001142 CheckForValidSection();
1143
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001144 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001145 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001146
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001147 // Diagnose attempt to use '.' as a label.
1148 if (IDVal == ".")
1149 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1150
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001151 // Diagnose attempt to use a variable as a label.
1152 //
1153 // FIXME: Diagnostics. Note the location of the definition as a label.
1154 // FIXME: This doesn't diagnose assignment to a symbol which has been
1155 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001156 MCSymbol *Sym;
1157 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001158 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001159 else
1160 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001161 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001162 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001163
Daniel Dunbar959fd882009-08-26 22:13:22 +00001164 // Emit the label.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001165 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001166
Kevin Enderby94c2e852011-12-09 18:09:40 +00001167 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001168 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001169 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001170 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1171 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001172
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001173 // Consume any end of statement token, if present, to avoid spurious
1174 // AddBlankLine calls().
1175 if (Lexer.is(AsmToken::EndOfStatement)) {
1176 Lex();
1177 if (Lexer.is(AsmToken::Eof))
1178 return false;
1179 }
1180
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001181 return ParseStatement();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001182 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001183
Daniel Dunbar3f872332009-07-28 16:08:33 +00001184 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001185 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001186 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001187
Nico Weber4c4c7322011-01-28 03:04:41 +00001188 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001189
1190 default: // Normal instruction or directive.
1191 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001192 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001193
1194 // If macros are enabled, check to see if this is a macro instantiation.
1195 if (MacrosEnabled)
1196 if (const Macro *M = MacroMap.lookup(IDVal))
1197 return HandleMacroEntry(IDVal, IDLoc, M);
1198
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001199 // Otherwise, we have a normal instruction or directive.
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001200 if (IDVal[0] == '.' && IDVal != ".") {
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001201
1202 // Target hook for parsing target specific directives.
1203 if (!getTargetParser().ParseDirective(ID))
1204 return false;
1205
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001206 // Assembler features
Roman Divacky50e7a782010-10-28 16:22:58 +00001207 if (IDVal == ".set" || IDVal == ".equ")
Nico Weber4c4c7322011-01-28 03:04:41 +00001208 return ParseDirectiveSet(IDVal, true);
1209 if (IDVal == ".equiv")
1210 return ParseDirectiveSet(IDVal, false);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001211
Daniel Dunbara0d14262009-06-24 23:30:00 +00001212 // Data directives
1213
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001214 if (IDVal == ".ascii")
Rafael Espindola787c3372010-10-28 20:02:27 +00001215 return ParseDirectiveAscii(IDVal, false);
1216 if (IDVal == ".asciz" || IDVal == ".string")
1217 return ParseDirectiveAscii(IDVal, true);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001218
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001219 if (IDVal == ".byte")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001220 return ParseDirectiveValue(1);
Kevin Enderby9c656452009-09-10 20:51:44 +00001221 if (IDVal == ".short")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001222 return ParseDirectiveValue(2);
Rafael Espindolacc3acee2010-11-01 15:29:07 +00001223 if (IDVal == ".value")
1224 return ParseDirectiveValue(2);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001225 if (IDVal == ".2byte")
1226 return ParseDirectiveValue(2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001227 if (IDVal == ".long")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001228 return ParseDirectiveValue(4);
Rafael Espindola435279b2010-11-17 16:24:40 +00001229 if (IDVal == ".int")
1230 return ParseDirectiveValue(4);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001231 if (IDVal == ".4byte")
1232 return ParseDirectiveValue(4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001233 if (IDVal == ".quad")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001234 return ParseDirectiveValue(8);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001235 if (IDVal == ".8byte")
1236 return ParseDirectiveValue(8);
Roman Divacky14e66552011-01-28 14:20:32 +00001237 if (IDVal == ".single" || IDVal == ".float")
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001238 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1239 if (IDVal == ".double")
1240 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001241
Eli Friedman5d68ec22010-07-19 04:17:25 +00001242 if (IDVal == ".align") {
1243 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1244 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1245 }
1246 if (IDVal == ".align32") {
1247 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1248 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1249 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001250 if (IDVal == ".balign")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001251 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001252 if (IDVal == ".balignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001253 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001254 if (IDVal == ".balignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001255 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001256 if (IDVal == ".p2align")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001257 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001258 if (IDVal == ".p2alignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001259 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001260 if (IDVal == ".p2alignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001261 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1262
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001263 if (IDVal == ".org")
Daniel Dunbarc238b582009-06-25 22:44:51 +00001264 return ParseDirectiveOrg();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001265
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001266 if (IDVal == ".fill")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001267 return ParseDirectiveFill();
Rafael Espindolace8463f2011-04-07 20:26:23 +00001268 if (IDVal == ".space" || IDVal == ".skip")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001269 return ParseDirectiveSpace();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001270 if (IDVal == ".zero")
1271 return ParseDirectiveZero();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001272
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001273 // Symbol attribute directives
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001274
Benjamin Kramere14a3c52012-05-12 11:18:59 +00001275 if (IDVal == ".extern") {
1276 EatToEndOfStatement(); // .extern is the default, ignore it.
1277 return false;
1278 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001279 if (IDVal == ".globl" || IDVal == ".global")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001280 return ParseDirectiveSymbolAttribute(MCSA_Global);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001281 if (IDVal == ".indirect_symbol")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001282 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001283 if (IDVal == ".lazy_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001284 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001285 if (IDVal == ".no_dead_strip")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001286 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Kevin Enderbye8e98d72010-11-19 18:39:33 +00001287 if (IDVal == ".symbol_resolver")
1288 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001289 if (IDVal == ".private_extern")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001290 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001291 if (IDVal == ".reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001292 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001293 if (IDVal == ".weak_definition")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001294 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001295 if (IDVal == ".weak_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001296 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Kevin Enderbyf59cac52010-07-08 17:22:42 +00001297 if (IDVal == ".weak_def_can_be_hidden")
1298 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001299
Hans Wennborg5cc64912011-06-18 13:51:54 +00001300 if (IDVal == ".comm" || IDVal == ".common")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001301 return ParseDirectiveComm(/*IsLocal=*/false);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001302 if (IDVal == ".lcomm")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001303 return ParseDirectiveComm(/*IsLocal=*/true);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001304
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001305 if (IDVal == ".abort")
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001306 return ParseDirectiveAbort();
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001307 if (IDVal == ".include")
Kevin Enderby1f049b22009-07-14 23:21:55 +00001308 return ParseDirectiveInclude();
Kevin Enderbyc55acca2011-12-14 21:47:48 +00001309 if (IDVal == ".incbin")
1310 return ParseDirectiveIncbin();
Kevin Enderbya5c78322009-07-13 21:03:15 +00001311
Benjamin Kramer5cdf0ad2012-05-12 11:19:04 +00001312 if (IDVal == ".code16" || IDVal == ".code16gcc")
Roman Divackyf6fbd842011-01-31 20:56:49 +00001313 return TokError(Twine(IDVal) + " not supported yet");
Roman Divackycb727802011-01-28 19:29:48 +00001314
Rafael Espindola761cb062012-06-03 23:57:14 +00001315 // Macro-like directives
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001316 if (IDVal == ".rept")
1317 return ParseDirectiveRept(IDLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001318 if (IDVal == ".irp")
1319 return ParseDirectiveIrp(IDLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00001320 if (IDVal == ".irpc")
1321 return ParseDirectiveIrpc(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001322 if (IDVal == ".endr")
Rafael Espindola761cb062012-06-03 23:57:14 +00001323 return ParseDirectiveEndr(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001324
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001325 // Look up the handler in the handler table.
1326 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1327 DirectiveMap.lookup(IDVal);
1328 if (Handler.first)
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +00001329 return (*Handler.second)(Handler.first, IDVal, IDLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001330
Kevin Enderby9c656452009-09-10 20:51:44 +00001331
Jim Grosbach686c0182012-05-01 18:38:27 +00001332 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001333 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001334
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001335 CheckForValidSection();
1336
Chris Lattnera7f13542010-05-19 23:34:33 +00001337 // Canonicalize the opcode to lower case.
Chad Rosier8f138d12012-10-15 17:19:13 +00001338 SmallString<128> OpcodeStr;
Chris Lattnera7f13542010-05-19 23:34:33 +00001339 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
Chad Rosier8f138d12012-10-15 17:19:13 +00001340 OpcodeStr.push_back(tolower(IDVal[i]));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001341
Chad Rosier8f138d12012-10-15 17:19:13 +00001342 bool HadError = getTargetParser().ParseInstruction(OpcodeStr.str(), IDLoc,
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001343 ParsedOperands);
Chris Lattner2cf5f142009-06-22 01:29:09 +00001344
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001345 // Dump the parsed representation, if requested.
1346 if (getShowParsedOperands()) {
1347 SmallString<256> Str;
1348 raw_svector_ostream OS(Str);
1349 OS << "parsed instruction: [";
1350 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1351 if (i != 0)
1352 OS << ", ";
Jim Grosbachb7f689b2011-07-13 15:34:57 +00001353 ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001354 }
1355 OS << "]";
1356
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001357 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001358 }
1359
Kevin Enderby613b7572011-11-01 22:27:22 +00001360 // If we are generating dwarf for assembly source files and the current
1361 // section is the initial text section then generate a .loc directive for
1362 // the instruction.
1363 if (!HadError && getContext().getGenDwarfForAssembly() &&
1364 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1365 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1366 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1367 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001368 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001369 StringRef());
1370 }
1371
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001372 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001373 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001374 unsigned ErrorInfo;
1375 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Opcode,
Chad Rosier8f138d12012-10-15 17:19:13 +00001376 ParsedOperands, Out,
1377 ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001378 ParsingInlineAsm);
1379 }
Chris Lattner98986712010-01-14 22:21:20 +00001380
Chad Rosier8f138d12012-10-15 17:19:13 +00001381 // Free any parsed operands. If parsing ms-style inline assembly it is the
1382 // responsibility of the caller (i.e., clang) to free the parsed operands.
1383 if (!ParsingInlineAsm)
1384 freeParsedOperands();
Chris Lattner98986712010-01-14 22:21:20 +00001385
Chris Lattnercbf8a982010-09-11 16:18:25 +00001386 // Don't skip the rest of the line, the instruction parser is responsible for
1387 // that.
1388 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001389}
Chris Lattner9a023f72009-06-24 04:43:34 +00001390
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001391/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1392/// since they may not be able to be tokenized to get to the end of line token.
1393void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001394 if (!Lexer.is(AsmToken::EndOfStatement))
1395 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001396 // Eat EOL.
1397 Lex();
1398}
1399
1400/// ParseCppHashLineFilenameComment as this:
1401/// ::= # number "filename"
1402/// or just as a full line comment if it doesn't have a number and a string.
1403bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1404 Lex(); // Eat the hash token.
1405
1406 if (getLexer().isNot(AsmToken::Integer)) {
1407 // Consume the line since in cases it is not a well-formed line directive,
1408 // as if were simply a full line comment.
1409 EatToEndOfLine();
1410 return false;
1411 }
1412
1413 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001414 Lex();
1415
1416 if (getLexer().isNot(AsmToken::String)) {
1417 EatToEndOfLine();
1418 return false;
1419 }
1420
1421 StringRef Filename = getTok().getString();
1422 // Get rid of the enclosing quotes.
1423 Filename = Filename.substr(1, Filename.size()-2);
1424
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001425 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1426 CppHashLoc = L;
1427 CppHashFilename = Filename;
1428 CppHashLineNumber = LineNumber;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001429
1430 // Ignore any trailing characters, they're just comment.
1431 EatToEndOfLine();
1432 return false;
1433}
1434
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001435/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001436/// for the Filename and LineNo if any in the diagnostic.
1437void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1438 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1439 raw_ostream &OS = errs();
1440
1441 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1442 const SMLoc &DiagLoc = Diag.getLoc();
1443 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1444 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1445
1446 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1447 // before printing the message.
1448 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001449 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001450 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1451 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1452 }
1453
1454 // If we have not parsed a cpp hash line filename comment or the source
1455 // manager changed or buffer changed (like in a nested include) then just
1456 // print the normal diagnostic using its Filename and LineNo.
1457 if (!Parser->CppHashLineNumber ||
1458 &DiagSrcMgr != &Parser->SrcMgr ||
1459 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001460 if (Parser->SavedDiagHandler)
1461 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1462 else
1463 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001464 return;
1465 }
1466
1467 // Use the CppHashFilename and calculate a line number based on the
1468 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1469 // the diagnostic.
1470 const std::string Filename = Parser->CppHashFilename;
1471
1472 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1473 int CppHashLocLineNo =
1474 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1475 int LineNo = Parser->CppHashLineNumber - 1 +
1476 (DiagLocLineNo - CppHashLocLineNo);
1477
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001478 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1479 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001480 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001481 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001482
Benjamin Kramer04a04262011-10-16 10:48:29 +00001483 if (Parser->SavedDiagHandler)
1484 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1485 else
1486 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001487}
1488
Rafael Espindola799aacf2012-08-21 18:29:30 +00001489// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1490// difference being that that function accepts '@' as part of identifiers and
1491// we can't do that. AsmLexer.cpp should probably be changed to handle
1492// '@' as a special case when needed.
1493static bool isIdentifierChar(char c) {
1494 return isalnum(c) || c == '_' || c == '$' || c == '.';
1495}
1496
Rafael Espindola761cb062012-06-03 23:57:14 +00001497bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +00001498 const MacroParameters &Parameters,
1499 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001500 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001501 unsigned NParameters = Parameters.size();
1502 if (NParameters != 0 && NParameters != A.size())
1503 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001504
Preston Gurd7b6f2032012-09-19 20:36:12 +00001505 // A macro without parameters is handled differently on Darwin:
1506 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001507 while (!Body.empty()) {
1508 // Scan for the next substitution.
1509 std::size_t End = Body.size(), Pos = 0;
1510 for (; Pos != End; ++Pos) {
1511 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001512 if (!NParameters) {
1513 // This macro has no parameters, look for $0, $1, etc.
1514 if (Body[Pos] != '$' || Pos + 1 == End)
1515 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001516
Rafael Espindola65366442011-06-05 02:43:45 +00001517 char Next = Body[Pos + 1];
1518 if (Next == '$' || Next == 'n' || isdigit(Next))
1519 break;
1520 } else {
1521 // This macro has parameters, look for \foo, \bar, etc.
1522 if (Body[Pos] == '\\' && Pos + 1 != End)
1523 break;
1524 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001525 }
1526
1527 // Add the prefix.
1528 OS << Body.slice(0, Pos);
1529
1530 // Check if we reached the end.
1531 if (Pos == End)
1532 break;
1533
Rafael Espindola65366442011-06-05 02:43:45 +00001534 if (!NParameters) {
1535 switch (Body[Pos+1]) {
1536 // $$ => $
1537 case '$':
1538 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001539 break;
1540
Rafael Espindola65366442011-06-05 02:43:45 +00001541 // $n => number of arguments
1542 case 'n':
1543 OS << A.size();
1544 break;
1545
1546 // $[0-9] => argument
1547 default: {
1548 // Missing arguments are ignored.
1549 unsigned Index = Body[Pos+1] - '0';
1550 if (Index >= A.size())
1551 break;
1552
1553 // Otherwise substitute with the token values, with spaces eliminated.
Rafael Espindola28c1f6662012-06-03 22:41:23 +00001554 for (MacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001555 ie = A[Index].end(); it != ie; ++it)
1556 OS << it->getString();
1557 break;
1558 }
1559 }
1560 Pos += 2;
1561 } else {
1562 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001563 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001564 ++I;
1565
1566 const char *Begin = Body.data() + Pos +1;
1567 StringRef Argument(Begin, I - (Pos +1));
1568 unsigned Index = 0;
1569 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001570 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001571 break;
1572
Preston Gurd7b6f2032012-09-19 20:36:12 +00001573 if (Index == NParameters) {
1574 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1575 Pos += 3;
1576 else {
1577 OS << '\\' << Argument;
1578 Pos = I;
1579 }
1580 } else {
1581 for (MacroArgument::const_iterator it = A[Index].begin(),
1582 ie = A[Index].end(); it != ie; ++it)
1583 if (it->getKind() == AsmToken::String)
1584 OS << it->getStringContents();
1585 else
1586 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001587
Preston Gurd7b6f2032012-09-19 20:36:12 +00001588 Pos += 1 + Argument.size();
1589 }
Rafael Espindola65366442011-06-05 02:43:45 +00001590 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001591 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001592 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001593 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001594
Rafael Espindola65366442011-06-05 02:43:45 +00001595 return false;
1596}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001597
Rafael Espindola65366442011-06-05 02:43:45 +00001598MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1599 MemoryBuffer *I)
1600 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1601{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001602}
1603
Preston Gurd7b6f2032012-09-19 20:36:12 +00001604static bool IsOperator(AsmToken::TokenKind kind)
1605{
1606 switch (kind)
1607 {
1608 default:
1609 return false;
1610 case AsmToken::Plus:
1611 case AsmToken::Minus:
1612 case AsmToken::Tilde:
1613 case AsmToken::Slash:
1614 case AsmToken::Star:
1615 case AsmToken::Dot:
1616 case AsmToken::Equal:
1617 case AsmToken::EqualEqual:
1618 case AsmToken::Pipe:
1619 case AsmToken::PipePipe:
1620 case AsmToken::Caret:
1621 case AsmToken::Amp:
1622 case AsmToken::AmpAmp:
1623 case AsmToken::Exclaim:
1624 case AsmToken::ExclaimEqual:
1625 case AsmToken::Percent:
1626 case AsmToken::Less:
1627 case AsmToken::LessEqual:
1628 case AsmToken::LessLess:
1629 case AsmToken::LessGreater:
1630 case AsmToken::Greater:
1631 case AsmToken::GreaterEqual:
1632 case AsmToken::GreaterGreater:
1633 return true;
1634 }
1635}
1636
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001637/// ParseMacroArgument - Extract AsmTokens for a macro argument.
1638/// This is used for both default macro parameter values and the
1639/// arguments in macro invocations
Preston Gurd7b6f2032012-09-19 20:36:12 +00001640bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1641 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001642 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001643 unsigned AddTokens = 0;
1644
1645 // gas accepts arguments separated by whitespace, except on Darwin
1646 if (!IsDarwin)
1647 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001648
1649 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001650 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1651 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001652 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001653 }
1654
1655 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1656 // Spaces and commas cannot be mixed to delimit parameters
1657 if (ArgumentDelimiter == AsmToken::Eof)
1658 ArgumentDelimiter = AsmToken::Comma;
1659 else if (ArgumentDelimiter != AsmToken::Comma) {
1660 Lexer.setSkipSpace(true);
1661 return TokError("expected ' ' for macro argument separator");
1662 }
1663 break;
1664 }
1665
1666 if (Lexer.is(AsmToken::Space)) {
1667 Lex(); // Eat spaces
1668
1669 // Spaces can delimit parameters, but could also be part an expression.
1670 // If the token after a space is an operator, add the token and the next
1671 // one into this argument
1672 if (ArgumentDelimiter == AsmToken::Space ||
1673 ArgumentDelimiter == AsmToken::Eof) {
1674 if (IsOperator(Lexer.getKind())) {
1675 // Check to see whether the token is used as an operator,
1676 // or part of an identifier
1677 const char *NextChar = getTok().getEndLoc().getPointer() + 1;
1678 if (*NextChar == ' ')
1679 AddTokens = 2;
1680 }
1681
1682 if (!AddTokens && ParenLevel == 0) {
1683 if (ArgumentDelimiter == AsmToken::Eof &&
1684 !IsOperator(Lexer.getKind()))
1685 ArgumentDelimiter = AsmToken::Space;
1686 break;
1687 }
1688 }
1689 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001690
1691 // HandleMacroEntry relies on not advancing the lexer here
1692 // to be able to fill in the remaining default parameter values
1693 if (Lexer.is(AsmToken::EndOfStatement))
1694 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001695
1696 // Adjust the current parentheses level.
1697 if (Lexer.is(AsmToken::LParen))
1698 ++ParenLevel;
1699 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1700 --ParenLevel;
1701
1702 // Append the token to the current argument list.
1703 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001704 if (AddTokens)
1705 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001706 Lex();
1707 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001708
1709 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001710 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001711 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001712 return false;
1713}
1714
1715// Parse the macro instantiation arguments.
Rafael Espindola8a403d32012-08-08 14:51:03 +00001716bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001717 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001718 // Argument delimiter is initially unknown. It will be set by
1719 // ParseMacroArgument()
1720 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001721
1722 // Parse two kinds of macro invocations:
1723 // - macros defined without any parameters accept an arbitrary number of them
1724 // - macros defined with parameters accept at most that many of them
1725 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1726 ++Parameter) {
1727 MacroArgument MA;
1728
Preston Gurd7b6f2032012-09-19 20:36:12 +00001729 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001730 return true;
1731
Preston Gurd6c9176a2012-09-19 20:29:04 +00001732 if (!MA.empty() || !NParameters)
1733 A.push_back(MA);
1734 else if (NParameters) {
1735 if (!M->Parameters[Parameter].second.empty())
1736 A.push_back(M->Parameters[Parameter].second);
1737 }
Jim Grosbach97146442012-07-30 22:44:17 +00001738
Preston Gurd6c9176a2012-09-19 20:29:04 +00001739 // At the end of the statement, fill in remaining arguments that have
1740 // default values. If there aren't any, then the next argument is
1741 // required but missing
1742 if (Lexer.is(AsmToken::EndOfStatement)) {
1743 if (NParameters && Parameter < NParameters - 1) {
1744 if (M->Parameters[Parameter + 1].second.empty())
1745 return TokError("macro argument '" +
1746 Twine(M->Parameters[Parameter + 1].first) +
1747 "' is missing");
1748 else
1749 continue;
1750 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001751 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001752 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001753
1754 if (Lexer.is(AsmToken::Comma))
1755 Lex();
1756 }
1757 return TokError("Too many arguments");
1758}
1759
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001760bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1761 const Macro *M) {
1762 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1763 // this, although we should protect against infinite loops.
1764 if (ActiveMacros.size() == 20)
1765 return TokError("macros cannot be nested more than 20 levels deep");
1766
Rafael Espindola8a403d32012-08-08 14:51:03 +00001767 MacroArguments A;
1768 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001769 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001770
Jim Grosbach97146442012-07-30 22:44:17 +00001771 // Remove any trailing empty arguments. Do this after-the-fact as we have
1772 // to keep empty arguments in the middle of the list or positionality
1773 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001774 while (!A.empty() && A.back().empty())
1775 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001776
Rafael Espindola65366442011-06-05 02:43:45 +00001777 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1778 // to hold the macro body with substitutions.
1779 SmallString<256> Buf;
1780 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001781 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001782
Rafael Espindola8a403d32012-08-08 14:51:03 +00001783 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001784 return true;
1785
Rafael Espindola761cb062012-06-03 23:57:14 +00001786 // We include the .endmacro in the buffer as our queue to exit the macro
1787 // instantiation.
1788 OS << ".endmacro\n";
1789
Rafael Espindola65366442011-06-05 02:43:45 +00001790 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001791 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001792
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001793 // Create the macro instantiation object and add to the current macro
1794 // instantiation stack.
1795 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001796 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001797 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001798 ActiveMacros.push_back(MI);
1799
1800 // Jump to the macro instantiation and prime the lexer.
1801 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1802 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1803 Lex();
1804
1805 return false;
1806}
1807
1808void AsmParser::HandleMacroExit() {
1809 // Jump to the EndOfStatement we should return to, and consume it.
1810 JumpToLoc(ActiveMacros.back()->ExitLoc);
1811 Lex();
1812
1813 // Pop the instantiation entry.
1814 delete ActiveMacros.back();
1815 ActiveMacros.pop_back();
1816}
1817
Rafael Espindolae71cc862012-01-28 05:57:00 +00001818static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001819 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001820 case MCExpr::Binary: {
1821 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1822 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001823 break;
1824 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001825 case MCExpr::Target:
1826 case MCExpr::Constant:
1827 return false;
1828 case MCExpr::SymbolRef: {
1829 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001830 if (S.isVariable())
1831 return IsUsedIn(Sym, S.getVariableValue());
1832 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001833 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001834 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001835 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001836 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001837
1838 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001839}
1840
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001841bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1842 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001843 // FIXME: Use better location, we should use proper tokens.
1844 SMLoc EqualLoc = Lexer.getLoc();
1845
Daniel Dunbar821e3332009-08-31 08:09:28 +00001846 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001847 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001848 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001849
Rafael Espindolae71cc862012-01-28 05:57:00 +00001850 // Note: we don't count b as used in "a = b". This is to allow
1851 // a = b
1852 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001853
Daniel Dunbar3f872332009-07-28 16:08:33 +00001854 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001855 return TokError("unexpected token in assignment");
1856
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001857 // Error on assignment to '.'.
1858 if (Name == ".") {
1859 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1860 "(use '.space' or '.org').)"));
1861 }
1862
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001863 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001864 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001865
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001866 // Validate that the LHS is allowed to be a variable (either it has not been
1867 // used as a symbol, or it is an absolute symbol).
1868 MCSymbol *Sym = getContext().LookupSymbol(Name);
1869 if (Sym) {
1870 // Diagnose assignment to a label.
1871 //
1872 // FIXME: Diagnostics. Note the location of the definition as a label.
1873 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00001874 if (IsUsedIn(Sym, Value))
1875 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1876 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001877 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00001878 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1879 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00001880 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001881 return Error(EqualLoc, "redefinition of '" + Name + "'");
1882 else if (!Sym->isVariable())
1883 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00001884 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001885 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1886 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001887
1888 // Don't count these checks as uses.
1889 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001890 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001891 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001892
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001893 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001894
1895 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00001896 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001897 if (NoDeadStrip)
1898 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1899
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001900
1901 return false;
1902}
1903
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001904/// ParseIdentifier:
1905/// ::= identifier
1906/// ::= string
1907bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00001908 // The assembler has relaxed rules for accepting identifiers, in particular we
1909 // allow things like '.globl $foo', which would normally be separate
1910 // tokens. At this level, we have already lexed so we cannot (currently)
1911 // handle this as a context dependent token, instead we detect adjacent tokens
1912 // and return the combined identifier.
1913 if (Lexer.is(AsmToken::Dollar)) {
1914 SMLoc DollarLoc = getLexer().getLoc();
1915
1916 // Consume the dollar sign, and check for a following identifier.
1917 Lex();
1918 if (Lexer.isNot(AsmToken::Identifier))
1919 return true;
1920
1921 // We have a '$' followed by an identifier, make sure they are adjacent.
1922 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1923 return true;
1924
1925 // Construct the joined identifier and consume the token.
1926 Res = StringRef(DollarLoc.getPointer(),
1927 getTok().getIdentifier().size() + 1);
1928 Lex();
1929 return false;
1930 }
1931
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001932 if (Lexer.isNot(AsmToken::Identifier) &&
1933 Lexer.isNot(AsmToken::String))
1934 return true;
1935
Sean Callanan18b83232010-01-19 21:44:56 +00001936 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001937
Sean Callanan79ed1a82010-01-19 20:22:31 +00001938 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001939
1940 return false;
1941}
1942
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001943/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00001944/// ::= .equ identifier ',' expression
1945/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001946/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00001947bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001948 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001949
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001950 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00001951 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001952
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001953 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00001954 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001955 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001956
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001957 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001958}
1959
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001960bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001961 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001962
1963 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00001964 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001965 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1966 if (Str[i] != '\\') {
1967 Data += Str[i];
1968 continue;
1969 }
1970
1971 // Recognize escaped characters. Note that this escape semantics currently
1972 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1973 ++i;
1974 if (i == e)
1975 return TokError("unexpected backslash at end of string");
1976
1977 // Recognize octal sequences.
1978 if ((unsigned) (Str[i] - '0') <= 7) {
1979 // Consume up to three octal characters.
1980 unsigned Value = Str[i] - '0';
1981
1982 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1983 ++i;
1984 Value = Value * 8 + (Str[i] - '0');
1985
1986 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1987 ++i;
1988 Value = Value * 8 + (Str[i] - '0');
1989 }
1990 }
1991
1992 if (Value > 255)
1993 return TokError("invalid octal escape sequence (out of range)");
1994
1995 Data += (unsigned char) Value;
1996 continue;
1997 }
1998
1999 // Otherwise recognize individual escapes.
2000 switch (Str[i]) {
2001 default:
2002 // Just reject invalid escape sequences for now.
2003 return TokError("invalid escape sequence (unrecognized character)");
2004
2005 case 'b': Data += '\b'; break;
2006 case 'f': Data += '\f'; break;
2007 case 'n': Data += '\n'; break;
2008 case 'r': Data += '\r'; break;
2009 case 't': Data += '\t'; break;
2010 case '"': Data += '"'; break;
2011 case '\\': Data += '\\'; break;
2012 }
2013 }
2014
2015 return false;
2016}
2017
Daniel Dunbara0d14262009-06-24 23:30:00 +00002018/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002019/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2020bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002021 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002022 CheckForValidSection();
2023
Daniel Dunbara0d14262009-06-24 23:30:00 +00002024 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002025 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002026 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002027
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002028 std::string Data;
2029 if (ParseEscapedString(Data))
2030 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002031
2032 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002033 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002034 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2035
Sean Callanan79ed1a82010-01-19 20:22:31 +00002036 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002037
2038 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002039 break;
2040
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002041 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002042 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002043 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002044 }
2045 }
2046
Sean Callanan79ed1a82010-01-19 20:22:31 +00002047 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002048 return false;
2049}
2050
2051/// ParseDirectiveValue
2052/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2053bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002054 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002055 CheckForValidSection();
2056
Daniel Dunbara0d14262009-06-24 23:30:00 +00002057 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002058 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002059 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002060 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002061 return true;
2062
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002063 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002064 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2065 assert(Size <= 8 && "Invalid size");
2066 uint64_t IntValue = MCE->getValue();
2067 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2068 return Error(ExprLoc, "literal value out of range for directive");
2069 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2070 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002071 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002072
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002073 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002074 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002075
Daniel Dunbara0d14262009-06-24 23:30:00 +00002076 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002077 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002078 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002079 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002080 }
2081 }
2082
Sean Callanan79ed1a82010-01-19 20:22:31 +00002083 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002084 return false;
2085}
2086
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002087/// ParseDirectiveRealValue
2088/// ::= (.single | .double) [ expression (, expression)* ]
2089bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2090 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2091 CheckForValidSection();
2092
2093 for (;;) {
2094 // We don't truly support arithmetic on floating point expressions, so we
2095 // have to manually parse unary prefixes.
2096 bool IsNeg = false;
2097 if (getLexer().is(AsmToken::Minus)) {
2098 Lex();
2099 IsNeg = true;
2100 } else if (getLexer().is(AsmToken::Plus))
2101 Lex();
2102
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002103 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002104 getLexer().isNot(AsmToken::Real) &&
2105 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002106 return TokError("unexpected token in directive");
2107
2108 // Convert to an APFloat.
2109 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002110 StringRef IDVal = getTok().getString();
2111 if (getLexer().is(AsmToken::Identifier)) {
2112 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2113 Value = APFloat::getInf(Semantics);
2114 else if (!IDVal.compare_lower("nan"))
2115 Value = APFloat::getNaN(Semantics, false, ~0);
2116 else
2117 return TokError("invalid floating point literal");
2118 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002119 APFloat::opInvalidOp)
2120 return TokError("invalid floating point literal");
2121 if (IsNeg)
2122 Value.changeSign();
2123
2124 // Consume the numeric token.
2125 Lex();
2126
2127 // Emit the value as an integer.
2128 APInt AsInt = Value.bitcastToAPInt();
2129 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2130 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2131
2132 if (getLexer().is(AsmToken::EndOfStatement))
2133 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002134
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002135 if (getLexer().isNot(AsmToken::Comma))
2136 return TokError("unexpected token in directive");
2137 Lex();
2138 }
2139 }
2140
2141 Lex();
2142 return false;
2143}
2144
Daniel Dunbara0d14262009-06-24 23:30:00 +00002145/// ParseDirectiveSpace
2146/// ::= .space expression [ , expression ]
2147bool AsmParser::ParseDirectiveSpace() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002148 CheckForValidSection();
2149
Daniel Dunbara0d14262009-06-24 23:30:00 +00002150 int64_t NumBytes;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002151 if (ParseAbsoluteExpression(NumBytes))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002152 return true;
2153
2154 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002155 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2156 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002157 return TokError("unexpected token in '.space' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002158 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002159
Daniel Dunbar475839e2009-06-29 20:37:27 +00002160 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002161 return true;
2162
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002163 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002164 return TokError("unexpected token in '.space' directive");
2165 }
2166
Sean Callanan79ed1a82010-01-19 20:22:31 +00002167 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002168
2169 if (NumBytes <= 0)
2170 return TokError("invalid number of bytes in '.space' directive");
2171
2172 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002173 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002174
2175 return false;
2176}
2177
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002178/// ParseDirectiveZero
2179/// ::= .zero expression
2180bool AsmParser::ParseDirectiveZero() {
2181 CheckForValidSection();
2182
2183 int64_t NumBytes;
2184 if (ParseAbsoluteExpression(NumBytes))
2185 return true;
2186
Rafael Espindolae452b172010-10-05 19:42:57 +00002187 int64_t Val = 0;
2188 if (getLexer().is(AsmToken::Comma)) {
2189 Lex();
2190 if (ParseAbsoluteExpression(Val))
2191 return true;
2192 }
2193
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002194 if (getLexer().isNot(AsmToken::EndOfStatement))
2195 return TokError("unexpected token in '.zero' directive");
2196
2197 Lex();
2198
Rafael Espindolae452b172010-10-05 19:42:57 +00002199 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002200
2201 return false;
2202}
2203
Daniel Dunbara0d14262009-06-24 23:30:00 +00002204/// ParseDirectiveFill
2205/// ::= .fill expression , expression , expression
2206bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002207 CheckForValidSection();
2208
Daniel Dunbara0d14262009-06-24 23:30:00 +00002209 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002210 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002211 return true;
2212
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002213 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002214 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002215 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002216
Daniel Dunbara0d14262009-06-24 23:30:00 +00002217 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002218 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002219 return true;
2220
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002221 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002222 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002223 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002224
Daniel Dunbara0d14262009-06-24 23:30:00 +00002225 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002226 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002227 return true;
2228
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002229 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002230 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002231
Sean Callanan79ed1a82010-01-19 20:22:31 +00002232 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002233
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002234 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2235 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002236
2237 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002238 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002239
2240 return false;
2241}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002242
2243/// ParseDirectiveOrg
2244/// ::= .org expression [ , expression ]
2245bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002246 CheckForValidSection();
2247
Daniel Dunbar821e3332009-08-31 08:09:28 +00002248 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002249 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002250 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002251 return true;
2252
2253 // Parse optional fill expression.
2254 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002255 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2256 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002257 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002258 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002259
Daniel Dunbar475839e2009-06-29 20:37:27 +00002260 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002261 return true;
2262
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002263 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002264 return TokError("unexpected token in '.org' directive");
2265 }
2266
Sean Callanan79ed1a82010-01-19 20:22:31 +00002267 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002268
Jim Grosbachebd4c052012-01-27 00:37:08 +00002269 // Only limited forms of relocatable expressions are accepted here, it
2270 // has to be relative to the current section. The streamer will return
2271 // 'true' if the expression wasn't evaluatable.
2272 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2273 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002274
2275 return false;
2276}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002277
2278/// ParseDirectiveAlign
2279/// ::= {.align, ...} expression [ , expression [ , expression ]]
2280bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002281 CheckForValidSection();
2282
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002283 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002284 int64_t Alignment;
2285 if (ParseAbsoluteExpression(Alignment))
2286 return true;
2287
2288 SMLoc MaxBytesLoc;
2289 bool HasFillExpr = false;
2290 int64_t FillExpr = 0;
2291 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002292 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2293 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002294 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002295 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002296
2297 // The fill expression can be omitted while specifying a maximum number of
2298 // alignment bytes, e.g:
2299 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002300 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002301 HasFillExpr = true;
2302 if (ParseAbsoluteExpression(FillExpr))
2303 return true;
2304 }
2305
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002306 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2307 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002308 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002309 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002310
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002311 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002312 if (ParseAbsoluteExpression(MaxBytesToFill))
2313 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002314
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002315 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002316 return TokError("unexpected token in directive");
2317 }
2318 }
2319
Sean Callanan79ed1a82010-01-19 20:22:31 +00002320 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002321
Daniel Dunbar648ac512010-05-17 21:54:30 +00002322 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002323 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002324
2325 // Compute alignment in bytes.
2326 if (IsPow2) {
2327 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002328 if (Alignment >= 32) {
2329 Error(AlignmentLoc, "invalid alignment value");
2330 Alignment = 31;
2331 }
2332
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002333 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002334 }
2335
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002336 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002337 if (MaxBytesLoc.isValid()) {
2338 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002339 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2340 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002341 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002342 }
2343
2344 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002345 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2346 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002347 MaxBytesToFill = 0;
2348 }
2349 }
2350
Daniel Dunbar648ac512010-05-17 21:54:30 +00002351 // Check whether we should use optimal code alignment for this .align
2352 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002353 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002354 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2355 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002356 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002357 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002358 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002359 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2360 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002361 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002362
2363 return false;
2364}
2365
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002366/// ParseDirectiveSymbolAttribute
2367/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00002368bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002369 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002370 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002371 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00002372 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002373
2374 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00002375 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002376
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002377 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002378
Jim Grosbach10ec6502011-09-15 17:56:49 +00002379 // Assembler local symbols don't make any sense here. Complain loudly.
2380 if (Sym->isTemporary())
2381 return Error(Loc, "non-local symbol required in directive");
2382
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002383 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002384
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002385 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002386 break;
2387
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002388 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002389 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002390 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002391 }
2392 }
2393
Sean Callanan79ed1a82010-01-19 20:22:31 +00002394 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00002395 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002396}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002397
2398/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00002399/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2400bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002401 CheckForValidSection();
2402
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002403 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002404 StringRef Name;
2405 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002406 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002407
Daniel Dunbar76c4d762009-07-31 21:55:09 +00002408 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002409 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002410
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002411 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002412 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002413 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002414
2415 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002416 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002417 if (ParseAbsoluteExpression(Size))
2418 return true;
2419
2420 int64_t Pow2Alignment = 0;
2421 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002422 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00002423 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002424 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002425 if (ParseAbsoluteExpression(Pow2Alignment))
2426 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002427
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002428 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2429 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00002430 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2431
Chris Lattner258281d2010-01-19 06:22:22 +00002432 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002433 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2434 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00002435 if (!isPowerOf2_64(Pow2Alignment))
2436 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2437 Pow2Alignment = Log2_64(Pow2Alignment);
2438 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002439 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002440
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002441 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00002442 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002443
Sean Callanan79ed1a82010-01-19 20:22:31 +00002444 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002445
Chris Lattner1fc3d752009-07-09 17:25:12 +00002446 // NOTE: a size of zero for a .comm should create a undefined symbol
2447 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002448 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002449 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2450 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002451
Eric Christopherc260a3e2010-05-14 01:38:54 +00002452 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002453 // may internally end up wanting an alignment in bytes.
2454 // FIXME: Diagnose overflow.
2455 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002456 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2457 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002458
Daniel Dunbar8906ff12009-08-22 07:22:36 +00002459 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002460 return Error(IDLoc, "invalid symbol redefinition");
2461
Chris Lattner1fc3d752009-07-09 17:25:12 +00002462 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002463 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00002464 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002465 return false;
2466 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002467
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002468 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002469 return false;
2470}
Chris Lattner9be3fee2009-07-10 22:20:30 +00002471
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002472/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002473/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002474bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002475 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002476 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002477
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002478 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002479 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002480 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002481
Sean Callanan79ed1a82010-01-19 20:22:31 +00002482 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002483
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002484 if (Str.empty())
2485 Error(Loc, ".abort detected. Assembly stopping.");
2486 else
2487 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002488 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002489
2490 return false;
2491}
Kevin Enderby71148242009-07-14 21:35:03 +00002492
Kevin Enderby1f049b22009-07-14 23:21:55 +00002493/// ParseDirectiveInclude
2494/// ::= .include "filename"
2495bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002496 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002497 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002498
Sean Callanan18b83232010-01-19 21:44:56 +00002499 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002500 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002501 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00002502
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002503 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002504 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002505
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002506 // Strip the quotes.
2507 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002508
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002509 // Attempt to switch the lexer to the included file before consuming the end
2510 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00002511 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00002512 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002513 return true;
2514 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00002515
2516 return false;
2517}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00002518
Kevin Enderbyc55acca2011-12-14 21:47:48 +00002519/// ParseDirectiveIncbin
2520/// ::= .incbin "filename"
2521bool AsmParser::ParseDirectiveIncbin() {
2522 if (getLexer().isNot(AsmToken::String))
2523 return TokError("expected string in '.incbin' directive");
2524
2525 std::string Filename = getTok().getString();
2526 SMLoc IncbinLoc = getLexer().getLoc();
2527 Lex();
2528
2529 if (getLexer().isNot(AsmToken::EndOfStatement))
2530 return TokError("unexpected token in '.incbin' directive");
2531
2532 // Strip the quotes.
2533 Filename = Filename.substr(1, Filename.size()-2);
2534
2535 // Attempt to process the included file.
2536 if (ProcessIncbinFile(Filename)) {
2537 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2538 return true;
2539 }
2540
2541 return false;
2542}
2543
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002544/// ParseDirectiveIf
2545/// ::= .if expression
2546bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002547 TheCondStack.push_back(TheCondState);
2548 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00002549 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002550 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00002551 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002552 int64_t ExprValue;
2553 if (ParseAbsoluteExpression(ExprValue))
2554 return true;
2555
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002556 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002557 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002558
Sean Callanan79ed1a82010-01-19 20:22:31 +00002559 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002560
2561 TheCondState.CondMet = ExprValue;
2562 TheCondState.Ignore = !TheCondState.CondMet;
2563 }
2564
2565 return false;
2566}
2567
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002568/// ParseDirectiveIfb
2569/// ::= .ifb string
2570bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2571 TheCondStack.push_back(TheCondState);
2572 TheCondState.TheCond = AsmCond::IfCond;
2573
Benjamin Kramer29739e72012-05-12 16:52:21 +00002574 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002575 EatToEndOfStatement();
2576 } else {
2577 StringRef Str = ParseStringToEndOfStatement();
2578
2579 if (getLexer().isNot(AsmToken::EndOfStatement))
2580 return TokError("unexpected token in '.ifb' directive");
2581
2582 Lex();
2583
2584 TheCondState.CondMet = ExpectBlank == Str.empty();
2585 TheCondState.Ignore = !TheCondState.CondMet;
2586 }
2587
2588 return false;
2589}
2590
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002591/// ParseDirectiveIfc
2592/// ::= .ifc string1, string2
2593bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2594 TheCondStack.push_back(TheCondState);
2595 TheCondState.TheCond = AsmCond::IfCond;
2596
Benjamin Kramer29739e72012-05-12 16:52:21 +00002597 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002598 EatToEndOfStatement();
2599 } else {
2600 StringRef Str1 = ParseStringToComma();
2601
2602 if (getLexer().isNot(AsmToken::Comma))
2603 return TokError("unexpected token in '.ifc' directive");
2604
2605 Lex();
2606
2607 StringRef Str2 = ParseStringToEndOfStatement();
2608
2609 if (getLexer().isNot(AsmToken::EndOfStatement))
2610 return TokError("unexpected token in '.ifc' directive");
2611
2612 Lex();
2613
2614 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2615 TheCondState.Ignore = !TheCondState.CondMet;
2616 }
2617
2618 return false;
2619}
2620
2621/// ParseDirectiveIfdef
2622/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00002623bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2624 StringRef Name;
2625 TheCondStack.push_back(TheCondState);
2626 TheCondState.TheCond = AsmCond::IfCond;
2627
2628 if (TheCondState.Ignore) {
2629 EatToEndOfStatement();
2630 } else {
2631 if (ParseIdentifier(Name))
2632 return TokError("expected identifier after '.ifdef'");
2633
2634 Lex();
2635
2636 MCSymbol *Sym = getContext().LookupSymbol(Name);
2637
2638 if (expect_defined)
2639 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2640 else
2641 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2642 TheCondState.Ignore = !TheCondState.CondMet;
2643 }
2644
2645 return false;
2646}
2647
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002648/// ParseDirectiveElseIf
2649/// ::= .elseif expression
2650bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2651 if (TheCondState.TheCond != AsmCond::IfCond &&
2652 TheCondState.TheCond != AsmCond::ElseIfCond)
2653 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2654 " an .elseif");
2655 TheCondState.TheCond = AsmCond::ElseIfCond;
2656
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002657 bool LastIgnoreState = false;
2658 if (!TheCondStack.empty())
2659 LastIgnoreState = TheCondStack.back().Ignore;
2660 if (LastIgnoreState || TheCondState.CondMet) {
2661 TheCondState.Ignore = true;
2662 EatToEndOfStatement();
2663 }
2664 else {
2665 int64_t ExprValue;
2666 if (ParseAbsoluteExpression(ExprValue))
2667 return true;
2668
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002669 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002670 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002671
Sean Callanan79ed1a82010-01-19 20:22:31 +00002672 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002673 TheCondState.CondMet = ExprValue;
2674 TheCondState.Ignore = !TheCondState.CondMet;
2675 }
2676
2677 return false;
2678}
2679
2680/// ParseDirectiveElse
2681/// ::= .else
2682bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002683 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002684 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002685
Sean Callanan79ed1a82010-01-19 20:22:31 +00002686 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002687
2688 if (TheCondState.TheCond != AsmCond::IfCond &&
2689 TheCondState.TheCond != AsmCond::ElseIfCond)
2690 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2691 ".elseif");
2692 TheCondState.TheCond = AsmCond::ElseCond;
2693 bool LastIgnoreState = false;
2694 if (!TheCondStack.empty())
2695 LastIgnoreState = TheCondStack.back().Ignore;
2696 if (LastIgnoreState || TheCondState.CondMet)
2697 TheCondState.Ignore = true;
2698 else
2699 TheCondState.Ignore = false;
2700
2701 return false;
2702}
2703
2704/// ParseDirectiveEndIf
2705/// ::= .endif
2706bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002707 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002708 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002709
Sean Callanan79ed1a82010-01-19 20:22:31 +00002710 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002711
2712 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2713 TheCondStack.empty())
2714 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2715 ".else");
2716 if (!TheCondStack.empty()) {
2717 TheCondState = TheCondStack.back();
2718 TheCondStack.pop_back();
2719 }
2720
2721 return false;
2722}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002723
2724/// ParseDirectiveFile
Nick Lewycky44d798d2011-10-17 23:05:28 +00002725/// ::= .file [number] filename
2726/// ::= .file number directory filename
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002727bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002728 // FIXME: I'm not sure what this is.
2729 int64_t FileNumber = -1;
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002730 SMLoc FileNumberLoc = getLexer().getLoc();
Daniel Dunbareceec052010-07-12 17:45:27 +00002731 if (getLexer().is(AsmToken::Integer)) {
Sean Callanan18b83232010-01-19 21:44:56 +00002732 FileNumber = getTok().getIntVal();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002733 Lex();
Daniel Dunbareceec052010-07-12 17:45:27 +00002734
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002735 if (FileNumber < 1)
2736 return TokError("file number less than one");
2737 }
2738
Daniel Dunbareceec052010-07-12 17:45:27 +00002739 if (getLexer().isNot(AsmToken::String))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002740 return TokError("unexpected token in '.file' directive");
Daniel Dunbareceec052010-07-12 17:45:27 +00002741
Nick Lewycky44d798d2011-10-17 23:05:28 +00002742 // Usually the directory and filename together, otherwise just the directory.
2743 StringRef Path = getTok().getString();
2744 Path = Path.substr(1, Path.size()-2);
Sean Callanan79ed1a82010-01-19 20:22:31 +00002745 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002746
Nick Lewycky44d798d2011-10-17 23:05:28 +00002747 StringRef Directory;
2748 StringRef Filename;
2749 if (getLexer().is(AsmToken::String)) {
2750 if (FileNumber == -1)
2751 return TokError("explicit path specified, but no file number");
2752 Filename = getTok().getString();
2753 Filename = Filename.substr(1, Filename.size()-2);
2754 Directory = Path;
2755 Lex();
2756 } else {
2757 Filename = Path;
2758 }
2759
Daniel Dunbareceec052010-07-12 17:45:27 +00002760 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002761 return TokError("unexpected token in '.file' directive");
2762
Chris Lattnerd32e8032010-01-25 19:02:58 +00002763 if (FileNumber == -1)
Daniel Dunbareceec052010-07-12 17:45:27 +00002764 getStreamer().EmitFileDirective(Filename);
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002765 else {
Kevin Enderby8704b782012-01-11 18:04:47 +00002766 if (getContext().getGenDwarfForAssembly() == true)
2767 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2768 "used to generate dwarf debug info for assembly code");
2769
Nick Lewycky44d798d2011-10-17 23:05:28 +00002770 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002771 Error(FileNumberLoc, "file number already allocated");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002772 }
Daniel Dunbareceec052010-07-12 17:45:27 +00002773
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002774 return false;
2775}
2776
2777/// ParseDirectiveLine
2778/// ::= .line [number]
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002779bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbareceec052010-07-12 17:45:27 +00002780 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2781 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002782 return TokError("unexpected token in '.line' directive");
2783
Sean Callanan18b83232010-01-19 21:44:56 +00002784 int64_t LineNumber = getTok().getIntVal();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002785 (void) LineNumber;
Sean Callanan79ed1a82010-01-19 20:22:31 +00002786 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002787
2788 // FIXME: Do something with the .line.
2789 }
2790
Daniel Dunbareceec052010-07-12 17:45:27 +00002791 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar839348a2010-07-01 20:20:01 +00002792 return TokError("unexpected token in '.line' directive");
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002793
2794 return false;
2795}
2796
2797
2798/// ParseDirectiveLoc
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002799/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002800/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2801/// The first number is a file number, must have been previously assigned with
2802/// a .file directive, the second number is the line number and optionally the
2803/// third number is a column position (zero if not specified). The remaining
2804/// optional items are .loc sub-directives.
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002805bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002806
Daniel Dunbareceec052010-07-12 17:45:27 +00002807 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002808 return TokError("unexpected token in '.loc' directive");
Sean Callanan18b83232010-01-19 21:44:56 +00002809 int64_t FileNumber = getTok().getIntVal();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002810 if (FileNumber < 1)
2811 return TokError("file number less than one in '.loc' directive");
Kevin Enderby3f55c242010-10-04 20:17:24 +00002812 if (!getContext().isValidDwarfFileNumber(FileNumber))
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002813 return TokError("unassigned file number in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002814 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002815
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002816 int64_t LineNumber = 0;
2817 if (getLexer().is(AsmToken::Integer)) {
2818 LineNumber = getTok().getIntVal();
2819 if (LineNumber < 1)
2820 return TokError("line number less than one in '.loc' directive");
2821 Lex();
2822 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002823
2824 int64_t ColumnPos = 0;
2825 if (getLexer().is(AsmToken::Integer)) {
2826 ColumnPos = getTok().getIntVal();
2827 if (ColumnPos < 0)
2828 return TokError("column position less than zero in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002829 Lex();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002830 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002831
Kevin Enderbyc0957932010-09-30 16:52:03 +00002832 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002833 unsigned Isa = 0;
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002834 int64_t Discriminator = 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002835 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2836 for (;;) {
2837 if (getLexer().is(AsmToken::EndOfStatement))
2838 break;
2839
2840 StringRef Name;
2841 SMLoc Loc = getTok().getLoc();
2842 if (getParser().ParseIdentifier(Name))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002843 return TokError("unexpected token in '.loc' directive");
2844
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002845 if (Name == "basic_block")
2846 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2847 else if (Name == "prologue_end")
2848 Flags |= DWARF2_FLAG_PROLOGUE_END;
2849 else if (Name == "epilogue_begin")
2850 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2851 else if (Name == "is_stmt") {
2852 SMLoc Loc = getTok().getLoc();
2853 const MCExpr *Value;
2854 if (getParser().ParseExpression(Value))
2855 return true;
2856 // The expression must be the constant 0 or 1.
2857 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2858 int Value = MCE->getValue();
2859 if (Value == 0)
2860 Flags &= ~DWARF2_FLAG_IS_STMT;
2861 else if (Value == 1)
2862 Flags |= DWARF2_FLAG_IS_STMT;
2863 else
2864 return Error(Loc, "is_stmt value not 0 or 1");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002865 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002866 else {
2867 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2868 }
2869 }
2870 else if (Name == "isa") {
2871 SMLoc Loc = getTok().getLoc();
2872 const MCExpr *Value;
2873 if (getParser().ParseExpression(Value))
2874 return true;
2875 // The expression must be a constant greater or equal to 0.
2876 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2877 int Value = MCE->getValue();
2878 if (Value < 0)
2879 return Error(Loc, "isa number less than zero");
2880 Isa = Value;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002881 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002882 else {
2883 return Error(Loc, "isa number not a constant value");
2884 }
2885 }
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002886 else if (Name == "discriminator") {
2887 if (getParser().ParseAbsoluteExpression(Discriminator))
2888 return true;
2889 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002890 else {
2891 return Error(Loc, "unknown sub-directive in '.loc' directive");
2892 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002893
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002894 if (getLexer().is(AsmToken::EndOfStatement))
2895 break;
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002896 }
2897 }
2898
Rafael Espindolaaf6b58082010-11-16 21:20:32 +00002899 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
Devang Patel3f3bf932011-04-18 20:26:49 +00002900 Isa, Discriminator, StringRef());
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002901
2902 return false;
2903}
2904
Daniel Dunbar138abae2010-10-16 04:56:42 +00002905/// ParseDirectiveStabs
2906/// ::= .stabs string, number, number, number
2907bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2908 SMLoc DirectiveLoc) {
2909 return TokError("unsupported directive '" + Directive + "'");
2910}
2911
Rafael Espindolaf9efd832011-05-10 01:10:18 +00002912/// ParseDirectiveCFISections
2913/// ::= .cfi_sections section [, section]
2914bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2915 SMLoc DirectiveLoc) {
2916 StringRef Name;
2917 bool EH = false;
2918 bool Debug = false;
2919
2920 if (getParser().ParseIdentifier(Name))
2921 return TokError("Expected an identifier");
2922
2923 if (Name == ".eh_frame")
2924 EH = true;
2925 else if (Name == ".debug_frame")
2926 Debug = true;
2927
2928 if (getLexer().is(AsmToken::Comma)) {
2929 Lex();
2930
2931 if (getParser().ParseIdentifier(Name))
2932 return TokError("Expected an identifier");
2933
2934 if (Name == ".eh_frame")
2935 EH = true;
2936 else if (Name == ".debug_frame")
2937 Debug = true;
2938 }
2939
2940 getStreamer().EmitCFISections(EH, Debug);
2941
2942 return false;
2943}
2944
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002945/// ParseDirectiveCFIStartProc
2946/// ::= .cfi_startproc
2947bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2948 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002949 getStreamer().EmitCFIStartProc();
2950 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002951}
2952
2953/// ParseDirectiveCFIEndProc
2954/// ::= .cfi_endproc
2955bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002956 getStreamer().EmitCFIEndProc();
2957 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002958}
2959
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002960/// ParseRegisterOrRegisterNumber - parse register name or number.
2961bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2962 SMLoc DirectiveLoc) {
2963 unsigned RegNo;
2964
Jim Grosbach6f888a82011-06-02 17:14:04 +00002965 if (getLexer().isNot(AsmToken::Integer)) {
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002966 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2967 DirectiveLoc))
2968 return true;
Evan Cheng0e6a0522011-07-18 20:57:22 +00002969 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002970 } else
2971 return getParser().ParseAbsoluteExpression(Register);
Jim Grosbachde2f5f42011-02-11 19:05:56 +00002972
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002973 return false;
2974}
2975
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002976/// ParseDirectiveCFIDefCfa
2977/// ::= .cfi_def_cfa register, offset
2978bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2979 SMLoc DirectiveLoc) {
2980 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002981 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002982 return true;
2983
2984 if (getLexer().isNot(AsmToken::Comma))
2985 return TokError("unexpected token in directive");
2986 Lex();
2987
2988 int64_t Offset = 0;
2989 if (getParser().ParseAbsoluteExpression(Offset))
2990 return true;
2991
Rafael Espindola066c2f42011-04-12 23:59:07 +00002992 getStreamer().EmitCFIDefCfa(Register, Offset);
2993 return false;
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002994}
2995
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002996/// ParseDirectiveCFIDefCfaOffset
2997/// ::= .cfi_def_cfa_offset offset
2998bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2999 SMLoc DirectiveLoc) {
3000 int64_t Offset = 0;
3001 if (getParser().ParseAbsoluteExpression(Offset))
3002 return true;
3003
Rafael Espindola066c2f42011-04-12 23:59:07 +00003004 getStreamer().EmitCFIDefCfaOffset(Offset);
3005 return false;
Rafael Espindola53abbe52011-04-11 20:29:16 +00003006}
3007
3008/// ParseDirectiveCFIAdjustCfaOffset
3009/// ::= .cfi_adjust_cfa_offset adjustment
3010bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3011 SMLoc DirectiveLoc) {
3012 int64_t Adjustment = 0;
3013 if (getParser().ParseAbsoluteExpression(Adjustment))
3014 return true;
3015
Rafael Espindola5d7dcd32011-04-12 18:53:30 +00003016 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3017 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003018}
3019
3020/// ParseDirectiveCFIDefCfaRegister
3021/// ::= .cfi_def_cfa_register register
3022bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3023 SMLoc DirectiveLoc) {
3024 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003025 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003026 return true;
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003027
Rafael Espindola066c2f42011-04-12 23:59:07 +00003028 getStreamer().EmitCFIDefCfaRegister(Register);
3029 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003030}
3031
3032/// ParseDirectiveCFIOffset
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003033/// ::= .cfi_offset register, offset
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003034bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3035 int64_t Register = 0;
3036 int64_t Offset = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003037
3038 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003039 return true;
3040
3041 if (getLexer().isNot(AsmToken::Comma))
3042 return TokError("unexpected token in directive");
3043 Lex();
3044
3045 if (getParser().ParseAbsoluteExpression(Offset))
3046 return true;
3047
Rafael Espindola066c2f42011-04-12 23:59:07 +00003048 getStreamer().EmitCFIOffset(Register, Offset);
3049 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003050}
3051
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003052/// ParseDirectiveCFIRelOffset
3053/// ::= .cfi_rel_offset register, offset
3054bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3055 SMLoc DirectiveLoc) {
3056 int64_t Register = 0;
3057
3058 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3059 return true;
3060
3061 if (getLexer().isNot(AsmToken::Comma))
3062 return TokError("unexpected token in directive");
3063 Lex();
3064
3065 int64_t Offset = 0;
3066 if (getParser().ParseAbsoluteExpression(Offset))
3067 return true;
3068
Rafael Espindola25f492e2011-04-12 16:12:03 +00003069 getStreamer().EmitCFIRelOffset(Register, Offset);
3070 return false;
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003071}
3072
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003073static bool isValidEncoding(int64_t Encoding) {
3074 if (Encoding & ~0xff)
3075 return false;
3076
3077 if (Encoding == dwarf::DW_EH_PE_omit)
3078 return true;
3079
3080 const unsigned Format = Encoding & 0xf;
3081 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3082 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3083 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3084 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3085 return false;
3086
Rafael Espindolacaf11582010-12-29 04:31:26 +00003087 const unsigned Application = Encoding & 0x70;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003088 if (Application != dwarf::DW_EH_PE_absptr &&
Rafael Espindolacaf11582010-12-29 04:31:26 +00003089 Application != dwarf::DW_EH_PE_pcrel)
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003090 return false;
3091
3092 return true;
3093}
3094
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003095/// ParseDirectiveCFIPersonalityOrLsda
3096/// ::= .cfi_personality encoding, [symbol_name]
3097/// ::= .cfi_lsda encoding, [symbol_name]
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003098bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003099 SMLoc DirectiveLoc) {
3100 int64_t Encoding = 0;
3101 if (getParser().ParseAbsoluteExpression(Encoding))
3102 return true;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003103 if (Encoding == dwarf::DW_EH_PE_omit)
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003104 return false;
3105
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003106 if (!isValidEncoding(Encoding))
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003107 return TokError("unsupported encoding.");
3108
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003109 if (getLexer().isNot(AsmToken::Comma))
3110 return TokError("unexpected token in directive");
3111 Lex();
3112
3113 StringRef Name;
3114 if (getParser().ParseIdentifier(Name))
3115 return TokError("expected identifier in directive");
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003116
3117 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3118
3119 if (IDVal == ".cfi_personality")
Rafael Espindola066c2f42011-04-12 23:59:07 +00003120 getStreamer().EmitCFIPersonality(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003121 else {
3122 assert(IDVal == ".cfi_lsda");
Rafael Espindola066c2f42011-04-12 23:59:07 +00003123 getStreamer().EmitCFILsda(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003124 }
Rafael Espindola066c2f42011-04-12 23:59:07 +00003125 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003126}
3127
Rafael Espindolafe024d02010-12-28 18:36:23 +00003128/// ParseDirectiveCFIRememberState
3129/// ::= .cfi_remember_state
3130bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3131 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003132 getStreamer().EmitCFIRememberState();
3133 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003134}
3135
3136/// ParseDirectiveCFIRestoreState
3137/// ::= .cfi_remember_state
3138bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3139 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003140 getStreamer().EmitCFIRestoreState();
3141 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003142}
3143
Rafael Espindolac5754392011-04-12 15:31:05 +00003144/// ParseDirectiveCFISameValue
3145/// ::= .cfi_same_value register
3146bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3147 SMLoc DirectiveLoc) {
3148 int64_t Register = 0;
3149
3150 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3151 return true;
3152
3153 getStreamer().EmitCFISameValue(Register);
3154
3155 return false;
3156}
3157
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003158/// ParseDirectiveCFIRestore
3159/// ::= .cfi_restore register
3160bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003161 SMLoc DirectiveLoc) {
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003162 int64_t Register = 0;
3163 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3164 return true;
3165
3166 getStreamer().EmitCFIRestore(Register);
3167
3168 return false;
3169}
3170
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003171/// ParseDirectiveCFIEscape
3172/// ::= .cfi_escape expression[,...]
3173bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003174 SMLoc DirectiveLoc) {
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003175 std::string Values;
3176 int64_t CurrValue;
3177 if (getParser().ParseAbsoluteExpression(CurrValue))
3178 return true;
3179
3180 Values.push_back((uint8_t)CurrValue);
3181
3182 while (getLexer().is(AsmToken::Comma)) {
3183 Lex();
3184
3185 if (getParser().ParseAbsoluteExpression(CurrValue))
3186 return true;
3187
3188 Values.push_back((uint8_t)CurrValue);
3189 }
3190
3191 getStreamer().EmitCFIEscape(Values);
3192 return false;
3193}
3194
Rafael Espindola16d7d432012-01-23 21:51:52 +00003195/// ParseDirectiveCFISignalFrame
3196/// ::= .cfi_signal_frame
3197bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3198 SMLoc DirectiveLoc) {
3199 if (getLexer().isNot(AsmToken::EndOfStatement))
3200 return Error(getLexer().getLoc(),
3201 "unexpected token in '" + Directive + "' directive");
3202
3203 getStreamer().EmitCFISignalFrame();
3204
3205 return false;
3206}
3207
Daniel Dunbar3c802de2010-07-18 18:38:02 +00003208/// ParseDirectiveMacrosOnOff
3209/// ::= .macros_on
3210/// ::= .macros_off
3211bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3212 SMLoc DirectiveLoc) {
3213 if (getLexer().isNot(AsmToken::EndOfStatement))
3214 return Error(getLexer().getLoc(),
3215 "unexpected token in '" + Directive + "' directive");
3216
3217 getParser().MacrosEnabled = Directive == ".macros_on";
3218
3219 return false;
3220}
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003221
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003222/// ParseDirectiveMacro
Rafael Espindola65366442011-06-05 02:43:45 +00003223/// ::= .macro name [parameters]
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003224bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3225 SMLoc DirectiveLoc) {
3226 StringRef Name;
3227 if (getParser().ParseIdentifier(Name))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003228 return TokError("expected identifier in '.macro' directive");
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003229
Rafael Espindola8a403d32012-08-08 14:51:03 +00003230 MacroParameters Parameters;
Preston Gurd7b6f2032012-09-19 20:36:12 +00003231 // Argument delimiter is initially unknown. It will be set by
3232 // ParseMacroArgument()
3233 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindola65366442011-06-05 02:43:45 +00003234 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Rafael Espindola7996d042012-08-21 16:06:48 +00003235 for (;;) {
3236 MacroParameter Parameter;
Preston Gurd6c9176a2012-09-19 20:29:04 +00003237 if (getParser().ParseIdentifier(Parameter.first))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003238 return TokError("expected identifier in '.macro' directive");
Preston Gurd6c9176a2012-09-19 20:29:04 +00003239
3240 if (getLexer().is(AsmToken::Equal)) {
3241 Lex();
Preston Gurd7b6f2032012-09-19 20:36:12 +00003242 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
Preston Gurd6c9176a2012-09-19 20:29:04 +00003243 return true;
3244 }
3245
Rafael Espindola65366442011-06-05 02:43:45 +00003246 Parameters.push_back(Parameter);
3247
Preston Gurd7b6f2032012-09-19 20:36:12 +00003248 if (getLexer().is(AsmToken::Comma))
3249 Lex();
3250 else if (getLexer().is(AsmToken::EndOfStatement))
Rafael Espindola65366442011-06-05 02:43:45 +00003251 break;
Rafael Espindola65366442011-06-05 02:43:45 +00003252 }
3253 }
3254
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003255 // Eat the end of statement.
3256 Lex();
3257
3258 AsmToken EndToken, StartToken = getTok();
3259
3260 // Lex the macro definition.
3261 for (;;) {
3262 // Check whether we have reached the end of the file.
3263 if (getLexer().is(AsmToken::Eof))
3264 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3265
3266 // Otherwise, check whether we have reach the .endmacro.
3267 if (getLexer().is(AsmToken::Identifier) &&
3268 (getTok().getIdentifier() == ".endm" ||
3269 getTok().getIdentifier() == ".endmacro")) {
3270 EndToken = getTok();
3271 Lex();
3272 if (getLexer().isNot(AsmToken::EndOfStatement))
3273 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3274 "' directive");
3275 break;
3276 }
3277
3278 // Otherwise, scan til the end of the statement.
3279 getParser().EatToEndOfStatement();
3280 }
3281
3282 if (getParser().MacroMap.lookup(Name)) {
3283 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3284 }
3285
3286 const char *BodyStart = StartToken.getLoc().getPointer();
3287 const char *BodyEnd = EndToken.getLoc().getPointer();
3288 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Rafael Espindola65366442011-06-05 02:43:45 +00003289 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003290 return false;
3291}
3292
3293/// ParseDirectiveEndMacro
3294/// ::= .endm
3295/// ::= .endmacro
3296bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
Rafael Espindola8a403d32012-08-08 14:51:03 +00003297 SMLoc DirectiveLoc) {
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003298 if (getLexer().isNot(AsmToken::EndOfStatement))
3299 return TokError("unexpected token in '" + Directive + "' directive");
3300
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00003301 // If we are inside a macro instantiation, terminate the current
3302 // instantiation.
3303 if (!getParser().ActiveMacros.empty()) {
3304 getParser().HandleMacroExit();
3305 return false;
3306 }
3307
3308 // Otherwise, this .endmacro is a stray entry in the file; well formed
3309 // .endmacro directives are handled during the macro definition parsing.
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003310 return TokError("unexpected '" + Directive + "' in file, "
3311 "no current macro definition");
3312}
3313
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +00003314/// ParseDirectivePurgeMacro
3315/// ::= .purgem
3316bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3317 SMLoc DirectiveLoc) {
3318 StringRef Name;
3319 if (getParser().ParseIdentifier(Name))
3320 return TokError("expected identifier in '.purgem' directive");
3321
3322 if (getLexer().isNot(AsmToken::EndOfStatement))
3323 return TokError("unexpected token in '.purgem' directive");
3324
3325 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3326 if (I == getParser().MacroMap.end())
3327 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3328
3329 // Undefine the macro.
3330 delete I->getValue();
3331 getParser().MacroMap.erase(I);
3332 return false;
3333}
3334
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003335bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
Rafael Espindola3ff57092010-11-02 17:22:24 +00003336 getParser().CheckForValidSection();
3337
3338 const MCExpr *Value;
3339
3340 if (getParser().ParseExpression(Value))
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003341 return true;
3342
3343 if (getLexer().isNot(AsmToken::EndOfStatement))
3344 return TokError("unexpected token in directive");
3345
3346 if (DirName[1] == 's')
Rafael Espindola3ff57092010-11-02 17:22:24 +00003347 getStreamer().EmitSLEB128Value(Value);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003348 else
Rafael Espindola3ff57092010-11-02 17:22:24 +00003349 getStreamer().EmitULEB128Value(Value);
3350
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003351 return false;
3352}
3353
Rafael Espindola761cb062012-06-03 23:57:14 +00003354Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003355 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003356
Rafael Espindola761cb062012-06-03 23:57:14 +00003357 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003358 for (;;) {
3359 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003360 if (getLexer().is(AsmToken::Eof)) {
3361 Error(DirectiveLoc, "no matching '.endr' in definition");
3362 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003363 }
3364
Rafael Espindola761cb062012-06-03 23:57:14 +00003365 if (Lexer.is(AsmToken::Identifier) &&
3366 (getTok().getIdentifier() == ".rept")) {
3367 ++NestLevel;
3368 }
3369
3370 // Otherwise, check whether we have reached the .endr.
3371 if (Lexer.is(AsmToken::Identifier) &&
3372 getTok().getIdentifier() == ".endr") {
3373 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003374 EndToken = getTok();
3375 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003376 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3377 TokError("unexpected token in '.endr' directive");
3378 return 0;
3379 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003380 break;
3381 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003382 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003383 }
3384
Rafael Espindola761cb062012-06-03 23:57:14 +00003385 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003386 EatToEndOfStatement();
3387 }
3388
3389 const char *BodyStart = StartToken.getLoc().getPointer();
3390 const char *BodyEnd = EndToken.getLoc().getPointer();
3391 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3392
Rafael Espindola761cb062012-06-03 23:57:14 +00003393 // We Are Anonymous.
3394 StringRef Name;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003395 MacroParameters Parameters;
Rafael Espindola761cb062012-06-03 23:57:14 +00003396 return new Macro(Name, Body, Parameters);
3397}
3398
3399void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3400 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003401 OS << ".endr\n";
3402
3403 MemoryBuffer *Instantiation =
3404 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3405
Rafael Espindola761cb062012-06-03 23:57:14 +00003406 // Create the macro instantiation object and add to the current macro
3407 // instantiation stack.
3408 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3409 getTok().getLoc(),
3410 Instantiation);
3411 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003412
Rafael Espindola761cb062012-06-03 23:57:14 +00003413 // Jump to the macro instantiation and prime the lexer.
3414 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3415 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3416 Lex();
3417}
3418
3419bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3420 int64_t Count;
3421 if (ParseAbsoluteExpression(Count))
3422 return TokError("unexpected token in '.rept' directive");
3423
3424 if (Count < 0)
3425 return TokError("Count is negative");
3426
3427 if (Lexer.isNot(AsmToken::EndOfStatement))
3428 return TokError("unexpected token in '.rept' directive");
3429
3430 // Eat the end of statement.
3431 Lex();
3432
3433 // Lex the rept definition.
3434 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3435 if (!M)
3436 return true;
3437
3438 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3439 // to hold the macro body with substitutions.
3440 SmallString<256> Buf;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003441 MacroParameters Parameters;
3442 MacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003443 raw_svector_ostream OS(Buf);
3444 while (Count--) {
3445 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3446 return true;
3447 }
3448 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003449
3450 return false;
3451}
3452
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003453/// ParseDirectiveIrp
3454/// ::= .irp symbol,values
3455bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003456 MacroParameters Parameters;
3457 MacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003458
Preston Gurd6c9176a2012-09-19 20:29:04 +00003459 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003460 return TokError("expected identifier in '.irp' directive");
3461
3462 Parameters.push_back(Parameter);
3463
3464 if (Lexer.isNot(AsmToken::Comma))
3465 return TokError("expected comma in '.irp' directive");
3466
3467 Lex();
3468
Rafael Espindola8a403d32012-08-08 14:51:03 +00003469 MacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003470 if (ParseMacroArguments(0, A))
3471 return true;
3472
3473 // Eat the end of statement.
3474 Lex();
3475
3476 // Lex the irp definition.
3477 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3478 if (!M)
3479 return true;
3480
3481 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3482 // to hold the macro body with substitutions.
3483 SmallString<256> Buf;
3484 raw_svector_ostream OS(Buf);
3485
Rafael Espindola7996d042012-08-21 16:06:48 +00003486 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3487 MacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003488 Args.push_back(*i);
3489
3490 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3491 return true;
3492 }
3493
3494 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3495
3496 return false;
3497}
3498
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003499/// ParseDirectiveIrpc
3500/// ::= .irpc symbol,values
3501bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003502 MacroParameters Parameters;
3503 MacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003504
Preston Gurd6c9176a2012-09-19 20:29:04 +00003505 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003506 return TokError("expected identifier in '.irpc' directive");
3507
3508 Parameters.push_back(Parameter);
3509
3510 if (Lexer.isNot(AsmToken::Comma))
3511 return TokError("expected comma in '.irpc' directive");
3512
3513 Lex();
3514
Rafael Espindola8a403d32012-08-08 14:51:03 +00003515 MacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003516 if (ParseMacroArguments(0, A))
3517 return true;
3518
3519 if (A.size() != 1 || A.front().size() != 1)
3520 return TokError("unexpected token in '.irpc' directive");
3521
3522 // Eat the end of statement.
3523 Lex();
3524
3525 // Lex the irpc definition.
3526 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3527 if (!M)
3528 return true;
3529
3530 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3531 // to hold the macro body with substitutions.
3532 SmallString<256> Buf;
3533 raw_svector_ostream OS(Buf);
3534
3535 StringRef Values = A.front().front().getString();
3536 std::size_t I, End = Values.size();
3537 for (I = 0; I < End; ++I) {
3538 MacroArgument Arg;
3539 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3540
Rafael Espindola8a403d32012-08-08 14:51:03 +00003541 MacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003542 Args.push_back(Arg);
3543
3544 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3545 return true;
3546 }
3547
3548 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3549
3550 return false;
3551}
3552
Rafael Espindola761cb062012-06-03 23:57:14 +00003553bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3554 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003555 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003556
3557 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003558 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003559 assert(getLexer().is(AsmToken::EndOfStatement));
3560
Rafael Espindola761cb062012-06-03 23:57:14 +00003561 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003562 return false;
3563}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003564
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003565/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003566MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003567 MCContext &C, MCStreamer &Out,
3568 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003569 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003570}