blob: 15737994335c7f83c8b4aad12fd4880d8056746b [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"
Chad Rosierb1f8c132012-10-18 15:49:34 +000022#include "llvm/MC/MCInstPrinter.h"
23#include "llvm/MC/MCInstrInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000024#include "llvm/MC/MCParser/AsmCond.h"
25#include "llvm/MC/MCParser/AsmLexer.h"
26#include "llvm/MC/MCParser/MCAsmParser.h"
27#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Evan Chenge76a33b2011-07-20 05:58:47 +000028#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000029#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000030#include "llvm/MC/MCStreamer.h"
Daniel Dunbardce0f3c2009-06-29 23:43:14 +000031#include "llvm/MC/MCSymbol.h"
Evan Cheng94b95502011-07-26 00:24:13 +000032#include "llvm/MC/MCTargetAsmParser.h"
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000033#include "llvm/Support/CommandLine.h"
Benjamin Kramer518ff562012-01-28 15:28:41 +000034#include "llvm/Support/ErrorHandling.h"
Jim Grosbach254cf032011-06-29 16:05:14 +000035#include "llvm/Support/MathExtras.h"
Kevin Enderbyf187ac52010-06-28 21:45:58 +000036#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000037#include "llvm/Support/SourceMgr.h"
Chris Lattnerb0789ed2009-06-21 20:54:55 +000038#include "llvm/Support/raw_ostream.h"
Nick Lewycky476b2422010-12-19 20:43:38 +000039#include <cctype>
Chad Rosierb1f8c132012-10-18 15:49:34 +000040#include <set>
41#include <string>
Daniel Dunbaraef87e32010-07-18 18:31:38 +000042#include <vector>
Chris Lattner27aa7d22009-06-21 20:16:42 +000043using namespace llvm;
44
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000045static cl::opt<bool>
46FatalAssemblerWarnings("fatal-assembler-warnings",
47 cl::desc("Consider warnings as error"));
48
Nick Lewycky0d7d11d2012-10-19 07:00:09 +000049MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
50
Daniel Dunbar81ea00f2010-07-12 17:54:38 +000051namespace {
52
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000053/// \brief Helper class for tracking macro definitions.
Rafael Espindola28c1f6662012-06-03 22:41:23 +000054typedef std::vector<AsmToken> MacroArgument;
Rafael Espindola8a403d32012-08-08 14:51:03 +000055typedef std::vector<MacroArgument> MacroArguments;
Preston Gurd6c9176a2012-09-19 20:29:04 +000056typedef std::pair<StringRef, MacroArgument> MacroParameter;
Rafael Espindola8a403d32012-08-08 14:51:03 +000057typedef std::vector<MacroParameter> MacroParameters;
Rafael Espindola28c1f6662012-06-03 22:41:23 +000058
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000059struct Macro {
60 StringRef Name;
61 StringRef Body;
Rafael Espindola8a403d32012-08-08 14:51:03 +000062 MacroParameters Parameters;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000063
64public:
Rafael Espindola8a403d32012-08-08 14:51:03 +000065 Macro(StringRef N, StringRef B, const MacroParameters &P) :
Rafael Espindola65366442011-06-05 02:43:45 +000066 Name(N), Body(B), Parameters(P) {}
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000067};
68
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000069/// \brief Helper class for storing information about an active macro
70/// instantiation.
71struct MacroInstantiation {
72 /// The macro being instantiated.
73 const Macro *TheMacro;
74
75 /// The macro instantiation with substitutions.
76 MemoryBuffer *Instantiation;
77
78 /// The location of the instantiation.
79 SMLoc InstantiationLoc;
80
81 /// The location where parsing should resume upon instantiation completion.
82 SMLoc ExitLoc;
83
84public:
Daniel Dunbar7a570d02010-07-18 19:00:10 +000085 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000086 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000087};
88
Daniel Dunbaraef87e32010-07-18 18:31:38 +000089/// \brief The concrete assembly parser instance.
90class AsmParser : public MCAsmParser {
Daniel Dunbar3c802de2010-07-18 18:38:02 +000091 friend class GenericAsmParser;
92
Craig Topper85aadc02012-09-15 16:23:52 +000093 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
94 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
Daniel Dunbaraef87e32010-07-18 18:31:38 +000095private:
96 AsmLexer Lexer;
97 MCContext &Ctx;
98 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +000099 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000100 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +0000101 SourceMgr::DiagHandlerTy SavedDiagHandler;
102 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000103 MCAsmParserExtension *GenericParser;
104 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000105
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000106 /// This is the current buffer index we're lexing from as managed by the
107 /// SourceMgr object.
108 int CurBuffer;
109
110 AsmCond TheCondState;
111 std::vector<AsmCond> TheCondStack;
112
113 /// DirectiveMap - This is a table handlers for directives. Each handler is
114 /// invoked after the directive identifier is read and is responsible for
115 /// parsing and validating the rest of the directive. The handler is passed
116 /// in the directive name and the location of the directive keyword.
117 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000118
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000119 /// MacroMap - Map of currently defined macros.
120 StringMap<Macro*> MacroMap;
121
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000122 /// ActiveMacros - Stack of active macro instantiations.
123 std::vector<MacroInstantiation*> ActiveMacros;
124
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000125 /// Boolean tracking whether macro substitution is enabled.
126 unsigned MacrosEnabled : 1;
127
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000128 /// Flag tracking whether any errors have been encountered.
129 unsigned HadError : 1;
130
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000131 /// The values from the last parsed cpp hash file line comment if any.
132 StringRef CppHashFilename;
133 int64_t CppHashLineNumber;
134 SMLoc CppHashLoc;
135
Devang Patel0db58bf2012-01-31 18:14:05 +0000136 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
137 unsigned AssemblerDialect;
138
Preston Gurd7b6f2032012-09-19 20:36:12 +0000139 /// IsDarwin - is Darwin compatibility enabled?
140 bool IsDarwin;
141
Chad Rosier8f138d12012-10-15 17:19:13 +0000142 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000143 bool ParsingInlineAsm;
144
Chad Rosier8f138d12012-10-15 17:19:13 +0000145 /// ParsedOperands - The parsed operands from the last parsed statement.
146 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
147
Chad Rosierb1f8c132012-10-18 15:49:34 +0000148 /// Opcode - The opcode from the last parsed instruction. This is MS-style
149 /// inline asm specific.
Chad Rosier8f138d12012-10-15 17:19:13 +0000150 unsigned Opcode;
151
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000152public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000153 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000154 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000155 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000156
157 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
158
Craig Topper345d16d2012-08-29 05:48:09 +0000159 virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
160 StringRef Directive,
161 DirectiveHandler Handler) {
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000162 DirectiveMap[Directive] = std::make_pair(Object, Handler);
163 }
164
165public:
166 /// @name MCAsmParser Interface
167 /// {
168
169 virtual SourceMgr &getSourceManager() { return SrcMgr; }
170 virtual MCAsmLexer &getLexer() { return Lexer; }
171 virtual MCContext &getContext() { return Ctx; }
172 virtual MCStreamer &getStreamer() { return Out; }
Devang Patel0db58bf2012-01-31 18:14:05 +0000173 virtual unsigned getAssemblerDialect() {
174 if (AssemblerDialect == ~0U)
175 return MAI.getAssemblerDialect();
176 else
177 return AssemblerDialect;
178 }
179 virtual void setAssemblerDialect(unsigned i) {
180 AssemblerDialect = i;
181 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000182
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000183 virtual bool Warning(SMLoc L, const Twine &Msg,
184 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
185 virtual bool Error(SMLoc L, const Twine &Msg,
186 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000187
Craig Topper345d16d2012-08-29 05:48:09 +0000188 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000189
Chad Rosier84125ca2012-10-13 00:26:04 +0000190 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosierc5ac87d2012-10-16 20:16:20 +0000191 bool isParsingInlineAsm() { return ParsingInlineAsm; }
Chad Rosierb1f8c132012-10-18 15:49:34 +0000192
193 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
194 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosierc8dd27e2012-10-18 19:39:30 +0000195 SmallVectorImpl<void *> &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000196 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000197 SmallVectorImpl<std::string> &Clobbers,
198 const MCInstrInfo *MII,
199 const MCInstPrinter *IP,
200 MCAsmParserSemaCallback &SI);
Chad Rosier84125ca2012-10-13 00:26:04 +0000201
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000202 bool ParseExpression(const MCExpr *&Res);
203 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
204 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
205 virtual bool ParseAbsoluteExpression(int64_t &Res);
206
207 /// }
208
209private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000210 void CheckForValidSection();
211
Chad Rosierb1f8c132012-10-18 15:49:34 +0000212 bool ParseStatement();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000213 void EatToEndOfLine();
214 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000215
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000216 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
Rafael Espindola761cb062012-06-03 23:57:14 +0000217 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +0000218 const MacroParameters &Parameters,
219 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000220 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000221 void HandleMacroExit();
222
223 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000224 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000225 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
226 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000227 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000228 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000229
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000230 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
231 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000232 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
233 /// This returns true on failure.
234 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000235
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000236 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000237 /// current token is not set; clients should ensure Lex() is called
238 /// subsequently.
239 void JumpToLoc(SMLoc Loc);
240
Craig Topper345d16d2012-08-29 05:48:09 +0000241 virtual void EatToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000242
Preston Gurd7b6f2032012-09-19 20:36:12 +0000243 bool ParseMacroArgument(MacroArgument &MA,
244 AsmToken::TokenKind &ArgumentDelimiter);
Rafael Espindola8a403d32012-08-08 14:51:03 +0000245 bool ParseMacroArguments(const Macro *M, MacroArguments &A);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000246
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000247 /// \brief Parse up to the end of statement and a return the contents from the
248 /// current token until the end of the statement; the current token on exit
249 /// will be either the EndOfStatement or EOF.
Craig Topper345d16d2012-08-29 05:48:09 +0000250 virtual StringRef ParseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000251
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000252 /// \brief Parse until the end of a statement or a comma is encountered,
253 /// return the contents from the current token up to the end or comma.
254 StringRef ParseStringToComma();
255
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000256 bool ParseAssignment(StringRef Name, bool allow_redef,
257 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000258
259 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
260 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
261 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000262 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000263
264 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000265 /// and set \p Res to the identifier contents.
Craig Topper345d16d2012-08-29 05:48:09 +0000266 virtual bool ParseIdentifier(StringRef &Res);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000267
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000268 // Directive Parsing.
Rafael Espindola787c3372010-10-28 20:02:27 +0000269
270 // ".ascii", ".asciiz", ".string"
271 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000272 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000273 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000274 bool ParseDirectiveFill(); // ".fill"
275 bool ParseDirectiveSpace(); // ".space"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000276 bool ParseDirectiveZero(); // ".zero"
Nico Weber4c4c7322011-01-28 03:04:41 +0000277 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000278 bool ParseDirectiveOrg(); // ".org"
279 // ".align{,32}", ".p2align{,w,l}"
280 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
281
282 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
283 /// accepts a single symbol (which should be a label or an external).
284 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000285
286 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
287
288 bool ParseDirectiveAbort(); // ".abort"
289 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000290 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000291
292 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000293 // ".ifb" or ".ifnb", depending on ExpectBlank.
294 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000295 // ".ifc" or ".ifnc", depending on ExpectEqual.
296 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000297 // ".ifdef" or ".ifndef", depending on expect_defined
298 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000299 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
300 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
301 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
302
303 /// ParseEscapedString - Parse the current token as a string which may include
304 /// escaped characters and return the string contents.
305 bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000306
307 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
308 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000309
Rafael Espindola761cb062012-06-03 23:57:14 +0000310 // Macro-like directives
311 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
312 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
313 raw_svector_ostream &OS);
314 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000315 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000316 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000317 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000318
319 // MS-style inline assembly parsing.
320 bool isInstruction() { return Opcode != (unsigned)~0x0; }
321 unsigned getOpcode() { return Opcode; }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000322};
323
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000324/// \brief Generic implementations of directive handling, etc. which is shared
325/// (or the default, at least) for all assembler parser.
326class GenericAsmParser : public MCAsmParserExtension {
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000327 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
328 void AddDirectiveHandler(StringRef Directive) {
329 getParser().AddDirectiveHandler(this, Directive,
330 HandleDirective<GenericAsmParser, Handler>);
331 }
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000332public:
333 GenericAsmParser() {}
334
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000335 AsmParser &getParser() {
336 return (AsmParser&) this->MCAsmParserExtension::getParser();
337 }
338
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000339 virtual void Initialize(MCAsmParser &Parser) {
340 // Call the base implementation.
341 this->MCAsmParserExtension::Initialize(Parser);
342
343 // Debugging directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000344 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
345 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
346 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
Daniel Dunbar138abae2010-10-16 04:56:42 +0000347 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000348
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000349 // CFI directives.
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000350 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
351 ".cfi_sections");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000352 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
353 ".cfi_startproc");
354 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
355 ".cfi_endproc");
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000356 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
357 ".cfi_def_cfa");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000358 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
359 ".cfi_def_cfa_offset");
Rafael Espindola53abbe52011-04-11 20:29:16 +0000360 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
361 ".cfi_adjust_cfa_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000362 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
363 ".cfi_def_cfa_register");
364 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
365 ".cfi_offset");
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000366 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
367 ".cfi_rel_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000368 AddDirectiveHandler<
369 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
370 AddDirectiveHandler<
371 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
Rafael Espindolafe024d02010-12-28 18:36:23 +0000372 AddDirectiveHandler<
373 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
374 AddDirectiveHandler<
375 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
Rafael Espindolac5754392011-04-12 15:31:05 +0000376 AddDirectiveHandler<
377 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000378 AddDirectiveHandler<
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000379 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
380 AddDirectiveHandler<
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000381 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
Rafael Espindola16d7d432012-01-23 21:51:52 +0000382 AddDirectiveHandler<
383 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000384
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000385 // Macro directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000386 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
387 ".macros_on");
388 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
389 ".macros_off");
390 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
391 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
392 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000393 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000394
395 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
396 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000397 }
398
Roman Divacky54b0f4f2011-01-27 17:16:37 +0000399 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
400
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000401 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
402 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
403 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar138abae2010-10-16 04:56:42 +0000404 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000405 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000406 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
407 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000408 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000409 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola53abbe52011-04-11 20:29:16 +0000410 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000411 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
412 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000413 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000414 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
Rafael Espindolafe024d02010-12-28 18:36:23 +0000415 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
416 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac5754392011-04-12 15:31:05 +0000417 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000418 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000419 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
Rafael Espindola16d7d432012-01-23 21:51:52 +0000420 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000421
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000422 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000423 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
424 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000425 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000426
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000427 bool ParseDirectiveLEB128(StringRef, SMLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000428};
429
430}
431
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000432namespace llvm {
433
434extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000435extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000436extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000437
438}
439
Chris Lattneraaec2052010-01-19 19:46:13 +0000440enum { DEFAULT_ADDRSPACE = 0 };
441
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000442AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000443 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000444 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Rafael Espindola5d7dcd32011-04-12 18:53:30 +0000445 GenericParser(new GenericAsmParser), PlatformParser(0),
Preston Gurd7b6f2032012-09-19 20:36:12 +0000446 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
Chad Rosier8f138d12012-10-15 17:19:13 +0000447 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false),
Chad Rosier127f5ed2012-10-15 19:08:18 +0000448 Opcode(~0x0) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000449 // Save the old handler.
450 SavedDiagHandler = SrcMgr.getDiagHandler();
451 SavedDiagContext = SrcMgr.getDiagContext();
452 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000453 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000454 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000455
456 // Initialize the generic parser.
457 GenericParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000458
459 // Initialize the platform / file format parser.
460 //
461 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
462 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000463 if (_MAI.hasMicrosoftFastStdCallMangling()) {
464 PlatformParser = createCOFFAsmParser();
465 PlatformParser->Initialize(*this);
466 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000467 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000468 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000469 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000470 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000471 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000472 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000473 }
Chris Lattnerebb89b42009-09-27 21:16:52 +0000474}
475
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000476AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000477 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
478
479 // Destroy any macros.
480 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
481 ie = MacroMap.end(); it != ie; ++it)
482 delete it->getValue();
483
Daniel Dunbare4749702010-07-12 18:12:02 +0000484 delete PlatformParser;
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000485 delete GenericParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000486}
487
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000488void AsmParser::PrintMacroInstantiations() {
489 // Print the active macro instantiation stack.
490 for (std::vector<MacroInstantiation*>::const_reverse_iterator
491 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000492 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
493 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000494}
495
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000496bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000497 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000498 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000499 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000500 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000501 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000502}
503
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000504bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000505 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000506 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000507 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000508 return true;
509}
510
Sean Callananfd0b0282010-01-21 00:19:58 +0000511bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000512 std::string IncludedFile;
513 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000514 if (NewBuf == -1)
515 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000516
Sean Callananfd0b0282010-01-21 00:19:58 +0000517 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000518
Sean Callananfd0b0282010-01-21 00:19:58 +0000519 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000520
Sean Callananfd0b0282010-01-21 00:19:58 +0000521 return false;
522}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000523
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000524/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000525/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000526/// returns true on failure.
527bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
528 std::string IncludedFile;
529 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
530 if (NewBuf == -1)
531 return true;
532
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000533 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000534 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
535 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000536 return false;
537}
538
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000539void AsmParser::JumpToLoc(SMLoc Loc) {
540 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
541 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
542}
543
Sean Callananfd0b0282010-01-21 00:19:58 +0000544const AsmToken &AsmParser::Lex() {
545 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000546
Sean Callananfd0b0282010-01-21 00:19:58 +0000547 if (tok->is(AsmToken::Eof)) {
548 // If this is the end of an included file, pop the parent file off the
549 // include stack.
550 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
551 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000552 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000553 tok = &Lexer.Lex();
554 }
555 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000556
Sean Callananfd0b0282010-01-21 00:19:58 +0000557 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000558 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000559
Sean Callananfd0b0282010-01-21 00:19:58 +0000560 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000561}
562
Chris Lattner79180e22010-04-05 23:15:42 +0000563bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000564 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000565 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000566 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000567
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000568 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000569 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000570
571 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000572 AsmCond StartingCondState = TheCondState;
573
Kevin Enderby613b7572011-11-01 22:27:22 +0000574 // If we are generating dwarf for assembly source files save the initial text
575 // section and generate a .file directive.
576 if (getContext().getGenDwarfForAssembly()) {
577 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000578 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
579 getStreamer().EmitLabel(SectionStartSym);
580 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000581 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
582 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
583 }
584
Chris Lattnerb717fb02009-07-02 21:53:43 +0000585 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000586 while (Lexer.isNot(AsmToken::Eof)) {
Chris Lattnerb717fb02009-07-02 21:53:43 +0000587 if (!ParseStatement()) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000588
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000589 // We had an error, validate that one was emitted and recover by skipping to
590 // the next line.
591 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000592 EatToEndOfStatement();
593 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000594
595 if (TheCondState.TheCond != StartingCondState.TheCond ||
596 TheCondState.Ignore != StartingCondState.Ignore)
597 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000598
599 // Check to see there are no empty DwarfFile slots.
600 const std::vector<MCDwarfFile *> &MCDwarfFiles =
601 getContext().getMCDwarfFiles();
602 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000603 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000604 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000605 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000606
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000607 // Check to see that all assembler local symbols were actually defined.
608 // Targets that don't do subsections via symbols may not want this, though,
609 // so conservatively exclude them. Only do this if we're finalizing, though,
610 // as otherwise we won't necessarilly have seen everything yet.
611 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
612 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
613 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
614 e = Symbols.end();
615 i != e; ++i) {
616 MCSymbol *Sym = i->getValue();
617 // Variable symbols may not be marked as defined, so check those
618 // explicitly. If we know it's a variable, we have a definition for
619 // the purposes of this check.
620 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
621 // FIXME: We would really like to refer back to where the symbol was
622 // first referenced for a source location. We need to add something
623 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000624 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
625 "assembler local symbol '" + Sym->getName() +
626 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000627 }
628 }
629
630
Chris Lattner79180e22010-04-05 23:15:42 +0000631 // Finalize the output stream if there are no errors and if the client wants
632 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000633 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000634 Out.Finish();
635
Chris Lattnerb717fb02009-07-02 21:53:43 +0000636 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000637}
638
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000639void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000640 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000641 TokError("expected section directive before assembly directive");
642 Out.SwitchSection(Ctx.getMachOSection(
643 "__TEXT", "__text",
644 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
645 0, SectionKind::getText()));
646 }
647}
648
Chris Lattner2cf5f142009-06-22 01:29:09 +0000649/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
650void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000651 while (Lexer.isNot(AsmToken::EndOfStatement) &&
652 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000653 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000654
Chris Lattner2cf5f142009-06-22 01:29:09 +0000655 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000656 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000657 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000658}
659
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000660StringRef AsmParser::ParseStringToEndOfStatement() {
661 const char *Start = getTok().getLoc().getPointer();
662
663 while (Lexer.isNot(AsmToken::EndOfStatement) &&
664 Lexer.isNot(AsmToken::Eof))
665 Lex();
666
667 const char *End = getTok().getLoc().getPointer();
668 return StringRef(Start, End - Start);
669}
Chris Lattnerc4193832009-06-22 05:51:26 +0000670
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000671StringRef AsmParser::ParseStringToComma() {
672 const char *Start = getTok().getLoc().getPointer();
673
674 while (Lexer.isNot(AsmToken::EndOfStatement) &&
675 Lexer.isNot(AsmToken::Comma) &&
676 Lexer.isNot(AsmToken::Eof))
677 Lex();
678
679 const char *End = getTok().getLoc().getPointer();
680 return StringRef(Start, End - Start);
681}
682
Chris Lattner74ec1a32009-06-22 06:32:03 +0000683/// ParseParenExpr - Parse a paren expression and return it.
684/// NOTE: This assumes the leading '(' has already been consumed.
685///
686/// parenexpr ::= expr)
687///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000688bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000689 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000690 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000691 return TokError("expected ')' in parentheses expression");
Chris Lattnerb4307b32010-01-15 19:28:38 +0000692 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000693 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000694 return false;
695}
Chris Lattnerc4193832009-06-22 05:51:26 +0000696
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000697/// ParseBracketExpr - Parse a bracket expression and return it.
698/// NOTE: This assumes the leading '[' has already been consumed.
699///
700/// bracketexpr ::= expr]
701///
702bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
703 if (ParseExpression(Res)) return true;
704 if (Lexer.isNot(AsmToken::RBrac))
705 return TokError("expected ']' in brackets expression");
706 EndLoc = Lexer.getLoc();
707 Lex();
708 return false;
709}
710
Chris Lattner74ec1a32009-06-22 06:32:03 +0000711/// ParsePrimaryExpr - Parse a primary expression and return it.
712/// primaryexpr ::= (parenexpr
713/// primaryexpr ::= symbol
714/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000715/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000716/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000717bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000718 switch (Lexer.getKind()) {
719 default:
720 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000721 // If we have an error assume that we've already handled it.
722 case AsmToken::Error:
723 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000724 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000725 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000726 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000727 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000728 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000729 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000730 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000731 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000732 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000733 EndLoc = Lexer.getLoc();
734
735 StringRef Identifier;
736 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000737 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000738
Daniel Dunbarfffff912009-10-16 01:34:54 +0000739 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000740 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000741 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000742
743 // Lookup the symbol variant if used.
744 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000745 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000746 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000747 if (Variant == MCSymbolRefExpr::VK_Invalid) {
748 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000749 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000750 }
751 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000752
Daniel Dunbarfffff912009-10-16 01:34:54 +0000753 // If this is an absolute variable reference, substitute it now to preserve
754 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000755 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000756 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000757 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000758
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000759 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000760 return false;
761 }
762
763 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000764 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000765 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000766 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000767 case AsmToken::Integer: {
768 SMLoc Loc = getTok().getLoc();
769 int64_t IntVal = getTok().getIntVal();
770 Res = MCConstantExpr::Create(IntVal, getContext());
Chris Lattnerb4307b32010-01-15 19:28:38 +0000771 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000772 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000773 // Look for 'b' or 'f' following an Integer as a directional label
774 if (Lexer.getKind() == AsmToken::Identifier) {
775 StringRef IDVal = getTok().getString();
776 if (IDVal == "f" || IDVal == "b"){
777 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
778 IDVal == "f" ? 1 : 0);
779 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
780 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000781 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000782 return Error(Loc, "invalid reference to undefined symbol");
783 EndLoc = Lexer.getLoc();
784 Lex(); // Eat identifier.
785 }
786 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000787 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000788 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000789 case AsmToken::Real: {
790 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000791 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000792 Res = MCConstantExpr::Create(IntVal, getContext());
793 Lex(); // Eat token.
794 return false;
795 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000796 case AsmToken::Dot: {
797 // This is a '.' reference, which references the current PC. Emit a
798 // temporary label to the streamer and refer to it.
799 MCSymbol *Sym = Ctx.CreateTempSymbol();
800 Out.EmitLabel(Sym);
801 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
802 EndLoc = Lexer.getLoc();
803 Lex(); // Eat identifier.
804 return false;
805 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000806 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000807 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000808 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000809 case AsmToken::LBrac:
810 if (!PlatformParser->HasBracketExpressions())
811 return TokError("brackets expression not supported on this target");
812 Lex(); // Eat the '['.
813 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000814 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000815 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000816 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000817 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000818 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000819 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000820 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000821 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000822 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000823 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000824 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000825 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000826 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000827 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000828 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000829 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000830 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000831 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000832 }
833}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000834
Chris Lattnerb4307b32010-01-15 19:28:38 +0000835bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000836 SMLoc EndLoc;
837 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000838}
839
Daniel Dunbarcceba832010-09-17 02:47:07 +0000840const MCExpr *
841AsmParser::ApplyModifierToExpr(const MCExpr *E,
842 MCSymbolRefExpr::VariantKind Variant) {
843 // Recurse over the given expression, rebuilding it to apply the given variant
844 // if there is exactly one symbol.
845 switch (E->getKind()) {
846 case MCExpr::Target:
847 case MCExpr::Constant:
848 return 0;
849
850 case MCExpr::SymbolRef: {
851 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
852
853 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
854 TokError("invalid variant on expression '" +
855 getTok().getIdentifier() + "' (already modified)");
856 return E;
857 }
858
859 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
860 }
861
862 case MCExpr::Unary: {
863 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
864 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
865 if (!Sub)
866 return 0;
867 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
868 }
869
870 case MCExpr::Binary: {
871 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
872 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
873 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
874
875 if (!LHS && !RHS)
876 return 0;
877
878 if (!LHS) LHS = BE->getLHS();
879 if (!RHS) RHS = BE->getRHS();
880
881 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
882 }
883 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000884
Craig Topper85814382012-02-07 05:05:23 +0000885 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000886}
887
Chris Lattner74ec1a32009-06-22 06:32:03 +0000888/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000889///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000890/// expr ::= expr &&,|| expr -> lowest.
891/// expr ::= expr |,^,&,! expr
892/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
893/// expr ::= expr <<,>> expr
894/// expr ::= expr +,- expr
895/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000896/// expr ::= primaryexpr
897///
Chris Lattner54482b42010-01-15 19:39:23 +0000898bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000899 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000900 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000901 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
902 return true;
903
Daniel Dunbarcceba832010-09-17 02:47:07 +0000904 // As a special case, we support 'a op b @ modifier' by rewriting the
905 // expression to include the modifier. This is inefficient, but in general we
906 // expect users to use 'a@modifier op b'.
907 if (Lexer.getKind() == AsmToken::At) {
908 Lex();
909
910 if (Lexer.isNot(AsmToken::Identifier))
911 return TokError("unexpected symbol modifier following '@'");
912
913 MCSymbolRefExpr::VariantKind Variant =
914 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
915 if (Variant == MCSymbolRefExpr::VK_Invalid)
916 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
917
918 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
919 if (!ModifiedRes) {
920 return TokError("invalid modifier '" + getTok().getIdentifier() +
921 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000922 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000923
Daniel Dunbarcceba832010-09-17 02:47:07 +0000924 Res = ModifiedRes;
925 Lex();
926 }
927
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000928 // Try to constant fold it up front, if possible.
929 int64_t Value;
930 if (Res->EvaluateAsAbsolute(Value))
931 Res = MCConstantExpr::Create(Value, getContext());
932
933 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000934}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000935
Chris Lattnerb4307b32010-01-15 19:28:38 +0000936bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000937 Res = 0;
938 return ParseParenExpr(Res, EndLoc) ||
939 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000940}
941
Daniel Dunbar475839e2009-06-29 20:37:27 +0000942bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000943 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000944
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000945 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000946 if (ParseExpression(Expr))
947 return true;
948
Daniel Dunbare00b0112009-10-16 01:57:52 +0000949 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000950 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000951
952 return false;
953}
954
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000955static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000956 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000957 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000958 default:
959 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000960
Jim Grosbachfbe16812011-08-20 16:24:13 +0000961 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000962 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000963 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000964 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000965 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000966 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000967 return 1;
968
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000969
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000970 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +0000971 //
972 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +0000973 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000974 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000975 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000976 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000977 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000978 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000979 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000980 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000981 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000982
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000983 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000984 case AsmToken::EqualEqual:
985 Kind = MCBinaryExpr::EQ;
986 return 3;
987 case AsmToken::ExclaimEqual:
988 case AsmToken::LessGreater:
989 Kind = MCBinaryExpr::NE;
990 return 3;
991 case AsmToken::Less:
992 Kind = MCBinaryExpr::LT;
993 return 3;
994 case AsmToken::LessEqual:
995 Kind = MCBinaryExpr::LTE;
996 return 3;
997 case AsmToken::Greater:
998 Kind = MCBinaryExpr::GT;
999 return 3;
1000 case AsmToken::GreaterEqual:
1001 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001002 return 3;
1003
Jim Grosbachfbe16812011-08-20 16:24:13 +00001004 // Intermediate Precedence: <<, >>
1005 case AsmToken::LessLess:
1006 Kind = MCBinaryExpr::Shl;
1007 return 4;
1008 case AsmToken::GreaterGreater:
1009 Kind = MCBinaryExpr::Shr;
1010 return 4;
1011
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001012 // High Intermediate Precedence: +, -
1013 case AsmToken::Plus:
1014 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001015 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001016 case AsmToken::Minus:
1017 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001018 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001019
Jim Grosbachfbe16812011-08-20 16:24:13 +00001020 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001021 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001022 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001023 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001024 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001025 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001026 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001027 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001028 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001029 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001030 }
1031}
1032
1033
1034/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1035/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001036bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1037 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001038 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001039 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001040 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001041
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001042 // If the next token is lower precedence than we are allowed to eat, return
1043 // successfully with what we ate already.
1044 if (TokPrec < Precedence)
1045 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001046
Sean Callanan79ed1a82010-01-19 20:22:31 +00001047 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001048
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001049 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001050 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001051 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001052
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001053 // If BinOp binds less tightly with RHS than the operator after RHS, let
1054 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001055 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001056 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001057 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001058 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001059 }
1060
Daniel Dunbar475839e2009-06-29 20:37:27 +00001061 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001062 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001063 }
1064}
1065
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001066/// ParseStatement:
1067/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001068/// ::= Label* Directive ...Operands... EndOfStatement
1069/// ::= Label* Identifier OperandList* EndOfStatement
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001070bool AsmParser::ParseStatement() {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001071 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001072 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001073 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001074 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001075 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001076
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001077 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001078 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001079 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001080 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001081 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001082 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001083 if (Lexer.is(AsmToken::Hash))
1084 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001085
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001086 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001087 if (Lexer.is(AsmToken::Integer)) {
1088 LocalLabelVal = getTok().getIntVal();
1089 if (LocalLabelVal < 0) {
1090 if (!TheCondState.Ignore)
1091 return TokError("unexpected token at start of statement");
1092 IDVal = "";
1093 }
1094 else {
1095 IDVal = getTok().getString();
1096 Lex(); // Consume the integer token to be used as an identifier token.
1097 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001098 if (!TheCondState.Ignore)
1099 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001100 }
1101 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001102
1103 } else if (Lexer.is(AsmToken::Dot)) {
1104 // Treat '.' as a valid identifier in this context.
1105 Lex();
1106 IDVal = ".";
1107
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001108 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001109 if (!TheCondState.Ignore)
1110 return TokError("unexpected token at start of statement");
1111 IDVal = "";
1112 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001113
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001114
Chris Lattner7834fac2010-04-17 18:14:27 +00001115 // Handle conditional assembly here before checking for skipping. We
1116 // have to do this so that .endif isn't skipped in a ".if 0" block for
1117 // example.
1118 if (IDVal == ".if")
1119 return ParseDirectiveIf(IDLoc);
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00001120 if (IDVal == ".ifb")
1121 return ParseDirectiveIfb(IDLoc, true);
1122 if (IDVal == ".ifnb")
1123 return ParseDirectiveIfb(IDLoc, false);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00001124 if (IDVal == ".ifc")
1125 return ParseDirectiveIfc(IDLoc, true);
1126 if (IDVal == ".ifnc")
1127 return ParseDirectiveIfc(IDLoc, false);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00001128 if (IDVal == ".ifdef")
1129 return ParseDirectiveIfdef(IDLoc, true);
1130 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1131 return ParseDirectiveIfdef(IDLoc, false);
Chris Lattner7834fac2010-04-17 18:14:27 +00001132 if (IDVal == ".elseif")
1133 return ParseDirectiveElseIf(IDLoc);
1134 if (IDVal == ".else")
1135 return ParseDirectiveElse(IDLoc);
1136 if (IDVal == ".endif")
1137 return ParseDirectiveEndIf(IDLoc);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001138
Chris Lattner7834fac2010-04-17 18:14:27 +00001139 // If we are in a ".if 0" block, ignore this statement.
1140 if (TheCondState.Ignore) {
1141 EatToEndOfStatement();
1142 return false;
1143 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001144
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001145 // FIXME: Recurse on local labels?
1146
1147 // See what kind of statement we have.
1148 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001149 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001150 CheckForValidSection();
1151
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001152 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001153 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001154
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001155 // Diagnose attempt to use '.' as a label.
1156 if (IDVal == ".")
1157 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1158
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001159 // Diagnose attempt to use a variable as a label.
1160 //
1161 // FIXME: Diagnostics. Note the location of the definition as a label.
1162 // FIXME: This doesn't diagnose assignment to a symbol which has been
1163 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001164 MCSymbol *Sym;
1165 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001166 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001167 else
1168 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001169 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001170 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001171
Daniel Dunbar959fd882009-08-26 22:13:22 +00001172 // Emit the label.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001173 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001174
Kevin Enderby94c2e852011-12-09 18:09:40 +00001175 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001176 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001177 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001178 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1179 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001180
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001181 // Consume any end of statement token, if present, to avoid spurious
1182 // AddBlankLine calls().
1183 if (Lexer.is(AsmToken::EndOfStatement)) {
1184 Lex();
1185 if (Lexer.is(AsmToken::Eof))
1186 return false;
1187 }
1188
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001189 return ParseStatement();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001190 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001191
Daniel Dunbar3f872332009-07-28 16:08:33 +00001192 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001193 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001194 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001195
Nico Weber4c4c7322011-01-28 03:04:41 +00001196 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001197
1198 default: // Normal instruction or directive.
1199 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001200 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001201
1202 // If macros are enabled, check to see if this is a macro instantiation.
1203 if (MacrosEnabled)
1204 if (const Macro *M = MacroMap.lookup(IDVal))
1205 return HandleMacroEntry(IDVal, IDLoc, M);
1206
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001207 // Otherwise, we have a normal instruction or directive.
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001208 if (IDVal[0] == '.' && IDVal != ".") {
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001209
1210 // Target hook for parsing target specific directives.
1211 if (!getTargetParser().ParseDirective(ID))
1212 return false;
1213
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001214 // Assembler features
Roman Divacky50e7a782010-10-28 16:22:58 +00001215 if (IDVal == ".set" || IDVal == ".equ")
Nico Weber4c4c7322011-01-28 03:04:41 +00001216 return ParseDirectiveSet(IDVal, true);
1217 if (IDVal == ".equiv")
1218 return ParseDirectiveSet(IDVal, false);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001219
Daniel Dunbara0d14262009-06-24 23:30:00 +00001220 // Data directives
1221
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001222 if (IDVal == ".ascii")
Rafael Espindola787c3372010-10-28 20:02:27 +00001223 return ParseDirectiveAscii(IDVal, false);
1224 if (IDVal == ".asciz" || IDVal == ".string")
1225 return ParseDirectiveAscii(IDVal, true);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001226
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001227 if (IDVal == ".byte")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001228 return ParseDirectiveValue(1);
Kevin Enderby9c656452009-09-10 20:51:44 +00001229 if (IDVal == ".short")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001230 return ParseDirectiveValue(2);
Rafael Espindolacc3acee2010-11-01 15:29:07 +00001231 if (IDVal == ".value")
1232 return ParseDirectiveValue(2);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001233 if (IDVal == ".2byte")
1234 return ParseDirectiveValue(2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001235 if (IDVal == ".long")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001236 return ParseDirectiveValue(4);
Rafael Espindola435279b2010-11-17 16:24:40 +00001237 if (IDVal == ".int")
1238 return ParseDirectiveValue(4);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001239 if (IDVal == ".4byte")
1240 return ParseDirectiveValue(4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001241 if (IDVal == ".quad")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001242 return ParseDirectiveValue(8);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001243 if (IDVal == ".8byte")
1244 return ParseDirectiveValue(8);
Roman Divacky14e66552011-01-28 14:20:32 +00001245 if (IDVal == ".single" || IDVal == ".float")
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001246 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1247 if (IDVal == ".double")
1248 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001249
Eli Friedman5d68ec22010-07-19 04:17:25 +00001250 if (IDVal == ".align") {
1251 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1252 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1253 }
1254 if (IDVal == ".align32") {
1255 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1256 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1257 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001258 if (IDVal == ".balign")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001259 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001260 if (IDVal == ".balignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001261 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001262 if (IDVal == ".balignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001263 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001264 if (IDVal == ".p2align")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001265 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001266 if (IDVal == ".p2alignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001267 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001268 if (IDVal == ".p2alignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001269 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1270
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001271 if (IDVal == ".org")
Daniel Dunbarc238b582009-06-25 22:44:51 +00001272 return ParseDirectiveOrg();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001273
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001274 if (IDVal == ".fill")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001275 return ParseDirectiveFill();
Rafael Espindolace8463f2011-04-07 20:26:23 +00001276 if (IDVal == ".space" || IDVal == ".skip")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001277 return ParseDirectiveSpace();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001278 if (IDVal == ".zero")
1279 return ParseDirectiveZero();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001280
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001281 // Symbol attribute directives
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001282
Benjamin Kramere14a3c52012-05-12 11:18:59 +00001283 if (IDVal == ".extern") {
1284 EatToEndOfStatement(); // .extern is the default, ignore it.
1285 return false;
1286 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001287 if (IDVal == ".globl" || IDVal == ".global")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001288 return ParseDirectiveSymbolAttribute(MCSA_Global);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001289 if (IDVal == ".indirect_symbol")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001290 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001291 if (IDVal == ".lazy_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001292 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001293 if (IDVal == ".no_dead_strip")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001294 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Kevin Enderbye8e98d72010-11-19 18:39:33 +00001295 if (IDVal == ".symbol_resolver")
1296 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001297 if (IDVal == ".private_extern")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001298 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001299 if (IDVal == ".reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001300 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001301 if (IDVal == ".weak_definition")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001302 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001303 if (IDVal == ".weak_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001304 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Kevin Enderbyf59cac52010-07-08 17:22:42 +00001305 if (IDVal == ".weak_def_can_be_hidden")
1306 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001307
Hans Wennborg5cc64912011-06-18 13:51:54 +00001308 if (IDVal == ".comm" || IDVal == ".common")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001309 return ParseDirectiveComm(/*IsLocal=*/false);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001310 if (IDVal == ".lcomm")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001311 return ParseDirectiveComm(/*IsLocal=*/true);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001312
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001313 if (IDVal == ".abort")
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001314 return ParseDirectiveAbort();
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001315 if (IDVal == ".include")
Kevin Enderby1f049b22009-07-14 23:21:55 +00001316 return ParseDirectiveInclude();
Kevin Enderbyc55acca2011-12-14 21:47:48 +00001317 if (IDVal == ".incbin")
1318 return ParseDirectiveIncbin();
Kevin Enderbya5c78322009-07-13 21:03:15 +00001319
Benjamin Kramer5cdf0ad2012-05-12 11:19:04 +00001320 if (IDVal == ".code16" || IDVal == ".code16gcc")
Roman Divackyf6fbd842011-01-31 20:56:49 +00001321 return TokError(Twine(IDVal) + " not supported yet");
Roman Divackycb727802011-01-28 19:29:48 +00001322
Rafael Espindola761cb062012-06-03 23:57:14 +00001323 // Macro-like directives
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001324 if (IDVal == ".rept")
1325 return ParseDirectiveRept(IDLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001326 if (IDVal == ".irp")
1327 return ParseDirectiveIrp(IDLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00001328 if (IDVal == ".irpc")
1329 return ParseDirectiveIrpc(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001330 if (IDVal == ".endr")
Rafael Espindola761cb062012-06-03 23:57:14 +00001331 return ParseDirectiveEndr(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001332
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001333 // Look up the handler in the handler table.
1334 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1335 DirectiveMap.lookup(IDVal);
1336 if (Handler.first)
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +00001337 return (*Handler.second)(Handler.first, IDVal, IDLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001338
Kevin Enderby9c656452009-09-10 20:51:44 +00001339
Jim Grosbach686c0182012-05-01 18:38:27 +00001340 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001341 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001342
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001343 CheckForValidSection();
1344
Chris Lattnera7f13542010-05-19 23:34:33 +00001345 // Canonicalize the opcode to lower case.
Chad Rosier8f138d12012-10-15 17:19:13 +00001346 SmallString<128> OpcodeStr;
Chris Lattnera7f13542010-05-19 23:34:33 +00001347 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
Chad Rosier8f138d12012-10-15 17:19:13 +00001348 OpcodeStr.push_back(tolower(IDVal[i]));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001349
Chad Rosier8f138d12012-10-15 17:19:13 +00001350 bool HadError = getTargetParser().ParseInstruction(OpcodeStr.str(), IDLoc,
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001351 ParsedOperands);
Chris Lattner2cf5f142009-06-22 01:29:09 +00001352
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001353 // Dump the parsed representation, if requested.
1354 if (getShowParsedOperands()) {
1355 SmallString<256> Str;
1356 raw_svector_ostream OS(Str);
1357 OS << "parsed instruction: [";
1358 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1359 if (i != 0)
1360 OS << ", ";
Jim Grosbachb7f689b2011-07-13 15:34:57 +00001361 ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001362 }
1363 OS << "]";
1364
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001365 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001366 }
1367
Kevin Enderby613b7572011-11-01 22:27:22 +00001368 // If we are generating dwarf for assembly source files and the current
1369 // section is the initial text section then generate a .loc directive for
1370 // the instruction.
1371 if (!HadError && getContext().getGenDwarfForAssembly() &&
1372 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1373 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1374 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1375 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001376 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001377 StringRef());
1378 }
1379
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001380 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001381 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001382 unsigned ErrorInfo;
1383 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Opcode,
Chad Rosier8f138d12012-10-15 17:19:13 +00001384 ParsedOperands, Out,
1385 ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001386 ParsingInlineAsm);
1387 }
Chris Lattner98986712010-01-14 22:21:20 +00001388
Chad Rosierb1f8c132012-10-18 15:49:34 +00001389 // Free any parsed operands. If parsing ms-style inline assembly the operands
1390 // will be freed by the ParseMSInlineAsm() function.
1391 if (!ParsingInlineAsm) {
1392 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1393 delete ParsedOperands[i];
1394 ParsedOperands.clear();
1395 }
Chris Lattner98986712010-01-14 22:21:20 +00001396
Chris Lattnercbf8a982010-09-11 16:18:25 +00001397 // Don't skip the rest of the line, the instruction parser is responsible for
1398 // that.
1399 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001400}
Chris Lattner9a023f72009-06-24 04:43:34 +00001401
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001402/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1403/// since they may not be able to be tokenized to get to the end of line token.
1404void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001405 if (!Lexer.is(AsmToken::EndOfStatement))
1406 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001407 // Eat EOL.
1408 Lex();
1409}
1410
1411/// ParseCppHashLineFilenameComment as this:
1412/// ::= # number "filename"
1413/// or just as a full line comment if it doesn't have a number and a string.
1414bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1415 Lex(); // Eat the hash token.
1416
1417 if (getLexer().isNot(AsmToken::Integer)) {
1418 // Consume the line since in cases it is not a well-formed line directive,
1419 // as if were simply a full line comment.
1420 EatToEndOfLine();
1421 return false;
1422 }
1423
1424 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001425 Lex();
1426
1427 if (getLexer().isNot(AsmToken::String)) {
1428 EatToEndOfLine();
1429 return false;
1430 }
1431
1432 StringRef Filename = getTok().getString();
1433 // Get rid of the enclosing quotes.
1434 Filename = Filename.substr(1, Filename.size()-2);
1435
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001436 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1437 CppHashLoc = L;
1438 CppHashFilename = Filename;
1439 CppHashLineNumber = LineNumber;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001440
1441 // Ignore any trailing characters, they're just comment.
1442 EatToEndOfLine();
1443 return false;
1444}
1445
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001446/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001447/// for the Filename and LineNo if any in the diagnostic.
1448void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1449 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1450 raw_ostream &OS = errs();
1451
1452 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1453 const SMLoc &DiagLoc = Diag.getLoc();
1454 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1455 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1456
1457 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1458 // before printing the message.
1459 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001460 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001461 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1462 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1463 }
1464
1465 // If we have not parsed a cpp hash line filename comment or the source
1466 // manager changed or buffer changed (like in a nested include) then just
1467 // print the normal diagnostic using its Filename and LineNo.
1468 if (!Parser->CppHashLineNumber ||
1469 &DiagSrcMgr != &Parser->SrcMgr ||
1470 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001471 if (Parser->SavedDiagHandler)
1472 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1473 else
1474 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001475 return;
1476 }
1477
1478 // Use the CppHashFilename and calculate a line number based on the
1479 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1480 // the diagnostic.
1481 const std::string Filename = Parser->CppHashFilename;
1482
1483 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1484 int CppHashLocLineNo =
1485 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1486 int LineNo = Parser->CppHashLineNumber - 1 +
1487 (DiagLocLineNo - CppHashLocLineNo);
1488
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001489 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1490 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001491 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001492 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001493
Benjamin Kramer04a04262011-10-16 10:48:29 +00001494 if (Parser->SavedDiagHandler)
1495 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1496 else
1497 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001498}
1499
Rafael Espindola799aacf2012-08-21 18:29:30 +00001500// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1501// difference being that that function accepts '@' as part of identifiers and
1502// we can't do that. AsmLexer.cpp should probably be changed to handle
1503// '@' as a special case when needed.
1504static bool isIdentifierChar(char c) {
1505 return isalnum(c) || c == '_' || c == '$' || c == '.';
1506}
1507
Rafael Espindola761cb062012-06-03 23:57:14 +00001508bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +00001509 const MacroParameters &Parameters,
1510 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001511 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001512 unsigned NParameters = Parameters.size();
1513 if (NParameters != 0 && NParameters != A.size())
1514 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001515
Preston Gurd7b6f2032012-09-19 20:36:12 +00001516 // A macro without parameters is handled differently on Darwin:
1517 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001518 while (!Body.empty()) {
1519 // Scan for the next substitution.
1520 std::size_t End = Body.size(), Pos = 0;
1521 for (; Pos != End; ++Pos) {
1522 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001523 if (!NParameters) {
1524 // This macro has no parameters, look for $0, $1, etc.
1525 if (Body[Pos] != '$' || Pos + 1 == End)
1526 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001527
Rafael Espindola65366442011-06-05 02:43:45 +00001528 char Next = Body[Pos + 1];
1529 if (Next == '$' || Next == 'n' || isdigit(Next))
1530 break;
1531 } else {
1532 // This macro has parameters, look for \foo, \bar, etc.
1533 if (Body[Pos] == '\\' && Pos + 1 != End)
1534 break;
1535 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001536 }
1537
1538 // Add the prefix.
1539 OS << Body.slice(0, Pos);
1540
1541 // Check if we reached the end.
1542 if (Pos == End)
1543 break;
1544
Rafael Espindola65366442011-06-05 02:43:45 +00001545 if (!NParameters) {
1546 switch (Body[Pos+1]) {
1547 // $$ => $
1548 case '$':
1549 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001550 break;
1551
Rafael Espindola65366442011-06-05 02:43:45 +00001552 // $n => number of arguments
1553 case 'n':
1554 OS << A.size();
1555 break;
1556
1557 // $[0-9] => argument
1558 default: {
1559 // Missing arguments are ignored.
1560 unsigned Index = Body[Pos+1] - '0';
1561 if (Index >= A.size())
1562 break;
1563
1564 // Otherwise substitute with the token values, with spaces eliminated.
Rafael Espindola28c1f6662012-06-03 22:41:23 +00001565 for (MacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001566 ie = A[Index].end(); it != ie; ++it)
1567 OS << it->getString();
1568 break;
1569 }
1570 }
1571 Pos += 2;
1572 } else {
1573 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001574 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001575 ++I;
1576
1577 const char *Begin = Body.data() + Pos +1;
1578 StringRef Argument(Begin, I - (Pos +1));
1579 unsigned Index = 0;
1580 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001581 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001582 break;
1583
Preston Gurd7b6f2032012-09-19 20:36:12 +00001584 if (Index == NParameters) {
1585 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1586 Pos += 3;
1587 else {
1588 OS << '\\' << Argument;
1589 Pos = I;
1590 }
1591 } else {
1592 for (MacroArgument::const_iterator it = A[Index].begin(),
1593 ie = A[Index].end(); it != ie; ++it)
1594 if (it->getKind() == AsmToken::String)
1595 OS << it->getStringContents();
1596 else
1597 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001598
Preston Gurd7b6f2032012-09-19 20:36:12 +00001599 Pos += 1 + Argument.size();
1600 }
Rafael Espindola65366442011-06-05 02:43:45 +00001601 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001602 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001603 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001604 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001605
Rafael Espindola65366442011-06-05 02:43:45 +00001606 return false;
1607}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001608
Rafael Espindola65366442011-06-05 02:43:45 +00001609MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1610 MemoryBuffer *I)
1611 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1612{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001613}
1614
Preston Gurd7b6f2032012-09-19 20:36:12 +00001615static bool IsOperator(AsmToken::TokenKind kind)
1616{
1617 switch (kind)
1618 {
1619 default:
1620 return false;
1621 case AsmToken::Plus:
1622 case AsmToken::Minus:
1623 case AsmToken::Tilde:
1624 case AsmToken::Slash:
1625 case AsmToken::Star:
1626 case AsmToken::Dot:
1627 case AsmToken::Equal:
1628 case AsmToken::EqualEqual:
1629 case AsmToken::Pipe:
1630 case AsmToken::PipePipe:
1631 case AsmToken::Caret:
1632 case AsmToken::Amp:
1633 case AsmToken::AmpAmp:
1634 case AsmToken::Exclaim:
1635 case AsmToken::ExclaimEqual:
1636 case AsmToken::Percent:
1637 case AsmToken::Less:
1638 case AsmToken::LessEqual:
1639 case AsmToken::LessLess:
1640 case AsmToken::LessGreater:
1641 case AsmToken::Greater:
1642 case AsmToken::GreaterEqual:
1643 case AsmToken::GreaterGreater:
1644 return true;
1645 }
1646}
1647
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001648/// ParseMacroArgument - Extract AsmTokens for a macro argument.
1649/// This is used for both default macro parameter values and the
1650/// arguments in macro invocations
Preston Gurd7b6f2032012-09-19 20:36:12 +00001651bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1652 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001653 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001654 unsigned AddTokens = 0;
1655
1656 // gas accepts arguments separated by whitespace, except on Darwin
1657 if (!IsDarwin)
1658 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001659
1660 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001661 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1662 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001663 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001664 }
1665
1666 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1667 // Spaces and commas cannot be mixed to delimit parameters
1668 if (ArgumentDelimiter == AsmToken::Eof)
1669 ArgumentDelimiter = AsmToken::Comma;
1670 else if (ArgumentDelimiter != AsmToken::Comma) {
1671 Lexer.setSkipSpace(true);
1672 return TokError("expected ' ' for macro argument separator");
1673 }
1674 break;
1675 }
1676
1677 if (Lexer.is(AsmToken::Space)) {
1678 Lex(); // Eat spaces
1679
1680 // Spaces can delimit parameters, but could also be part an expression.
1681 // If the token after a space is an operator, add the token and the next
1682 // one into this argument
1683 if (ArgumentDelimiter == AsmToken::Space ||
1684 ArgumentDelimiter == AsmToken::Eof) {
1685 if (IsOperator(Lexer.getKind())) {
1686 // Check to see whether the token is used as an operator,
1687 // or part of an identifier
1688 const char *NextChar = getTok().getEndLoc().getPointer() + 1;
1689 if (*NextChar == ' ')
1690 AddTokens = 2;
1691 }
1692
1693 if (!AddTokens && ParenLevel == 0) {
1694 if (ArgumentDelimiter == AsmToken::Eof &&
1695 !IsOperator(Lexer.getKind()))
1696 ArgumentDelimiter = AsmToken::Space;
1697 break;
1698 }
1699 }
1700 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001701
1702 // HandleMacroEntry relies on not advancing the lexer here
1703 // to be able to fill in the remaining default parameter values
1704 if (Lexer.is(AsmToken::EndOfStatement))
1705 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001706
1707 // Adjust the current parentheses level.
1708 if (Lexer.is(AsmToken::LParen))
1709 ++ParenLevel;
1710 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1711 --ParenLevel;
1712
1713 // Append the token to the current argument list.
1714 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001715 if (AddTokens)
1716 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001717 Lex();
1718 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001719
1720 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001721 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001722 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001723 return false;
1724}
1725
1726// Parse the macro instantiation arguments.
Rafael Espindola8a403d32012-08-08 14:51:03 +00001727bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001728 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001729 // Argument delimiter is initially unknown. It will be set by
1730 // ParseMacroArgument()
1731 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001732
1733 // Parse two kinds of macro invocations:
1734 // - macros defined without any parameters accept an arbitrary number of them
1735 // - macros defined with parameters accept at most that many of them
1736 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1737 ++Parameter) {
1738 MacroArgument MA;
1739
Preston Gurd7b6f2032012-09-19 20:36:12 +00001740 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001741 return true;
1742
Preston Gurd6c9176a2012-09-19 20:29:04 +00001743 if (!MA.empty() || !NParameters)
1744 A.push_back(MA);
1745 else if (NParameters) {
1746 if (!M->Parameters[Parameter].second.empty())
1747 A.push_back(M->Parameters[Parameter].second);
1748 }
Jim Grosbach97146442012-07-30 22:44:17 +00001749
Preston Gurd6c9176a2012-09-19 20:29:04 +00001750 // At the end of the statement, fill in remaining arguments that have
1751 // default values. If there aren't any, then the next argument is
1752 // required but missing
1753 if (Lexer.is(AsmToken::EndOfStatement)) {
1754 if (NParameters && Parameter < NParameters - 1) {
1755 if (M->Parameters[Parameter + 1].second.empty())
1756 return TokError("macro argument '" +
1757 Twine(M->Parameters[Parameter + 1].first) +
1758 "' is missing");
1759 else
1760 continue;
1761 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001762 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001763 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001764
1765 if (Lexer.is(AsmToken::Comma))
1766 Lex();
1767 }
1768 return TokError("Too many arguments");
1769}
1770
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001771bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1772 const Macro *M) {
1773 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1774 // this, although we should protect against infinite loops.
1775 if (ActiveMacros.size() == 20)
1776 return TokError("macros cannot be nested more than 20 levels deep");
1777
Rafael Espindola8a403d32012-08-08 14:51:03 +00001778 MacroArguments A;
1779 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001780 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001781
Jim Grosbach97146442012-07-30 22:44:17 +00001782 // Remove any trailing empty arguments. Do this after-the-fact as we have
1783 // to keep empty arguments in the middle of the list or positionality
1784 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001785 while (!A.empty() && A.back().empty())
1786 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001787
Rafael Espindola65366442011-06-05 02:43:45 +00001788 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1789 // to hold the macro body with substitutions.
1790 SmallString<256> Buf;
1791 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001792 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001793
Rafael Espindola8a403d32012-08-08 14:51:03 +00001794 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001795 return true;
1796
Rafael Espindola761cb062012-06-03 23:57:14 +00001797 // We include the .endmacro in the buffer as our queue to exit the macro
1798 // instantiation.
1799 OS << ".endmacro\n";
1800
Rafael Espindola65366442011-06-05 02:43:45 +00001801 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001802 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001803
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001804 // Create the macro instantiation object and add to the current macro
1805 // instantiation stack.
1806 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001807 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001808 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001809 ActiveMacros.push_back(MI);
1810
1811 // Jump to the macro instantiation and prime the lexer.
1812 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1813 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1814 Lex();
1815
1816 return false;
1817}
1818
1819void AsmParser::HandleMacroExit() {
1820 // Jump to the EndOfStatement we should return to, and consume it.
1821 JumpToLoc(ActiveMacros.back()->ExitLoc);
1822 Lex();
1823
1824 // Pop the instantiation entry.
1825 delete ActiveMacros.back();
1826 ActiveMacros.pop_back();
1827}
1828
Rafael Espindolae71cc862012-01-28 05:57:00 +00001829static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001830 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001831 case MCExpr::Binary: {
1832 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1833 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001834 break;
1835 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001836 case MCExpr::Target:
1837 case MCExpr::Constant:
1838 return false;
1839 case MCExpr::SymbolRef: {
1840 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001841 if (S.isVariable())
1842 return IsUsedIn(Sym, S.getVariableValue());
1843 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001844 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001845 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001846 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001847 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001848
1849 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001850}
1851
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001852bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1853 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001854 // FIXME: Use better location, we should use proper tokens.
1855 SMLoc EqualLoc = Lexer.getLoc();
1856
Daniel Dunbar821e3332009-08-31 08:09:28 +00001857 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001858 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001859 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001860
Rafael Espindolae71cc862012-01-28 05:57:00 +00001861 // Note: we don't count b as used in "a = b". This is to allow
1862 // a = b
1863 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001864
Daniel Dunbar3f872332009-07-28 16:08:33 +00001865 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001866 return TokError("unexpected token in assignment");
1867
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001868 // Error on assignment to '.'.
1869 if (Name == ".") {
1870 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1871 "(use '.space' or '.org').)"));
1872 }
1873
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001874 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001875 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001876
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001877 // Validate that the LHS is allowed to be a variable (either it has not been
1878 // used as a symbol, or it is an absolute symbol).
1879 MCSymbol *Sym = getContext().LookupSymbol(Name);
1880 if (Sym) {
1881 // Diagnose assignment to a label.
1882 //
1883 // FIXME: Diagnostics. Note the location of the definition as a label.
1884 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00001885 if (IsUsedIn(Sym, Value))
1886 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1887 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001888 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00001889 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1890 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00001891 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001892 return Error(EqualLoc, "redefinition of '" + Name + "'");
1893 else if (!Sym->isVariable())
1894 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00001895 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001896 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1897 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001898
1899 // Don't count these checks as uses.
1900 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001901 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001902 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001903
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001904 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001905
1906 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00001907 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001908 if (NoDeadStrip)
1909 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1910
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001911
1912 return false;
1913}
1914
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001915/// ParseIdentifier:
1916/// ::= identifier
1917/// ::= string
1918bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00001919 // The assembler has relaxed rules for accepting identifiers, in particular we
1920 // allow things like '.globl $foo', which would normally be separate
1921 // tokens. At this level, we have already lexed so we cannot (currently)
1922 // handle this as a context dependent token, instead we detect adjacent tokens
1923 // and return the combined identifier.
1924 if (Lexer.is(AsmToken::Dollar)) {
1925 SMLoc DollarLoc = getLexer().getLoc();
1926
1927 // Consume the dollar sign, and check for a following identifier.
1928 Lex();
1929 if (Lexer.isNot(AsmToken::Identifier))
1930 return true;
1931
1932 // We have a '$' followed by an identifier, make sure they are adjacent.
1933 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1934 return true;
1935
1936 // Construct the joined identifier and consume the token.
1937 Res = StringRef(DollarLoc.getPointer(),
1938 getTok().getIdentifier().size() + 1);
1939 Lex();
1940 return false;
1941 }
1942
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001943 if (Lexer.isNot(AsmToken::Identifier) &&
1944 Lexer.isNot(AsmToken::String))
1945 return true;
1946
Sean Callanan18b83232010-01-19 21:44:56 +00001947 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001948
Sean Callanan79ed1a82010-01-19 20:22:31 +00001949 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001950
1951 return false;
1952}
1953
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001954/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00001955/// ::= .equ identifier ',' expression
1956/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001957/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00001958bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001959 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001960
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001961 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00001962 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001963
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001964 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00001965 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001966 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001967
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001968 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001969}
1970
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001971bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001972 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001973
1974 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00001975 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001976 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1977 if (Str[i] != '\\') {
1978 Data += Str[i];
1979 continue;
1980 }
1981
1982 // Recognize escaped characters. Note that this escape semantics currently
1983 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1984 ++i;
1985 if (i == e)
1986 return TokError("unexpected backslash at end of string");
1987
1988 // Recognize octal sequences.
1989 if ((unsigned) (Str[i] - '0') <= 7) {
1990 // Consume up to three octal characters.
1991 unsigned Value = Str[i] - '0';
1992
1993 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1994 ++i;
1995 Value = Value * 8 + (Str[i] - '0');
1996
1997 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1998 ++i;
1999 Value = Value * 8 + (Str[i] - '0');
2000 }
2001 }
2002
2003 if (Value > 255)
2004 return TokError("invalid octal escape sequence (out of range)");
2005
2006 Data += (unsigned char) Value;
2007 continue;
2008 }
2009
2010 // Otherwise recognize individual escapes.
2011 switch (Str[i]) {
2012 default:
2013 // Just reject invalid escape sequences for now.
2014 return TokError("invalid escape sequence (unrecognized character)");
2015
2016 case 'b': Data += '\b'; break;
2017 case 'f': Data += '\f'; break;
2018 case 'n': Data += '\n'; break;
2019 case 'r': Data += '\r'; break;
2020 case 't': Data += '\t'; break;
2021 case '"': Data += '"'; break;
2022 case '\\': Data += '\\'; break;
2023 }
2024 }
2025
2026 return false;
2027}
2028
Daniel Dunbara0d14262009-06-24 23:30:00 +00002029/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002030/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2031bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002032 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002033 CheckForValidSection();
2034
Daniel Dunbara0d14262009-06-24 23:30:00 +00002035 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002036 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002037 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002038
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002039 std::string Data;
2040 if (ParseEscapedString(Data))
2041 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002042
2043 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002044 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002045 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2046
Sean Callanan79ed1a82010-01-19 20:22:31 +00002047 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002048
2049 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002050 break;
2051
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002052 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002053 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002054 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002055 }
2056 }
2057
Sean Callanan79ed1a82010-01-19 20:22:31 +00002058 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002059 return false;
2060}
2061
2062/// ParseDirectiveValue
2063/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2064bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002065 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002066 CheckForValidSection();
2067
Daniel Dunbara0d14262009-06-24 23:30:00 +00002068 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002069 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002070 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002071 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002072 return true;
2073
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002074 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002075 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2076 assert(Size <= 8 && "Invalid size");
2077 uint64_t IntValue = MCE->getValue();
2078 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2079 return Error(ExprLoc, "literal value out of range for directive");
2080 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2081 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002082 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002083
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002084 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002085 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002086
Daniel Dunbara0d14262009-06-24 23:30:00 +00002087 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002088 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002089 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002090 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002091 }
2092 }
2093
Sean Callanan79ed1a82010-01-19 20:22:31 +00002094 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002095 return false;
2096}
2097
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002098/// ParseDirectiveRealValue
2099/// ::= (.single | .double) [ expression (, expression)* ]
2100bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2101 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2102 CheckForValidSection();
2103
2104 for (;;) {
2105 // We don't truly support arithmetic on floating point expressions, so we
2106 // have to manually parse unary prefixes.
2107 bool IsNeg = false;
2108 if (getLexer().is(AsmToken::Minus)) {
2109 Lex();
2110 IsNeg = true;
2111 } else if (getLexer().is(AsmToken::Plus))
2112 Lex();
2113
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002114 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002115 getLexer().isNot(AsmToken::Real) &&
2116 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002117 return TokError("unexpected token in directive");
2118
2119 // Convert to an APFloat.
2120 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002121 StringRef IDVal = getTok().getString();
2122 if (getLexer().is(AsmToken::Identifier)) {
2123 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2124 Value = APFloat::getInf(Semantics);
2125 else if (!IDVal.compare_lower("nan"))
2126 Value = APFloat::getNaN(Semantics, false, ~0);
2127 else
2128 return TokError("invalid floating point literal");
2129 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002130 APFloat::opInvalidOp)
2131 return TokError("invalid floating point literal");
2132 if (IsNeg)
2133 Value.changeSign();
2134
2135 // Consume the numeric token.
2136 Lex();
2137
2138 // Emit the value as an integer.
2139 APInt AsInt = Value.bitcastToAPInt();
2140 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2141 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2142
2143 if (getLexer().is(AsmToken::EndOfStatement))
2144 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002145
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002146 if (getLexer().isNot(AsmToken::Comma))
2147 return TokError("unexpected token in directive");
2148 Lex();
2149 }
2150 }
2151
2152 Lex();
2153 return false;
2154}
2155
Daniel Dunbara0d14262009-06-24 23:30:00 +00002156/// ParseDirectiveSpace
2157/// ::= .space expression [ , expression ]
2158bool AsmParser::ParseDirectiveSpace() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002159 CheckForValidSection();
2160
Daniel Dunbara0d14262009-06-24 23:30:00 +00002161 int64_t NumBytes;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002162 if (ParseAbsoluteExpression(NumBytes))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002163 return true;
2164
2165 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002166 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2167 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002168 return TokError("unexpected token in '.space' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002169 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002170
Daniel Dunbar475839e2009-06-29 20:37:27 +00002171 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002172 return true;
2173
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002174 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002175 return TokError("unexpected token in '.space' directive");
2176 }
2177
Sean Callanan79ed1a82010-01-19 20:22:31 +00002178 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002179
2180 if (NumBytes <= 0)
2181 return TokError("invalid number of bytes in '.space' directive");
2182
2183 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002184 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002185
2186 return false;
2187}
2188
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002189/// ParseDirectiveZero
2190/// ::= .zero expression
2191bool AsmParser::ParseDirectiveZero() {
2192 CheckForValidSection();
2193
2194 int64_t NumBytes;
2195 if (ParseAbsoluteExpression(NumBytes))
2196 return true;
2197
Rafael Espindolae452b172010-10-05 19:42:57 +00002198 int64_t Val = 0;
2199 if (getLexer().is(AsmToken::Comma)) {
2200 Lex();
2201 if (ParseAbsoluteExpression(Val))
2202 return true;
2203 }
2204
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002205 if (getLexer().isNot(AsmToken::EndOfStatement))
2206 return TokError("unexpected token in '.zero' directive");
2207
2208 Lex();
2209
Rafael Espindolae452b172010-10-05 19:42:57 +00002210 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002211
2212 return false;
2213}
2214
Daniel Dunbara0d14262009-06-24 23:30:00 +00002215/// ParseDirectiveFill
2216/// ::= .fill expression , expression , expression
2217bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002218 CheckForValidSection();
2219
Daniel Dunbara0d14262009-06-24 23:30:00 +00002220 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002221 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002222 return true;
2223
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002224 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002225 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002226 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002227
Daniel Dunbara0d14262009-06-24 23:30:00 +00002228 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002229 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002230 return true;
2231
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002232 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002233 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002234 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002235
Daniel Dunbara0d14262009-06-24 23:30:00 +00002236 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002237 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002238 return true;
2239
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002240 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002241 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002242
Sean Callanan79ed1a82010-01-19 20:22:31 +00002243 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002244
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002245 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2246 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002247
2248 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002249 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002250
2251 return false;
2252}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002253
2254/// ParseDirectiveOrg
2255/// ::= .org expression [ , expression ]
2256bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002257 CheckForValidSection();
2258
Daniel Dunbar821e3332009-08-31 08:09:28 +00002259 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002260 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002261 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002262 return true;
2263
2264 // Parse optional fill expression.
2265 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002266 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2267 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002268 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002269 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002270
Daniel Dunbar475839e2009-06-29 20:37:27 +00002271 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002272 return true;
2273
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002274 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002275 return TokError("unexpected token in '.org' directive");
2276 }
2277
Sean Callanan79ed1a82010-01-19 20:22:31 +00002278 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002279
Jim Grosbachebd4c052012-01-27 00:37:08 +00002280 // Only limited forms of relocatable expressions are accepted here, it
2281 // has to be relative to the current section. The streamer will return
2282 // 'true' if the expression wasn't evaluatable.
2283 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2284 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002285
2286 return false;
2287}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002288
2289/// ParseDirectiveAlign
2290/// ::= {.align, ...} expression [ , expression [ , expression ]]
2291bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002292 CheckForValidSection();
2293
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002294 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002295 int64_t Alignment;
2296 if (ParseAbsoluteExpression(Alignment))
2297 return true;
2298
2299 SMLoc MaxBytesLoc;
2300 bool HasFillExpr = false;
2301 int64_t FillExpr = 0;
2302 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002303 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2304 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002305 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002306 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002307
2308 // The fill expression can be omitted while specifying a maximum number of
2309 // alignment bytes, e.g:
2310 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002311 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002312 HasFillExpr = true;
2313 if (ParseAbsoluteExpression(FillExpr))
2314 return true;
2315 }
2316
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002317 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2318 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002319 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002320 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002321
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002322 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002323 if (ParseAbsoluteExpression(MaxBytesToFill))
2324 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002325
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002326 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002327 return TokError("unexpected token in directive");
2328 }
2329 }
2330
Sean Callanan79ed1a82010-01-19 20:22:31 +00002331 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002332
Daniel Dunbar648ac512010-05-17 21:54:30 +00002333 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002334 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002335
2336 // Compute alignment in bytes.
2337 if (IsPow2) {
2338 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002339 if (Alignment >= 32) {
2340 Error(AlignmentLoc, "invalid alignment value");
2341 Alignment = 31;
2342 }
2343
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002344 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002345 }
2346
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002347 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002348 if (MaxBytesLoc.isValid()) {
2349 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002350 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2351 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002352 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002353 }
2354
2355 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002356 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2357 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002358 MaxBytesToFill = 0;
2359 }
2360 }
2361
Daniel Dunbar648ac512010-05-17 21:54:30 +00002362 // Check whether we should use optimal code alignment for this .align
2363 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002364 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002365 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2366 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002367 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002368 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002369 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002370 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2371 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002372 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002373
2374 return false;
2375}
2376
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002377/// ParseDirectiveSymbolAttribute
2378/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00002379bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002380 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002381 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002382 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00002383 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002384
2385 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00002386 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002387
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002388 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002389
Jim Grosbach10ec6502011-09-15 17:56:49 +00002390 // Assembler local symbols don't make any sense here. Complain loudly.
2391 if (Sym->isTemporary())
2392 return Error(Loc, "non-local symbol required in directive");
2393
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002394 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002395
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002396 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002397 break;
2398
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002399 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002400 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002401 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002402 }
2403 }
2404
Sean Callanan79ed1a82010-01-19 20:22:31 +00002405 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00002406 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002407}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002408
2409/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00002410/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2411bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002412 CheckForValidSection();
2413
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002414 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002415 StringRef Name;
2416 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002417 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002418
Daniel Dunbar76c4d762009-07-31 21:55:09 +00002419 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002420 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002421
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002422 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002423 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002424 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002425
2426 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002427 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002428 if (ParseAbsoluteExpression(Size))
2429 return true;
2430
2431 int64_t Pow2Alignment = 0;
2432 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002433 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00002434 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002435 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002436 if (ParseAbsoluteExpression(Pow2Alignment))
2437 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002438
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002439 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2440 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00002441 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2442
Chris Lattner258281d2010-01-19 06:22:22 +00002443 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002444 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2445 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00002446 if (!isPowerOf2_64(Pow2Alignment))
2447 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2448 Pow2Alignment = Log2_64(Pow2Alignment);
2449 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002450 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002451
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002452 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00002453 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002454
Sean Callanan79ed1a82010-01-19 20:22:31 +00002455 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002456
Chris Lattner1fc3d752009-07-09 17:25:12 +00002457 // NOTE: a size of zero for a .comm should create a undefined symbol
2458 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002459 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002460 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2461 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002462
Eric Christopherc260a3e2010-05-14 01:38:54 +00002463 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002464 // may internally end up wanting an alignment in bytes.
2465 // FIXME: Diagnose overflow.
2466 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002467 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2468 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002469
Daniel Dunbar8906ff12009-08-22 07:22:36 +00002470 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002471 return Error(IDLoc, "invalid symbol redefinition");
2472
Chris Lattner1fc3d752009-07-09 17:25:12 +00002473 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002474 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00002475 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002476 return false;
2477 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002478
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002479 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002480 return false;
2481}
Chris Lattner9be3fee2009-07-10 22:20:30 +00002482
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002483/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002484/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002485bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002486 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002487 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002488
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002489 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002490 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002491 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002492
Sean Callanan79ed1a82010-01-19 20:22:31 +00002493 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002494
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002495 if (Str.empty())
2496 Error(Loc, ".abort detected. Assembly stopping.");
2497 else
2498 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002499 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002500
2501 return false;
2502}
Kevin Enderby71148242009-07-14 21:35:03 +00002503
Kevin Enderby1f049b22009-07-14 23:21:55 +00002504/// ParseDirectiveInclude
2505/// ::= .include "filename"
2506bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002507 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002508 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002509
Sean Callanan18b83232010-01-19 21:44:56 +00002510 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002511 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002512 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00002513
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002514 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002515 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002516
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002517 // Strip the quotes.
2518 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002519
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002520 // Attempt to switch the lexer to the included file before consuming the end
2521 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00002522 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00002523 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002524 return true;
2525 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00002526
2527 return false;
2528}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00002529
Kevin Enderbyc55acca2011-12-14 21:47:48 +00002530/// ParseDirectiveIncbin
2531/// ::= .incbin "filename"
2532bool AsmParser::ParseDirectiveIncbin() {
2533 if (getLexer().isNot(AsmToken::String))
2534 return TokError("expected string in '.incbin' directive");
2535
2536 std::string Filename = getTok().getString();
2537 SMLoc IncbinLoc = getLexer().getLoc();
2538 Lex();
2539
2540 if (getLexer().isNot(AsmToken::EndOfStatement))
2541 return TokError("unexpected token in '.incbin' directive");
2542
2543 // Strip the quotes.
2544 Filename = Filename.substr(1, Filename.size()-2);
2545
2546 // Attempt to process the included file.
2547 if (ProcessIncbinFile(Filename)) {
2548 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2549 return true;
2550 }
2551
2552 return false;
2553}
2554
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002555/// ParseDirectiveIf
2556/// ::= .if expression
2557bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002558 TheCondStack.push_back(TheCondState);
2559 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00002560 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002561 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00002562 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002563 int64_t ExprValue;
2564 if (ParseAbsoluteExpression(ExprValue))
2565 return true;
2566
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002567 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002568 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002569
Sean Callanan79ed1a82010-01-19 20:22:31 +00002570 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002571
2572 TheCondState.CondMet = ExprValue;
2573 TheCondState.Ignore = !TheCondState.CondMet;
2574 }
2575
2576 return false;
2577}
2578
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002579/// ParseDirectiveIfb
2580/// ::= .ifb string
2581bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2582 TheCondStack.push_back(TheCondState);
2583 TheCondState.TheCond = AsmCond::IfCond;
2584
Benjamin Kramer29739e72012-05-12 16:52:21 +00002585 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002586 EatToEndOfStatement();
2587 } else {
2588 StringRef Str = ParseStringToEndOfStatement();
2589
2590 if (getLexer().isNot(AsmToken::EndOfStatement))
2591 return TokError("unexpected token in '.ifb' directive");
2592
2593 Lex();
2594
2595 TheCondState.CondMet = ExpectBlank == Str.empty();
2596 TheCondState.Ignore = !TheCondState.CondMet;
2597 }
2598
2599 return false;
2600}
2601
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002602/// ParseDirectiveIfc
2603/// ::= .ifc string1, string2
2604bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2605 TheCondStack.push_back(TheCondState);
2606 TheCondState.TheCond = AsmCond::IfCond;
2607
Benjamin Kramer29739e72012-05-12 16:52:21 +00002608 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002609 EatToEndOfStatement();
2610 } else {
2611 StringRef Str1 = ParseStringToComma();
2612
2613 if (getLexer().isNot(AsmToken::Comma))
2614 return TokError("unexpected token in '.ifc' directive");
2615
2616 Lex();
2617
2618 StringRef Str2 = ParseStringToEndOfStatement();
2619
2620 if (getLexer().isNot(AsmToken::EndOfStatement))
2621 return TokError("unexpected token in '.ifc' directive");
2622
2623 Lex();
2624
2625 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2626 TheCondState.Ignore = !TheCondState.CondMet;
2627 }
2628
2629 return false;
2630}
2631
2632/// ParseDirectiveIfdef
2633/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00002634bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2635 StringRef Name;
2636 TheCondStack.push_back(TheCondState);
2637 TheCondState.TheCond = AsmCond::IfCond;
2638
2639 if (TheCondState.Ignore) {
2640 EatToEndOfStatement();
2641 } else {
2642 if (ParseIdentifier(Name))
2643 return TokError("expected identifier after '.ifdef'");
2644
2645 Lex();
2646
2647 MCSymbol *Sym = getContext().LookupSymbol(Name);
2648
2649 if (expect_defined)
2650 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2651 else
2652 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2653 TheCondState.Ignore = !TheCondState.CondMet;
2654 }
2655
2656 return false;
2657}
2658
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002659/// ParseDirectiveElseIf
2660/// ::= .elseif expression
2661bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2662 if (TheCondState.TheCond != AsmCond::IfCond &&
2663 TheCondState.TheCond != AsmCond::ElseIfCond)
2664 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2665 " an .elseif");
2666 TheCondState.TheCond = AsmCond::ElseIfCond;
2667
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002668 bool LastIgnoreState = false;
2669 if (!TheCondStack.empty())
2670 LastIgnoreState = TheCondStack.back().Ignore;
2671 if (LastIgnoreState || TheCondState.CondMet) {
2672 TheCondState.Ignore = true;
2673 EatToEndOfStatement();
2674 }
2675 else {
2676 int64_t ExprValue;
2677 if (ParseAbsoluteExpression(ExprValue))
2678 return true;
2679
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002680 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002681 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002682
Sean Callanan79ed1a82010-01-19 20:22:31 +00002683 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002684 TheCondState.CondMet = ExprValue;
2685 TheCondState.Ignore = !TheCondState.CondMet;
2686 }
2687
2688 return false;
2689}
2690
2691/// ParseDirectiveElse
2692/// ::= .else
2693bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002694 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002695 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002696
Sean Callanan79ed1a82010-01-19 20:22:31 +00002697 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002698
2699 if (TheCondState.TheCond != AsmCond::IfCond &&
2700 TheCondState.TheCond != AsmCond::ElseIfCond)
2701 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2702 ".elseif");
2703 TheCondState.TheCond = AsmCond::ElseCond;
2704 bool LastIgnoreState = false;
2705 if (!TheCondStack.empty())
2706 LastIgnoreState = TheCondStack.back().Ignore;
2707 if (LastIgnoreState || TheCondState.CondMet)
2708 TheCondState.Ignore = true;
2709 else
2710 TheCondState.Ignore = false;
2711
2712 return false;
2713}
2714
2715/// ParseDirectiveEndIf
2716/// ::= .endif
2717bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002718 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002719 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002720
Sean Callanan79ed1a82010-01-19 20:22:31 +00002721 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002722
2723 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2724 TheCondStack.empty())
2725 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2726 ".else");
2727 if (!TheCondStack.empty()) {
2728 TheCondState = TheCondStack.back();
2729 TheCondStack.pop_back();
2730 }
2731
2732 return false;
2733}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002734
2735/// ParseDirectiveFile
Nick Lewycky44d798d2011-10-17 23:05:28 +00002736/// ::= .file [number] filename
2737/// ::= .file number directory filename
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002738bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002739 // FIXME: I'm not sure what this is.
2740 int64_t FileNumber = -1;
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002741 SMLoc FileNumberLoc = getLexer().getLoc();
Daniel Dunbareceec052010-07-12 17:45:27 +00002742 if (getLexer().is(AsmToken::Integer)) {
Sean Callanan18b83232010-01-19 21:44:56 +00002743 FileNumber = getTok().getIntVal();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002744 Lex();
Daniel Dunbareceec052010-07-12 17:45:27 +00002745
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002746 if (FileNumber < 1)
2747 return TokError("file number less than one");
2748 }
2749
Daniel Dunbareceec052010-07-12 17:45:27 +00002750 if (getLexer().isNot(AsmToken::String))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002751 return TokError("unexpected token in '.file' directive");
Daniel Dunbareceec052010-07-12 17:45:27 +00002752
Nick Lewycky44d798d2011-10-17 23:05:28 +00002753 // Usually the directory and filename together, otherwise just the directory.
2754 StringRef Path = getTok().getString();
2755 Path = Path.substr(1, Path.size()-2);
Sean Callanan79ed1a82010-01-19 20:22:31 +00002756 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002757
Nick Lewycky44d798d2011-10-17 23:05:28 +00002758 StringRef Directory;
2759 StringRef Filename;
2760 if (getLexer().is(AsmToken::String)) {
2761 if (FileNumber == -1)
2762 return TokError("explicit path specified, but no file number");
2763 Filename = getTok().getString();
2764 Filename = Filename.substr(1, Filename.size()-2);
2765 Directory = Path;
2766 Lex();
2767 } else {
2768 Filename = Path;
2769 }
2770
Daniel Dunbareceec052010-07-12 17:45:27 +00002771 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002772 return TokError("unexpected token in '.file' directive");
2773
Chris Lattnerd32e8032010-01-25 19:02:58 +00002774 if (FileNumber == -1)
Daniel Dunbareceec052010-07-12 17:45:27 +00002775 getStreamer().EmitFileDirective(Filename);
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002776 else {
Kevin Enderby8704b782012-01-11 18:04:47 +00002777 if (getContext().getGenDwarfForAssembly() == true)
2778 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2779 "used to generate dwarf debug info for assembly code");
2780
Nick Lewycky44d798d2011-10-17 23:05:28 +00002781 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002782 Error(FileNumberLoc, "file number already allocated");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002783 }
Daniel Dunbareceec052010-07-12 17:45:27 +00002784
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002785 return false;
2786}
2787
2788/// ParseDirectiveLine
2789/// ::= .line [number]
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002790bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbareceec052010-07-12 17:45:27 +00002791 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2792 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002793 return TokError("unexpected token in '.line' directive");
2794
Sean Callanan18b83232010-01-19 21:44:56 +00002795 int64_t LineNumber = getTok().getIntVal();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002796 (void) LineNumber;
Sean Callanan79ed1a82010-01-19 20:22:31 +00002797 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002798
2799 // FIXME: Do something with the .line.
2800 }
2801
Daniel Dunbareceec052010-07-12 17:45:27 +00002802 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar839348a2010-07-01 20:20:01 +00002803 return TokError("unexpected token in '.line' directive");
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002804
2805 return false;
2806}
2807
2808
2809/// ParseDirectiveLoc
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002810/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002811/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2812/// The first number is a file number, must have been previously assigned with
2813/// a .file directive, the second number is the line number and optionally the
2814/// third number is a column position (zero if not specified). The remaining
2815/// optional items are .loc sub-directives.
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002816bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002817
Daniel Dunbareceec052010-07-12 17:45:27 +00002818 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002819 return TokError("unexpected token in '.loc' directive");
Sean Callanan18b83232010-01-19 21:44:56 +00002820 int64_t FileNumber = getTok().getIntVal();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002821 if (FileNumber < 1)
2822 return TokError("file number less than one in '.loc' directive");
Kevin Enderby3f55c242010-10-04 20:17:24 +00002823 if (!getContext().isValidDwarfFileNumber(FileNumber))
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002824 return TokError("unassigned file number in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002825 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002826
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002827 int64_t LineNumber = 0;
2828 if (getLexer().is(AsmToken::Integer)) {
2829 LineNumber = getTok().getIntVal();
2830 if (LineNumber < 1)
2831 return TokError("line number less than one in '.loc' directive");
2832 Lex();
2833 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002834
2835 int64_t ColumnPos = 0;
2836 if (getLexer().is(AsmToken::Integer)) {
2837 ColumnPos = getTok().getIntVal();
2838 if (ColumnPos < 0)
2839 return TokError("column position less than zero in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002840 Lex();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002841 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002842
Kevin Enderbyc0957932010-09-30 16:52:03 +00002843 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002844 unsigned Isa = 0;
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002845 int64_t Discriminator = 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002846 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2847 for (;;) {
2848 if (getLexer().is(AsmToken::EndOfStatement))
2849 break;
2850
2851 StringRef Name;
2852 SMLoc Loc = getTok().getLoc();
2853 if (getParser().ParseIdentifier(Name))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002854 return TokError("unexpected token in '.loc' directive");
2855
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002856 if (Name == "basic_block")
2857 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2858 else if (Name == "prologue_end")
2859 Flags |= DWARF2_FLAG_PROLOGUE_END;
2860 else if (Name == "epilogue_begin")
2861 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2862 else if (Name == "is_stmt") {
2863 SMLoc Loc = getTok().getLoc();
2864 const MCExpr *Value;
2865 if (getParser().ParseExpression(Value))
2866 return true;
2867 // The expression must be the constant 0 or 1.
2868 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2869 int Value = MCE->getValue();
2870 if (Value == 0)
2871 Flags &= ~DWARF2_FLAG_IS_STMT;
2872 else if (Value == 1)
2873 Flags |= DWARF2_FLAG_IS_STMT;
2874 else
2875 return Error(Loc, "is_stmt value not 0 or 1");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002876 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002877 else {
2878 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2879 }
2880 }
2881 else if (Name == "isa") {
2882 SMLoc Loc = getTok().getLoc();
2883 const MCExpr *Value;
2884 if (getParser().ParseExpression(Value))
2885 return true;
2886 // The expression must be a constant greater or equal to 0.
2887 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2888 int Value = MCE->getValue();
2889 if (Value < 0)
2890 return Error(Loc, "isa number less than zero");
2891 Isa = Value;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002892 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002893 else {
2894 return Error(Loc, "isa number not a constant value");
2895 }
2896 }
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002897 else if (Name == "discriminator") {
2898 if (getParser().ParseAbsoluteExpression(Discriminator))
2899 return true;
2900 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002901 else {
2902 return Error(Loc, "unknown sub-directive in '.loc' directive");
2903 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002904
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002905 if (getLexer().is(AsmToken::EndOfStatement))
2906 break;
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002907 }
2908 }
2909
Rafael Espindolaaf6b58082010-11-16 21:20:32 +00002910 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
Devang Patel3f3bf932011-04-18 20:26:49 +00002911 Isa, Discriminator, StringRef());
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002912
2913 return false;
2914}
2915
Daniel Dunbar138abae2010-10-16 04:56:42 +00002916/// ParseDirectiveStabs
2917/// ::= .stabs string, number, number, number
2918bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2919 SMLoc DirectiveLoc) {
2920 return TokError("unsupported directive '" + Directive + "'");
2921}
2922
Rafael Espindolaf9efd832011-05-10 01:10:18 +00002923/// ParseDirectiveCFISections
2924/// ::= .cfi_sections section [, section]
2925bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2926 SMLoc DirectiveLoc) {
2927 StringRef Name;
2928 bool EH = false;
2929 bool Debug = false;
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 if (getLexer().is(AsmToken::Comma)) {
2940 Lex();
2941
2942 if (getParser().ParseIdentifier(Name))
2943 return TokError("Expected an identifier");
2944
2945 if (Name == ".eh_frame")
2946 EH = true;
2947 else if (Name == ".debug_frame")
2948 Debug = true;
2949 }
2950
2951 getStreamer().EmitCFISections(EH, Debug);
2952
2953 return false;
2954}
2955
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002956/// ParseDirectiveCFIStartProc
2957/// ::= .cfi_startproc
2958bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2959 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002960 getStreamer().EmitCFIStartProc();
2961 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002962}
2963
2964/// ParseDirectiveCFIEndProc
2965/// ::= .cfi_endproc
2966bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002967 getStreamer().EmitCFIEndProc();
2968 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002969}
2970
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002971/// ParseRegisterOrRegisterNumber - parse register name or number.
2972bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2973 SMLoc DirectiveLoc) {
2974 unsigned RegNo;
2975
Jim Grosbach6f888a82011-06-02 17:14:04 +00002976 if (getLexer().isNot(AsmToken::Integer)) {
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002977 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2978 DirectiveLoc))
2979 return true;
Evan Cheng0e6a0522011-07-18 20:57:22 +00002980 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002981 } else
2982 return getParser().ParseAbsoluteExpression(Register);
Jim Grosbachde2f5f42011-02-11 19:05:56 +00002983
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002984 return false;
2985}
2986
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002987/// ParseDirectiveCFIDefCfa
2988/// ::= .cfi_def_cfa register, offset
2989bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2990 SMLoc DirectiveLoc) {
2991 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002992 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002993 return true;
2994
2995 if (getLexer().isNot(AsmToken::Comma))
2996 return TokError("unexpected token in directive");
2997 Lex();
2998
2999 int64_t Offset = 0;
3000 if (getParser().ParseAbsoluteExpression(Offset))
3001 return true;
3002
Rafael Espindola066c2f42011-04-12 23:59:07 +00003003 getStreamer().EmitCFIDefCfa(Register, Offset);
3004 return false;
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003005}
3006
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003007/// ParseDirectiveCFIDefCfaOffset
3008/// ::= .cfi_def_cfa_offset offset
3009bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3010 SMLoc DirectiveLoc) {
3011 int64_t Offset = 0;
3012 if (getParser().ParseAbsoluteExpression(Offset))
3013 return true;
3014
Rafael Espindola066c2f42011-04-12 23:59:07 +00003015 getStreamer().EmitCFIDefCfaOffset(Offset);
3016 return false;
Rafael Espindola53abbe52011-04-11 20:29:16 +00003017}
3018
3019/// ParseDirectiveCFIAdjustCfaOffset
3020/// ::= .cfi_adjust_cfa_offset adjustment
3021bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3022 SMLoc DirectiveLoc) {
3023 int64_t Adjustment = 0;
3024 if (getParser().ParseAbsoluteExpression(Adjustment))
3025 return true;
3026
Rafael Espindola5d7dcd32011-04-12 18:53:30 +00003027 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3028 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003029}
3030
3031/// ParseDirectiveCFIDefCfaRegister
3032/// ::= .cfi_def_cfa_register register
3033bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3034 SMLoc DirectiveLoc) {
3035 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003036 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003037 return true;
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003038
Rafael Espindola066c2f42011-04-12 23:59:07 +00003039 getStreamer().EmitCFIDefCfaRegister(Register);
3040 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003041}
3042
3043/// ParseDirectiveCFIOffset
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003044/// ::= .cfi_offset register, offset
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003045bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3046 int64_t Register = 0;
3047 int64_t Offset = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003048
3049 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003050 return true;
3051
3052 if (getLexer().isNot(AsmToken::Comma))
3053 return TokError("unexpected token in directive");
3054 Lex();
3055
3056 if (getParser().ParseAbsoluteExpression(Offset))
3057 return true;
3058
Rafael Espindola066c2f42011-04-12 23:59:07 +00003059 getStreamer().EmitCFIOffset(Register, Offset);
3060 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003061}
3062
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003063/// ParseDirectiveCFIRelOffset
3064/// ::= .cfi_rel_offset register, offset
3065bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3066 SMLoc DirectiveLoc) {
3067 int64_t Register = 0;
3068
3069 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3070 return true;
3071
3072 if (getLexer().isNot(AsmToken::Comma))
3073 return TokError("unexpected token in directive");
3074 Lex();
3075
3076 int64_t Offset = 0;
3077 if (getParser().ParseAbsoluteExpression(Offset))
3078 return true;
3079
Rafael Espindola25f492e2011-04-12 16:12:03 +00003080 getStreamer().EmitCFIRelOffset(Register, Offset);
3081 return false;
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003082}
3083
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003084static bool isValidEncoding(int64_t Encoding) {
3085 if (Encoding & ~0xff)
3086 return false;
3087
3088 if (Encoding == dwarf::DW_EH_PE_omit)
3089 return true;
3090
3091 const unsigned Format = Encoding & 0xf;
3092 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3093 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3094 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3095 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3096 return false;
3097
Rafael Espindolacaf11582010-12-29 04:31:26 +00003098 const unsigned Application = Encoding & 0x70;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003099 if (Application != dwarf::DW_EH_PE_absptr &&
Rafael Espindolacaf11582010-12-29 04:31:26 +00003100 Application != dwarf::DW_EH_PE_pcrel)
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003101 return false;
3102
3103 return true;
3104}
3105
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003106/// ParseDirectiveCFIPersonalityOrLsda
3107/// ::= .cfi_personality encoding, [symbol_name]
3108/// ::= .cfi_lsda encoding, [symbol_name]
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003109bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003110 SMLoc DirectiveLoc) {
3111 int64_t Encoding = 0;
3112 if (getParser().ParseAbsoluteExpression(Encoding))
3113 return true;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003114 if (Encoding == dwarf::DW_EH_PE_omit)
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003115 return false;
3116
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003117 if (!isValidEncoding(Encoding))
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003118 return TokError("unsupported encoding.");
3119
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003120 if (getLexer().isNot(AsmToken::Comma))
3121 return TokError("unexpected token in directive");
3122 Lex();
3123
3124 StringRef Name;
3125 if (getParser().ParseIdentifier(Name))
3126 return TokError("expected identifier in directive");
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003127
3128 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3129
3130 if (IDVal == ".cfi_personality")
Rafael Espindola066c2f42011-04-12 23:59:07 +00003131 getStreamer().EmitCFIPersonality(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003132 else {
3133 assert(IDVal == ".cfi_lsda");
Rafael Espindola066c2f42011-04-12 23:59:07 +00003134 getStreamer().EmitCFILsda(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003135 }
Rafael Espindola066c2f42011-04-12 23:59:07 +00003136 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003137}
3138
Rafael Espindolafe024d02010-12-28 18:36:23 +00003139/// ParseDirectiveCFIRememberState
3140/// ::= .cfi_remember_state
3141bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3142 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003143 getStreamer().EmitCFIRememberState();
3144 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003145}
3146
3147/// ParseDirectiveCFIRestoreState
3148/// ::= .cfi_remember_state
3149bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3150 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003151 getStreamer().EmitCFIRestoreState();
3152 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003153}
3154
Rafael Espindolac5754392011-04-12 15:31:05 +00003155/// ParseDirectiveCFISameValue
3156/// ::= .cfi_same_value register
3157bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3158 SMLoc DirectiveLoc) {
3159 int64_t Register = 0;
3160
3161 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3162 return true;
3163
3164 getStreamer().EmitCFISameValue(Register);
3165
3166 return false;
3167}
3168
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003169/// ParseDirectiveCFIRestore
3170/// ::= .cfi_restore register
3171bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003172 SMLoc DirectiveLoc) {
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003173 int64_t Register = 0;
3174 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3175 return true;
3176
3177 getStreamer().EmitCFIRestore(Register);
3178
3179 return false;
3180}
3181
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003182/// ParseDirectiveCFIEscape
3183/// ::= .cfi_escape expression[,...]
3184bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003185 SMLoc DirectiveLoc) {
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003186 std::string Values;
3187 int64_t CurrValue;
3188 if (getParser().ParseAbsoluteExpression(CurrValue))
3189 return true;
3190
3191 Values.push_back((uint8_t)CurrValue);
3192
3193 while (getLexer().is(AsmToken::Comma)) {
3194 Lex();
3195
3196 if (getParser().ParseAbsoluteExpression(CurrValue))
3197 return true;
3198
3199 Values.push_back((uint8_t)CurrValue);
3200 }
3201
3202 getStreamer().EmitCFIEscape(Values);
3203 return false;
3204}
3205
Rafael Espindola16d7d432012-01-23 21:51:52 +00003206/// ParseDirectiveCFISignalFrame
3207/// ::= .cfi_signal_frame
3208bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3209 SMLoc DirectiveLoc) {
3210 if (getLexer().isNot(AsmToken::EndOfStatement))
3211 return Error(getLexer().getLoc(),
3212 "unexpected token in '" + Directive + "' directive");
3213
3214 getStreamer().EmitCFISignalFrame();
3215
3216 return false;
3217}
3218
Daniel Dunbar3c802de2010-07-18 18:38:02 +00003219/// ParseDirectiveMacrosOnOff
3220/// ::= .macros_on
3221/// ::= .macros_off
3222bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3223 SMLoc DirectiveLoc) {
3224 if (getLexer().isNot(AsmToken::EndOfStatement))
3225 return Error(getLexer().getLoc(),
3226 "unexpected token in '" + Directive + "' directive");
3227
3228 getParser().MacrosEnabled = Directive == ".macros_on";
3229
3230 return false;
3231}
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003232
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003233/// ParseDirectiveMacro
Rafael Espindola65366442011-06-05 02:43:45 +00003234/// ::= .macro name [parameters]
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003235bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3236 SMLoc DirectiveLoc) {
3237 StringRef Name;
3238 if (getParser().ParseIdentifier(Name))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003239 return TokError("expected identifier in '.macro' directive");
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003240
Rafael Espindola8a403d32012-08-08 14:51:03 +00003241 MacroParameters Parameters;
Preston Gurd7b6f2032012-09-19 20:36:12 +00003242 // Argument delimiter is initially unknown. It will be set by
3243 // ParseMacroArgument()
3244 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindola65366442011-06-05 02:43:45 +00003245 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Rafael Espindola7996d042012-08-21 16:06:48 +00003246 for (;;) {
3247 MacroParameter Parameter;
Preston Gurd6c9176a2012-09-19 20:29:04 +00003248 if (getParser().ParseIdentifier(Parameter.first))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003249 return TokError("expected identifier in '.macro' directive");
Preston Gurd6c9176a2012-09-19 20:29:04 +00003250
3251 if (getLexer().is(AsmToken::Equal)) {
3252 Lex();
Preston Gurd7b6f2032012-09-19 20:36:12 +00003253 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
Preston Gurd6c9176a2012-09-19 20:29:04 +00003254 return true;
3255 }
3256
Rafael Espindola65366442011-06-05 02:43:45 +00003257 Parameters.push_back(Parameter);
3258
Preston Gurd7b6f2032012-09-19 20:36:12 +00003259 if (getLexer().is(AsmToken::Comma))
3260 Lex();
3261 else if (getLexer().is(AsmToken::EndOfStatement))
Rafael Espindola65366442011-06-05 02:43:45 +00003262 break;
Rafael Espindola65366442011-06-05 02:43:45 +00003263 }
3264 }
3265
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003266 // Eat the end of statement.
3267 Lex();
3268
3269 AsmToken EndToken, StartToken = getTok();
3270
3271 // Lex the macro definition.
3272 for (;;) {
3273 // Check whether we have reached the end of the file.
3274 if (getLexer().is(AsmToken::Eof))
3275 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3276
3277 // Otherwise, check whether we have reach the .endmacro.
3278 if (getLexer().is(AsmToken::Identifier) &&
3279 (getTok().getIdentifier() == ".endm" ||
3280 getTok().getIdentifier() == ".endmacro")) {
3281 EndToken = getTok();
3282 Lex();
3283 if (getLexer().isNot(AsmToken::EndOfStatement))
3284 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3285 "' directive");
3286 break;
3287 }
3288
3289 // Otherwise, scan til the end of the statement.
3290 getParser().EatToEndOfStatement();
3291 }
3292
3293 if (getParser().MacroMap.lookup(Name)) {
3294 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3295 }
3296
3297 const char *BodyStart = StartToken.getLoc().getPointer();
3298 const char *BodyEnd = EndToken.getLoc().getPointer();
3299 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Rafael Espindola65366442011-06-05 02:43:45 +00003300 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003301 return false;
3302}
3303
3304/// ParseDirectiveEndMacro
3305/// ::= .endm
3306/// ::= .endmacro
3307bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
Rafael Espindola8a403d32012-08-08 14:51:03 +00003308 SMLoc DirectiveLoc) {
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003309 if (getLexer().isNot(AsmToken::EndOfStatement))
3310 return TokError("unexpected token in '" + Directive + "' directive");
3311
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00003312 // If we are inside a macro instantiation, terminate the current
3313 // instantiation.
3314 if (!getParser().ActiveMacros.empty()) {
3315 getParser().HandleMacroExit();
3316 return false;
3317 }
3318
3319 // Otherwise, this .endmacro is a stray entry in the file; well formed
3320 // .endmacro directives are handled during the macro definition parsing.
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003321 return TokError("unexpected '" + Directive + "' in file, "
3322 "no current macro definition");
3323}
3324
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +00003325/// ParseDirectivePurgeMacro
3326/// ::= .purgem
3327bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3328 SMLoc DirectiveLoc) {
3329 StringRef Name;
3330 if (getParser().ParseIdentifier(Name))
3331 return TokError("expected identifier in '.purgem' directive");
3332
3333 if (getLexer().isNot(AsmToken::EndOfStatement))
3334 return TokError("unexpected token in '.purgem' directive");
3335
3336 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3337 if (I == getParser().MacroMap.end())
3338 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3339
3340 // Undefine the macro.
3341 delete I->getValue();
3342 getParser().MacroMap.erase(I);
3343 return false;
3344}
3345
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003346bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
Rafael Espindola3ff57092010-11-02 17:22:24 +00003347 getParser().CheckForValidSection();
3348
3349 const MCExpr *Value;
3350
3351 if (getParser().ParseExpression(Value))
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003352 return true;
3353
3354 if (getLexer().isNot(AsmToken::EndOfStatement))
3355 return TokError("unexpected token in directive");
3356
3357 if (DirName[1] == 's')
Rafael Espindola3ff57092010-11-02 17:22:24 +00003358 getStreamer().EmitSLEB128Value(Value);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003359 else
Rafael Espindola3ff57092010-11-02 17:22:24 +00003360 getStreamer().EmitULEB128Value(Value);
3361
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003362 return false;
3363}
3364
Rafael Espindola761cb062012-06-03 23:57:14 +00003365Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003366 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003367
Rafael Espindola761cb062012-06-03 23:57:14 +00003368 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003369 for (;;) {
3370 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003371 if (getLexer().is(AsmToken::Eof)) {
3372 Error(DirectiveLoc, "no matching '.endr' in definition");
3373 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003374 }
3375
Rafael Espindola761cb062012-06-03 23:57:14 +00003376 if (Lexer.is(AsmToken::Identifier) &&
3377 (getTok().getIdentifier() == ".rept")) {
3378 ++NestLevel;
3379 }
3380
3381 // Otherwise, check whether we have reached the .endr.
3382 if (Lexer.is(AsmToken::Identifier) &&
3383 getTok().getIdentifier() == ".endr") {
3384 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003385 EndToken = getTok();
3386 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003387 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3388 TokError("unexpected token in '.endr' directive");
3389 return 0;
3390 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003391 break;
3392 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003393 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003394 }
3395
Rafael Espindola761cb062012-06-03 23:57:14 +00003396 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003397 EatToEndOfStatement();
3398 }
3399
3400 const char *BodyStart = StartToken.getLoc().getPointer();
3401 const char *BodyEnd = EndToken.getLoc().getPointer();
3402 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3403
Rafael Espindola761cb062012-06-03 23:57:14 +00003404 // We Are Anonymous.
3405 StringRef Name;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003406 MacroParameters Parameters;
Rafael Espindola761cb062012-06-03 23:57:14 +00003407 return new Macro(Name, Body, Parameters);
3408}
3409
3410void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3411 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003412 OS << ".endr\n";
3413
3414 MemoryBuffer *Instantiation =
3415 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3416
Rafael Espindola761cb062012-06-03 23:57:14 +00003417 // Create the macro instantiation object and add to the current macro
3418 // instantiation stack.
3419 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3420 getTok().getLoc(),
3421 Instantiation);
3422 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003423
Rafael Espindola761cb062012-06-03 23:57:14 +00003424 // Jump to the macro instantiation and prime the lexer.
3425 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3426 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3427 Lex();
3428}
3429
3430bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3431 int64_t Count;
3432 if (ParseAbsoluteExpression(Count))
3433 return TokError("unexpected token in '.rept' directive");
3434
3435 if (Count < 0)
3436 return TokError("Count is negative");
3437
3438 if (Lexer.isNot(AsmToken::EndOfStatement))
3439 return TokError("unexpected token in '.rept' directive");
3440
3441 // Eat the end of statement.
3442 Lex();
3443
3444 // Lex the rept definition.
3445 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3446 if (!M)
3447 return true;
3448
3449 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3450 // to hold the macro body with substitutions.
3451 SmallString<256> Buf;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003452 MacroParameters Parameters;
3453 MacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003454 raw_svector_ostream OS(Buf);
3455 while (Count--) {
3456 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3457 return true;
3458 }
3459 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003460
3461 return false;
3462}
3463
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003464/// ParseDirectiveIrp
3465/// ::= .irp symbol,values
3466bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003467 MacroParameters Parameters;
3468 MacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003469
Preston Gurd6c9176a2012-09-19 20:29:04 +00003470 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003471 return TokError("expected identifier in '.irp' directive");
3472
3473 Parameters.push_back(Parameter);
3474
3475 if (Lexer.isNot(AsmToken::Comma))
3476 return TokError("expected comma in '.irp' directive");
3477
3478 Lex();
3479
Rafael Espindola8a403d32012-08-08 14:51:03 +00003480 MacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003481 if (ParseMacroArguments(0, A))
3482 return true;
3483
3484 // Eat the end of statement.
3485 Lex();
3486
3487 // Lex the irp definition.
3488 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3489 if (!M)
3490 return true;
3491
3492 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3493 // to hold the macro body with substitutions.
3494 SmallString<256> Buf;
3495 raw_svector_ostream OS(Buf);
3496
Rafael Espindola7996d042012-08-21 16:06:48 +00003497 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3498 MacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003499 Args.push_back(*i);
3500
3501 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3502 return true;
3503 }
3504
3505 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3506
3507 return false;
3508}
3509
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003510/// ParseDirectiveIrpc
3511/// ::= .irpc symbol,values
3512bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003513 MacroParameters Parameters;
3514 MacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003515
Preston Gurd6c9176a2012-09-19 20:29:04 +00003516 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003517 return TokError("expected identifier in '.irpc' directive");
3518
3519 Parameters.push_back(Parameter);
3520
3521 if (Lexer.isNot(AsmToken::Comma))
3522 return TokError("expected comma in '.irpc' directive");
3523
3524 Lex();
3525
Rafael Espindola8a403d32012-08-08 14:51:03 +00003526 MacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003527 if (ParseMacroArguments(0, A))
3528 return true;
3529
3530 if (A.size() != 1 || A.front().size() != 1)
3531 return TokError("unexpected token in '.irpc' directive");
3532
3533 // Eat the end of statement.
3534 Lex();
3535
3536 // Lex the irpc definition.
3537 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3538 if (!M)
3539 return true;
3540
3541 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3542 // to hold the macro body with substitutions.
3543 SmallString<256> Buf;
3544 raw_svector_ostream OS(Buf);
3545
3546 StringRef Values = A.front().front().getString();
3547 std::size_t I, End = Values.size();
3548 for (I = 0; I < End; ++I) {
3549 MacroArgument Arg;
3550 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3551
Rafael Espindola8a403d32012-08-08 14:51:03 +00003552 MacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003553 Args.push_back(Arg);
3554
3555 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3556 return true;
3557 }
3558
3559 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3560
3561 return false;
3562}
3563
Rafael Espindola761cb062012-06-03 23:57:14 +00003564bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3565 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003566 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003567
3568 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003569 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003570 assert(getLexer().is(AsmToken::EndOfStatement));
3571
Rafael Espindola761cb062012-06-03 23:57:14 +00003572 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003573 return false;
3574}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003575
Chad Rosierb1f8c132012-10-18 15:49:34 +00003576namespace {
3577enum AsmOpRewriteKind {
3578 AOK_Imm,
3579 AOK_Input,
3580 AOK_Output
3581};
3582
3583struct AsmOpRewrite {
3584 AsmOpRewriteKind Kind;
3585 SMLoc Loc;
3586 unsigned Len;
3587
3588public:
3589 AsmOpRewrite(AsmOpRewriteKind kind, SMLoc loc, unsigned len)
3590 : Kind(kind), Loc(loc), Len(len) { }
3591};
3592}
3593
3594bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3595 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003596 SmallVectorImpl<void *> &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003597 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003598 SmallVectorImpl<std::string> &Clobbers,
3599 const MCInstrInfo *MII,
3600 const MCInstPrinter *IP,
3601 MCAsmParserSemaCallback &SI) {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003602 SmallVector<void*, 4> InputDecls;
3603 SmallVector<void*, 4> OutputDecls;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003604 SmallVector<std::string, 4> InputConstraints;
3605 SmallVector<std::string, 4> OutputConstraints;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003606 std::set<std::string> ClobberRegs;
3607
3608 SmallVector<struct AsmOpRewrite, 4> AsmStrRewrites;
3609
3610 // Prime the lexer.
3611 Lex();
3612
3613 // While we have input, parse each statement.
3614 unsigned InputIdx = 0;
3615 unsigned OutputIdx = 0;
3616 while (getLexer().isNot(AsmToken::Eof)) {
3617 if (ParseStatement()) return true;
3618
3619 if (isInstruction()) {
3620 const MCInstrDesc &Desc = MII->get(getOpcode());
3621
3622 // Build the list of clobbers, outputs and inputs.
3623 for (unsigned i = 1, e = ParsedOperands.size(); i != e; ++i) {
3624 MCParsedAsmOperand *Operand = ParsedOperands[i];
3625
3626 // Immediate.
3627 if (Operand->isImm()) {
3628 AsmStrRewrites.push_back(AsmOpRewrite(AOK_Imm,
3629 Operand->getStartLoc(),
3630 Operand->getNameLen()));
3631 continue;
3632 }
3633
3634 // Register operand.
3635 if (Operand->isReg()) {
3636 unsigned NumDefs = Desc.getNumDefs();
3637 // Clobber.
3638 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3639 std::string Reg;
3640 raw_string_ostream OS(Reg);
3641 IP->printRegName(OS, Operand->getReg());
3642 ClobberRegs.insert(StringRef(OS.str()));
3643 }
3644 continue;
3645 }
3646
3647 // Expr/Input or Output.
Chad Rosier32989592012-10-18 20:27:15 +00003648 unsigned Size;
3649 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3650 Size);
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003651 if (OpDecl) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003652 bool isOutput = (i == 1) && Desc.mayStore();
3653 if (isOutput) {
3654 std::string Constraint = "=";
3655 ++InputIdx;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003656 OutputDecls.push_back(OpDecl);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003657 Constraint += Operand->getConstraint().str();
3658 OutputConstraints.push_back(Constraint);
3659 AsmStrRewrites.push_back(AsmOpRewrite(AOK_Output,
3660 Operand->getStartLoc(),
3661 Operand->getNameLen()));
3662 } else {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003663 InputDecls.push_back(OpDecl);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003664 InputConstraints.push_back(Operand->getConstraint().str());
3665 AsmStrRewrites.push_back(AsmOpRewrite(AOK_Input,
3666 Operand->getStartLoc(),
3667 Operand->getNameLen()));
3668 }
3669 }
3670 }
3671 // Free any parsed operands.
3672 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
3673 delete ParsedOperands[i];
3674 ParsedOperands.clear();
3675 }
3676 }
3677
3678 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003679 NumOutputs = OutputDecls.size();
3680 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00003681
3682 // Set the unique clobbers.
3683 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3684 E = ClobberRegs.end(); I != E; ++I)
3685 Clobbers.push_back(*I);
3686
3687 // Merge the various outputs and inputs. Output are expected first.
3688 if (NumOutputs || NumInputs) {
3689 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003690 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003691 Constraints.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003692 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003693 OpDecls[i] = OutputDecls[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003694 Constraints[i] = OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003695 }
3696 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003697 OpDecls[j] = InputDecls[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003698 Constraints[j] = InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003699 }
3700 }
3701
3702 // Build the IR assembly string.
3703 std::string AsmStringIR;
3704 raw_string_ostream OS(AsmStringIR);
3705 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
3706 for (SmallVectorImpl<struct AsmOpRewrite>::iterator
3707 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3708 const char *Loc = (*I).Loc.getPointer();
3709
3710 // Emit everything up to the immediate/expression.
3711 OS << StringRef(Start, Loc - Start);
3712
3713 // Rewrite expressions in $N notation.
3714 switch ((*I).Kind) {
3715 case AOK_Imm:
3716 OS << Twine("$$") + StringRef(Loc, (*I).Len);
3717 break;
3718 case AOK_Input:
3719 OS << '$';
3720 OS << InputIdx++;
3721 break;
3722 case AOK_Output:
3723 OS << '$';
3724 OS << OutputIdx++;
3725 break;
3726 }
3727
3728 // Skip the original expression.
3729 Start = Loc + (*I).Len;
3730 }
3731
3732 // Emit the remainder of the asm string.
3733 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
3734 if (Start != AsmEnd)
3735 OS << StringRef(Start, AsmEnd - Start);
3736
3737 AsmString = OS.str();
3738 return false;
3739}
3740
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003741/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003742MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003743 MCContext &C, MCStreamer &Out,
3744 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003745 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003746}