blob: 0e8fe6d5e94530054df4028a5ccad0b9e4b5ebd3 [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
Daniel Dunbar81ea00f2010-07-12 17:54:38 +000049namespace {
50
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000051/// \brief Helper class for tracking macro definitions.
Rafael Espindola28c1f6662012-06-03 22:41:23 +000052typedef std::vector<AsmToken> MacroArgument;
Rafael Espindola8a403d32012-08-08 14:51:03 +000053typedef std::vector<MacroArgument> MacroArguments;
Preston Gurd6c9176a2012-09-19 20:29:04 +000054typedef std::pair<StringRef, MacroArgument> MacroParameter;
Rafael Espindola8a403d32012-08-08 14:51:03 +000055typedef std::vector<MacroParameter> MacroParameters;
Rafael Espindola28c1f6662012-06-03 22:41:23 +000056
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000057struct Macro {
58 StringRef Name;
59 StringRef Body;
Rafael Espindola8a403d32012-08-08 14:51:03 +000060 MacroParameters Parameters;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000061
62public:
Rafael Espindola8a403d32012-08-08 14:51:03 +000063 Macro(StringRef N, StringRef B, const MacroParameters &P) :
Rafael Espindola65366442011-06-05 02:43:45 +000064 Name(N), Body(B), Parameters(P) {}
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000065};
66
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000067/// \brief Helper class for storing information about an active macro
68/// instantiation.
69struct MacroInstantiation {
70 /// The macro being instantiated.
71 const Macro *TheMacro;
72
73 /// The macro instantiation with substitutions.
74 MemoryBuffer *Instantiation;
75
76 /// The location of the instantiation.
77 SMLoc InstantiationLoc;
78
79 /// The location where parsing should resume upon instantiation completion.
80 SMLoc ExitLoc;
81
82public:
Daniel Dunbar7a570d02010-07-18 19:00:10 +000083 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000084 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000085};
86
Daniel Dunbaraef87e32010-07-18 18:31:38 +000087/// \brief The concrete assembly parser instance.
88class AsmParser : public MCAsmParser {
Daniel Dunbar3c802de2010-07-18 18:38:02 +000089 friend class GenericAsmParser;
90
Craig Topper85aadc02012-09-15 16:23:52 +000091 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
92 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
Daniel Dunbaraef87e32010-07-18 18:31:38 +000093private:
94 AsmLexer Lexer;
95 MCContext &Ctx;
96 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +000097 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +000098 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +000099 SourceMgr::DiagHandlerTy SavedDiagHandler;
100 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000101 MCAsmParserExtension *GenericParser;
102 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000103
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000104 /// This is the current buffer index we're lexing from as managed by the
105 /// SourceMgr object.
106 int CurBuffer;
107
108 AsmCond TheCondState;
109 std::vector<AsmCond> TheCondStack;
110
111 /// DirectiveMap - This is a table handlers for directives. Each handler is
112 /// invoked after the directive identifier is read and is responsible for
113 /// parsing and validating the rest of the directive. The handler is passed
114 /// in the directive name and the location of the directive keyword.
115 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000116
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000117 /// MacroMap - Map of currently defined macros.
118 StringMap<Macro*> MacroMap;
119
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000120 /// ActiveMacros - Stack of active macro instantiations.
121 std::vector<MacroInstantiation*> ActiveMacros;
122
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000123 /// Boolean tracking whether macro substitution is enabled.
124 unsigned MacrosEnabled : 1;
125
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000126 /// Flag tracking whether any errors have been encountered.
127 unsigned HadError : 1;
128
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000129 /// The values from the last parsed cpp hash file line comment if any.
130 StringRef CppHashFilename;
131 int64_t CppHashLineNumber;
132 SMLoc CppHashLoc;
133
Devang Patel0db58bf2012-01-31 18:14:05 +0000134 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
135 unsigned AssemblerDialect;
136
Preston Gurd7b6f2032012-09-19 20:36:12 +0000137 /// IsDarwin - is Darwin compatibility enabled?
138 bool IsDarwin;
139
Chad Rosier8f138d12012-10-15 17:19:13 +0000140 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000141 bool ParsingInlineAsm;
142
Chad Rosier8f138d12012-10-15 17:19:13 +0000143 /// ParsedOperands - The parsed operands from the last parsed statement.
144 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
145
Chad Rosierb1f8c132012-10-18 15:49:34 +0000146 /// Opcode - The opcode from the last parsed instruction. This is MS-style
147 /// inline asm specific.
Chad Rosier8f138d12012-10-15 17:19:13 +0000148 unsigned Opcode;
149
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000150public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000151 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000152 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000153 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000154
155 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
156
Craig Topper345d16d2012-08-29 05:48:09 +0000157 virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
158 StringRef Directive,
159 DirectiveHandler Handler) {
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000160 DirectiveMap[Directive] = std::make_pair(Object, Handler);
161 }
162
163public:
164 /// @name MCAsmParser Interface
165 /// {
166
167 virtual SourceMgr &getSourceManager() { return SrcMgr; }
168 virtual MCAsmLexer &getLexer() { return Lexer; }
169 virtual MCContext &getContext() { return Ctx; }
170 virtual MCStreamer &getStreamer() { return Out; }
Devang Patel0db58bf2012-01-31 18:14:05 +0000171 virtual unsigned getAssemblerDialect() {
172 if (AssemblerDialect == ~0U)
173 return MAI.getAssemblerDialect();
174 else
175 return AssemblerDialect;
176 }
177 virtual void setAssemblerDialect(unsigned i) {
178 AssemblerDialect = i;
179 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000180
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000181 virtual bool Warning(SMLoc L, const Twine &Msg,
182 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
183 virtual bool Error(SMLoc L, const Twine &Msg,
184 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000185
Craig Topper345d16d2012-08-29 05:48:09 +0000186 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000187
Chad Rosier84125ca2012-10-13 00:26:04 +0000188 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosierc5ac87d2012-10-16 20:16:20 +0000189 bool isParsingInlineAsm() { return ParsingInlineAsm; }
Chad Rosierb1f8c132012-10-18 15:49:34 +0000190
191 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
192 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosierc8dd27e2012-10-18 19:39:30 +0000193 SmallVectorImpl<void *> &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000194 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000195 SmallVectorImpl<std::string> &Clobbers,
196 const MCInstrInfo *MII,
197 const MCInstPrinter *IP,
198 MCAsmParserSemaCallback &SI);
Chad Rosier84125ca2012-10-13 00:26:04 +0000199
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000200 bool ParseExpression(const MCExpr *&Res);
201 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
202 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
203 virtual bool ParseAbsoluteExpression(int64_t &Res);
204
205 /// }
206
207private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000208 void CheckForValidSection();
209
Chad Rosierb1f8c132012-10-18 15:49:34 +0000210 bool ParseStatement();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000211 void EatToEndOfLine();
212 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000213
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000214 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
Rafael Espindola761cb062012-06-03 23:57:14 +0000215 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +0000216 const MacroParameters &Parameters,
217 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000218 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000219 void HandleMacroExit();
220
221 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000222 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000223 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
224 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000225 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000226 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000227
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000228 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
229 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000230 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
231 /// This returns true on failure.
232 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000233
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000234 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000235 /// current token is not set; clients should ensure Lex() is called
236 /// subsequently.
237 void JumpToLoc(SMLoc Loc);
238
Craig Topper345d16d2012-08-29 05:48:09 +0000239 virtual void EatToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000240
Preston Gurd7b6f2032012-09-19 20:36:12 +0000241 bool ParseMacroArgument(MacroArgument &MA,
242 AsmToken::TokenKind &ArgumentDelimiter);
Rafael Espindola8a403d32012-08-08 14:51:03 +0000243 bool ParseMacroArguments(const Macro *M, MacroArguments &A);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000244
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000245 /// \brief Parse up to the end of statement and a return the contents from the
246 /// current token until the end of the statement; the current token on exit
247 /// will be either the EndOfStatement or EOF.
Craig Topper345d16d2012-08-29 05:48:09 +0000248 virtual StringRef ParseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000249
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000250 /// \brief Parse until the end of a statement or a comma is encountered,
251 /// return the contents from the current token up to the end or comma.
252 StringRef ParseStringToComma();
253
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000254 bool ParseAssignment(StringRef Name, bool allow_redef,
255 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000256
257 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
258 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
259 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000260 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000261
262 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000263 /// and set \p Res to the identifier contents.
Craig Topper345d16d2012-08-29 05:48:09 +0000264 virtual bool ParseIdentifier(StringRef &Res);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000265
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000266 // Directive Parsing.
Rafael Espindola787c3372010-10-28 20:02:27 +0000267
268 // ".ascii", ".asciiz", ".string"
269 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000270 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000271 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000272 bool ParseDirectiveFill(); // ".fill"
273 bool ParseDirectiveSpace(); // ".space"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000274 bool ParseDirectiveZero(); // ".zero"
Nico Weber4c4c7322011-01-28 03:04:41 +0000275 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000276 bool ParseDirectiveOrg(); // ".org"
277 // ".align{,32}", ".p2align{,w,l}"
278 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
279
280 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
281 /// accepts a single symbol (which should be a label or an external).
282 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000283
284 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
285
286 bool ParseDirectiveAbort(); // ".abort"
287 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000288 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000289
290 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000291 // ".ifb" or ".ifnb", depending on ExpectBlank.
292 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000293 // ".ifc" or ".ifnc", depending on ExpectEqual.
294 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000295 // ".ifdef" or ".ifndef", depending on expect_defined
296 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000297 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
298 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
299 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
300
301 /// ParseEscapedString - Parse the current token as a string which may include
302 /// escaped characters and return the string contents.
303 bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000304
305 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
306 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000307
Rafael Espindola761cb062012-06-03 23:57:14 +0000308 // Macro-like directives
309 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
310 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
311 raw_svector_ostream &OS);
312 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000313 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000314 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000315 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000316
317 // MS-style inline assembly parsing.
318 bool isInstruction() { return Opcode != (unsigned)~0x0; }
319 unsigned getOpcode() { return Opcode; }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000320};
321
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000322/// \brief Generic implementations of directive handling, etc. which is shared
323/// (or the default, at least) for all assembler parser.
324class GenericAsmParser : public MCAsmParserExtension {
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000325 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
326 void AddDirectiveHandler(StringRef Directive) {
327 getParser().AddDirectiveHandler(this, Directive,
328 HandleDirective<GenericAsmParser, Handler>);
329 }
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000330public:
331 GenericAsmParser() {}
332
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000333 AsmParser &getParser() {
334 return (AsmParser&) this->MCAsmParserExtension::getParser();
335 }
336
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000337 virtual void Initialize(MCAsmParser &Parser) {
338 // Call the base implementation.
339 this->MCAsmParserExtension::Initialize(Parser);
340
341 // Debugging directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000342 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
343 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
344 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
Daniel Dunbar138abae2010-10-16 04:56:42 +0000345 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000346
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000347 // CFI directives.
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000348 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
349 ".cfi_sections");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000350 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
351 ".cfi_startproc");
352 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
353 ".cfi_endproc");
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000354 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
355 ".cfi_def_cfa");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000356 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
357 ".cfi_def_cfa_offset");
Rafael Espindola53abbe52011-04-11 20:29:16 +0000358 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
359 ".cfi_adjust_cfa_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000360 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
361 ".cfi_def_cfa_register");
362 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
363 ".cfi_offset");
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000364 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
365 ".cfi_rel_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000366 AddDirectiveHandler<
367 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
368 AddDirectiveHandler<
369 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
Rafael Espindolafe024d02010-12-28 18:36:23 +0000370 AddDirectiveHandler<
371 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
372 AddDirectiveHandler<
373 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
Rafael Espindolac5754392011-04-12 15:31:05 +0000374 AddDirectiveHandler<
375 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000376 AddDirectiveHandler<
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000377 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
378 AddDirectiveHandler<
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000379 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
Rafael Espindola16d7d432012-01-23 21:51:52 +0000380 AddDirectiveHandler<
381 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000382
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000383 // Macro directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000384 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
385 ".macros_on");
386 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
387 ".macros_off");
388 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
389 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
390 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000391 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000392
393 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
394 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000395 }
396
Roman Divacky54b0f4f2011-01-27 17:16:37 +0000397 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
398
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000399 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
400 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
401 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar138abae2010-10-16 04:56:42 +0000402 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000403 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000404 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
405 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000406 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000407 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola53abbe52011-04-11 20:29:16 +0000408 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000409 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
410 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000411 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000412 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
Rafael Espindolafe024d02010-12-28 18:36:23 +0000413 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
414 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac5754392011-04-12 15:31:05 +0000415 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000416 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000417 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
Rafael Espindola16d7d432012-01-23 21:51:52 +0000418 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000419
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000420 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000421 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
422 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000423 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000424
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000425 bool ParseDirectiveLEB128(StringRef, SMLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000426};
427
428}
429
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000430namespace llvm {
431
432extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000433extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000434extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000435
436}
437
Chris Lattneraaec2052010-01-19 19:46:13 +0000438enum { DEFAULT_ADDRSPACE = 0 };
439
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000440AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000441 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000442 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Rafael Espindola5d7dcd32011-04-12 18:53:30 +0000443 GenericParser(new GenericAsmParser), PlatformParser(0),
Preston Gurd7b6f2032012-09-19 20:36:12 +0000444 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
Chad Rosier8f138d12012-10-15 17:19:13 +0000445 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false),
Chad Rosier127f5ed2012-10-15 19:08:18 +0000446 Opcode(~0x0) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000447 // Save the old handler.
448 SavedDiagHandler = SrcMgr.getDiagHandler();
449 SavedDiagContext = SrcMgr.getDiagContext();
450 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000451 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000452 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000453
454 // Initialize the generic parser.
455 GenericParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000456
457 // Initialize the platform / file format parser.
458 //
459 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
460 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000461 if (_MAI.hasMicrosoftFastStdCallMangling()) {
462 PlatformParser = createCOFFAsmParser();
463 PlatformParser->Initialize(*this);
464 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000465 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000466 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000467 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000468 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000469 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000470 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000471 }
Chris Lattnerebb89b42009-09-27 21:16:52 +0000472}
473
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000474AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000475 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
476
477 // Destroy any macros.
478 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
479 ie = MacroMap.end(); it != ie; ++it)
480 delete it->getValue();
481
Daniel Dunbare4749702010-07-12 18:12:02 +0000482 delete PlatformParser;
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000483 delete GenericParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000484}
485
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000486void AsmParser::PrintMacroInstantiations() {
487 // Print the active macro instantiation stack.
488 for (std::vector<MacroInstantiation*>::const_reverse_iterator
489 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000490 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
491 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000492}
493
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000494bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000495 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000496 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000497 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000498 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000499 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000500}
501
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000502bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000503 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000504 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000505 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000506 return true;
507}
508
Sean Callananfd0b0282010-01-21 00:19:58 +0000509bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000510 std::string IncludedFile;
511 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000512 if (NewBuf == -1)
513 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000514
Sean Callananfd0b0282010-01-21 00:19:58 +0000515 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000516
Sean Callananfd0b0282010-01-21 00:19:58 +0000517 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000518
Sean Callananfd0b0282010-01-21 00:19:58 +0000519 return false;
520}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000521
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000522/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000523/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000524/// returns true on failure.
525bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
526 std::string IncludedFile;
527 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
528 if (NewBuf == -1)
529 return true;
530
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000531 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000532 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
533 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000534 return false;
535}
536
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000537void AsmParser::JumpToLoc(SMLoc Loc) {
538 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
539 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
540}
541
Sean Callananfd0b0282010-01-21 00:19:58 +0000542const AsmToken &AsmParser::Lex() {
543 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000544
Sean Callananfd0b0282010-01-21 00:19:58 +0000545 if (tok->is(AsmToken::Eof)) {
546 // If this is the end of an included file, pop the parent file off the
547 // include stack.
548 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
549 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000550 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000551 tok = &Lexer.Lex();
552 }
553 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000554
Sean Callananfd0b0282010-01-21 00:19:58 +0000555 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000556 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000557
Sean Callananfd0b0282010-01-21 00:19:58 +0000558 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000559}
560
Chris Lattner79180e22010-04-05 23:15:42 +0000561bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000562 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000563 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000564 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000565
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000566 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000567 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000568
569 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000570 AsmCond StartingCondState = TheCondState;
571
Kevin Enderby613b7572011-11-01 22:27:22 +0000572 // If we are generating dwarf for assembly source files save the initial text
573 // section and generate a .file directive.
574 if (getContext().getGenDwarfForAssembly()) {
575 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000576 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
577 getStreamer().EmitLabel(SectionStartSym);
578 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000579 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
580 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
581 }
582
Chris Lattnerb717fb02009-07-02 21:53:43 +0000583 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000584 while (Lexer.isNot(AsmToken::Eof)) {
Chris Lattnerb717fb02009-07-02 21:53:43 +0000585 if (!ParseStatement()) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000586
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000587 // We had an error, validate that one was emitted and recover by skipping to
588 // the next line.
589 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000590 EatToEndOfStatement();
591 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000592
593 if (TheCondState.TheCond != StartingCondState.TheCond ||
594 TheCondState.Ignore != StartingCondState.Ignore)
595 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000596
597 // Check to see there are no empty DwarfFile slots.
598 const std::vector<MCDwarfFile *> &MCDwarfFiles =
599 getContext().getMCDwarfFiles();
600 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000601 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000602 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000603 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000604
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000605 // Check to see that all assembler local symbols were actually defined.
606 // Targets that don't do subsections via symbols may not want this, though,
607 // so conservatively exclude them. Only do this if we're finalizing, though,
608 // as otherwise we won't necessarilly have seen everything yet.
609 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
610 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
611 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
612 e = Symbols.end();
613 i != e; ++i) {
614 MCSymbol *Sym = i->getValue();
615 // Variable symbols may not be marked as defined, so check those
616 // explicitly. If we know it's a variable, we have a definition for
617 // the purposes of this check.
618 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
619 // FIXME: We would really like to refer back to where the symbol was
620 // first referenced for a source location. We need to add something
621 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000622 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
623 "assembler local symbol '" + Sym->getName() +
624 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000625 }
626 }
627
628
Chris Lattner79180e22010-04-05 23:15:42 +0000629 // Finalize the output stream if there are no errors and if the client wants
630 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000631 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000632 Out.Finish();
633
Chris Lattnerb717fb02009-07-02 21:53:43 +0000634 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000635}
636
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000637void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000638 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000639 TokError("expected section directive before assembly directive");
640 Out.SwitchSection(Ctx.getMachOSection(
641 "__TEXT", "__text",
642 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
643 0, SectionKind::getText()));
644 }
645}
646
Chris Lattner2cf5f142009-06-22 01:29:09 +0000647/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
648void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000649 while (Lexer.isNot(AsmToken::EndOfStatement) &&
650 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000651 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000652
Chris Lattner2cf5f142009-06-22 01:29:09 +0000653 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000654 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000655 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000656}
657
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000658StringRef AsmParser::ParseStringToEndOfStatement() {
659 const char *Start = getTok().getLoc().getPointer();
660
661 while (Lexer.isNot(AsmToken::EndOfStatement) &&
662 Lexer.isNot(AsmToken::Eof))
663 Lex();
664
665 const char *End = getTok().getLoc().getPointer();
666 return StringRef(Start, End - Start);
667}
Chris Lattnerc4193832009-06-22 05:51:26 +0000668
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000669StringRef AsmParser::ParseStringToComma() {
670 const char *Start = getTok().getLoc().getPointer();
671
672 while (Lexer.isNot(AsmToken::EndOfStatement) &&
673 Lexer.isNot(AsmToken::Comma) &&
674 Lexer.isNot(AsmToken::Eof))
675 Lex();
676
677 const char *End = getTok().getLoc().getPointer();
678 return StringRef(Start, End - Start);
679}
680
Chris Lattner74ec1a32009-06-22 06:32:03 +0000681/// ParseParenExpr - Parse a paren expression and return it.
682/// NOTE: This assumes the leading '(' has already been consumed.
683///
684/// parenexpr ::= expr)
685///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000686bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000687 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000688 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000689 return TokError("expected ')' in parentheses expression");
Chris Lattnerb4307b32010-01-15 19:28:38 +0000690 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000691 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000692 return false;
693}
Chris Lattnerc4193832009-06-22 05:51:26 +0000694
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000695/// ParseBracketExpr - Parse a bracket expression and return it.
696/// NOTE: This assumes the leading '[' has already been consumed.
697///
698/// bracketexpr ::= expr]
699///
700bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
701 if (ParseExpression(Res)) return true;
702 if (Lexer.isNot(AsmToken::RBrac))
703 return TokError("expected ']' in brackets expression");
704 EndLoc = Lexer.getLoc();
705 Lex();
706 return false;
707}
708
Chris Lattner74ec1a32009-06-22 06:32:03 +0000709/// ParsePrimaryExpr - Parse a primary expression and return it.
710/// primaryexpr ::= (parenexpr
711/// primaryexpr ::= symbol
712/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000713/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000714/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000715bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000716 switch (Lexer.getKind()) {
717 default:
718 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000719 // If we have an error assume that we've already handled it.
720 case AsmToken::Error:
721 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000722 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000723 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000724 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000725 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000726 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000727 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000728 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000729 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000730 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000731 EndLoc = Lexer.getLoc();
732
733 StringRef Identifier;
734 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000735 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000736
Daniel Dunbarfffff912009-10-16 01:34:54 +0000737 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000738 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000739 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000740
741 // Lookup the symbol variant if used.
742 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000743 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000744 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000745 if (Variant == MCSymbolRefExpr::VK_Invalid) {
746 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000747 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000748 }
749 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000750
Daniel Dunbarfffff912009-10-16 01:34:54 +0000751 // If this is an absolute variable reference, substitute it now to preserve
752 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000753 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000754 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000755 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000756
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000757 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000758 return false;
759 }
760
761 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000762 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000763 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000764 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000765 case AsmToken::Integer: {
766 SMLoc Loc = getTok().getLoc();
767 int64_t IntVal = getTok().getIntVal();
768 Res = MCConstantExpr::Create(IntVal, getContext());
Chris Lattnerb4307b32010-01-15 19:28:38 +0000769 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000770 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000771 // Look for 'b' or 'f' following an Integer as a directional label
772 if (Lexer.getKind() == AsmToken::Identifier) {
773 StringRef IDVal = getTok().getString();
774 if (IDVal == "f" || IDVal == "b"){
775 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
776 IDVal == "f" ? 1 : 0);
777 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
778 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000779 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000780 return Error(Loc, "invalid reference to undefined symbol");
781 EndLoc = Lexer.getLoc();
782 Lex(); // Eat identifier.
783 }
784 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000785 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000786 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000787 case AsmToken::Real: {
788 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000789 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000790 Res = MCConstantExpr::Create(IntVal, getContext());
791 Lex(); // Eat token.
792 return false;
793 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000794 case AsmToken::Dot: {
795 // This is a '.' reference, which references the current PC. Emit a
796 // temporary label to the streamer and refer to it.
797 MCSymbol *Sym = Ctx.CreateTempSymbol();
798 Out.EmitLabel(Sym);
799 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
800 EndLoc = Lexer.getLoc();
801 Lex(); // Eat identifier.
802 return false;
803 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000804 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000805 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000806 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000807 case AsmToken::LBrac:
808 if (!PlatformParser->HasBracketExpressions())
809 return TokError("brackets expression not supported on this target");
810 Lex(); // Eat the '['.
811 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000812 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000813 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000814 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000815 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000816 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000817 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000818 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000819 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000820 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000821 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000822 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000823 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000824 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000825 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000826 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000827 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000828 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000829 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000830 }
831}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000832
Chris Lattnerb4307b32010-01-15 19:28:38 +0000833bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000834 SMLoc EndLoc;
835 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000836}
837
Daniel Dunbarcceba832010-09-17 02:47:07 +0000838const MCExpr *
839AsmParser::ApplyModifierToExpr(const MCExpr *E,
840 MCSymbolRefExpr::VariantKind Variant) {
841 // Recurse over the given expression, rebuilding it to apply the given variant
842 // if there is exactly one symbol.
843 switch (E->getKind()) {
844 case MCExpr::Target:
845 case MCExpr::Constant:
846 return 0;
847
848 case MCExpr::SymbolRef: {
849 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
850
851 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
852 TokError("invalid variant on expression '" +
853 getTok().getIdentifier() + "' (already modified)");
854 return E;
855 }
856
857 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
858 }
859
860 case MCExpr::Unary: {
861 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
862 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
863 if (!Sub)
864 return 0;
865 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
866 }
867
868 case MCExpr::Binary: {
869 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
870 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
871 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
872
873 if (!LHS && !RHS)
874 return 0;
875
876 if (!LHS) LHS = BE->getLHS();
877 if (!RHS) RHS = BE->getRHS();
878
879 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
880 }
881 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000882
Craig Topper85814382012-02-07 05:05:23 +0000883 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000884}
885
Chris Lattner74ec1a32009-06-22 06:32:03 +0000886/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000887///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000888/// expr ::= expr &&,|| expr -> lowest.
889/// expr ::= expr |,^,&,! expr
890/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
891/// expr ::= expr <<,>> expr
892/// expr ::= expr +,- expr
893/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000894/// expr ::= primaryexpr
895///
Chris Lattner54482b42010-01-15 19:39:23 +0000896bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000897 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000898 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000899 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
900 return true;
901
Daniel Dunbarcceba832010-09-17 02:47:07 +0000902 // As a special case, we support 'a op b @ modifier' by rewriting the
903 // expression to include the modifier. This is inefficient, but in general we
904 // expect users to use 'a@modifier op b'.
905 if (Lexer.getKind() == AsmToken::At) {
906 Lex();
907
908 if (Lexer.isNot(AsmToken::Identifier))
909 return TokError("unexpected symbol modifier following '@'");
910
911 MCSymbolRefExpr::VariantKind Variant =
912 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
913 if (Variant == MCSymbolRefExpr::VK_Invalid)
914 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
915
916 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
917 if (!ModifiedRes) {
918 return TokError("invalid modifier '" + getTok().getIdentifier() +
919 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000920 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000921
Daniel Dunbarcceba832010-09-17 02:47:07 +0000922 Res = ModifiedRes;
923 Lex();
924 }
925
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000926 // Try to constant fold it up front, if possible.
927 int64_t Value;
928 if (Res->EvaluateAsAbsolute(Value))
929 Res = MCConstantExpr::Create(Value, getContext());
930
931 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000932}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000933
Chris Lattnerb4307b32010-01-15 19:28:38 +0000934bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000935 Res = 0;
936 return ParseParenExpr(Res, EndLoc) ||
937 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000938}
939
Daniel Dunbar475839e2009-06-29 20:37:27 +0000940bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000941 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000942
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000943 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000944 if (ParseExpression(Expr))
945 return true;
946
Daniel Dunbare00b0112009-10-16 01:57:52 +0000947 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000948 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000949
950 return false;
951}
952
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000953static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000954 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000955 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000956 default:
957 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000958
Jim Grosbachfbe16812011-08-20 16:24:13 +0000959 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000960 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000961 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000962 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000963 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000964 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000965 return 1;
966
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000967
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000968 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +0000969 //
970 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +0000971 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000972 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000973 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000974 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000975 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000976 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000977 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000978 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000979 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000980
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000981 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000982 case AsmToken::EqualEqual:
983 Kind = MCBinaryExpr::EQ;
984 return 3;
985 case AsmToken::ExclaimEqual:
986 case AsmToken::LessGreater:
987 Kind = MCBinaryExpr::NE;
988 return 3;
989 case AsmToken::Less:
990 Kind = MCBinaryExpr::LT;
991 return 3;
992 case AsmToken::LessEqual:
993 Kind = MCBinaryExpr::LTE;
994 return 3;
995 case AsmToken::Greater:
996 Kind = MCBinaryExpr::GT;
997 return 3;
998 case AsmToken::GreaterEqual:
999 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001000 return 3;
1001
Jim Grosbachfbe16812011-08-20 16:24:13 +00001002 // Intermediate Precedence: <<, >>
1003 case AsmToken::LessLess:
1004 Kind = MCBinaryExpr::Shl;
1005 return 4;
1006 case AsmToken::GreaterGreater:
1007 Kind = MCBinaryExpr::Shr;
1008 return 4;
1009
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001010 // High Intermediate Precedence: +, -
1011 case AsmToken::Plus:
1012 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001013 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001014 case AsmToken::Minus:
1015 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001016 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001017
Jim Grosbachfbe16812011-08-20 16:24:13 +00001018 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001019 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001020 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001021 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001022 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001023 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001024 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001025 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001026 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001027 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001028 }
1029}
1030
1031
1032/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1033/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001034bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1035 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001036 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001037 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001038 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001039
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001040 // If the next token is lower precedence than we are allowed to eat, return
1041 // successfully with what we ate already.
1042 if (TokPrec < Precedence)
1043 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001044
Sean Callanan79ed1a82010-01-19 20:22:31 +00001045 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001046
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001047 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001048 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001049 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001050
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001051 // If BinOp binds less tightly with RHS than the operator after RHS, let
1052 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001053 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001054 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001055 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001056 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001057 }
1058
Daniel Dunbar475839e2009-06-29 20:37:27 +00001059 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001060 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001061 }
1062}
1063
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001064/// ParseStatement:
1065/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001066/// ::= Label* Directive ...Operands... EndOfStatement
1067/// ::= Label* Identifier OperandList* EndOfStatement
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001068bool AsmParser::ParseStatement() {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001069 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001070 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001071 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001072 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001073 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001074
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001075 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001076 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001077 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001078 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001079 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001080 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001081 if (Lexer.is(AsmToken::Hash))
1082 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001083
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001084 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001085 if (Lexer.is(AsmToken::Integer)) {
1086 LocalLabelVal = getTok().getIntVal();
1087 if (LocalLabelVal < 0) {
1088 if (!TheCondState.Ignore)
1089 return TokError("unexpected token at start of statement");
1090 IDVal = "";
1091 }
1092 else {
1093 IDVal = getTok().getString();
1094 Lex(); // Consume the integer token to be used as an identifier token.
1095 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001096 if (!TheCondState.Ignore)
1097 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001098 }
1099 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001100
1101 } else if (Lexer.is(AsmToken::Dot)) {
1102 // Treat '.' as a valid identifier in this context.
1103 Lex();
1104 IDVal = ".";
1105
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001106 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001107 if (!TheCondState.Ignore)
1108 return TokError("unexpected token at start of statement");
1109 IDVal = "";
1110 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001111
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001112
Chris Lattner7834fac2010-04-17 18:14:27 +00001113 // Handle conditional assembly here before checking for skipping. We
1114 // have to do this so that .endif isn't skipped in a ".if 0" block for
1115 // example.
1116 if (IDVal == ".if")
1117 return ParseDirectiveIf(IDLoc);
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00001118 if (IDVal == ".ifb")
1119 return ParseDirectiveIfb(IDLoc, true);
1120 if (IDVal == ".ifnb")
1121 return ParseDirectiveIfb(IDLoc, false);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00001122 if (IDVal == ".ifc")
1123 return ParseDirectiveIfc(IDLoc, true);
1124 if (IDVal == ".ifnc")
1125 return ParseDirectiveIfc(IDLoc, false);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00001126 if (IDVal == ".ifdef")
1127 return ParseDirectiveIfdef(IDLoc, true);
1128 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1129 return ParseDirectiveIfdef(IDLoc, false);
Chris Lattner7834fac2010-04-17 18:14:27 +00001130 if (IDVal == ".elseif")
1131 return ParseDirectiveElseIf(IDLoc);
1132 if (IDVal == ".else")
1133 return ParseDirectiveElse(IDLoc);
1134 if (IDVal == ".endif")
1135 return ParseDirectiveEndIf(IDLoc);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001136
Chris Lattner7834fac2010-04-17 18:14:27 +00001137 // If we are in a ".if 0" block, ignore this statement.
1138 if (TheCondState.Ignore) {
1139 EatToEndOfStatement();
1140 return false;
1141 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001142
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001143 // FIXME: Recurse on local labels?
1144
1145 // See what kind of statement we have.
1146 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001147 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001148 CheckForValidSection();
1149
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001150 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001151 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001152
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001153 // Diagnose attempt to use '.' as a label.
1154 if (IDVal == ".")
1155 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1156
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001157 // Diagnose attempt to use a variable as a label.
1158 //
1159 // FIXME: Diagnostics. Note the location of the definition as a label.
1160 // FIXME: This doesn't diagnose assignment to a symbol which has been
1161 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001162 MCSymbol *Sym;
1163 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001164 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001165 else
1166 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001167 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001168 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001169
Daniel Dunbar959fd882009-08-26 22:13:22 +00001170 // Emit the label.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001171 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001172
Kevin Enderby94c2e852011-12-09 18:09:40 +00001173 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001174 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001175 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001176 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1177 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001178
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001179 // Consume any end of statement token, if present, to avoid spurious
1180 // AddBlankLine calls().
1181 if (Lexer.is(AsmToken::EndOfStatement)) {
1182 Lex();
1183 if (Lexer.is(AsmToken::Eof))
1184 return false;
1185 }
1186
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001187 return ParseStatement();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001188 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001189
Daniel Dunbar3f872332009-07-28 16:08:33 +00001190 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001191 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001192 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001193
Nico Weber4c4c7322011-01-28 03:04:41 +00001194 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001195
1196 default: // Normal instruction or directive.
1197 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001198 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001199
1200 // If macros are enabled, check to see if this is a macro instantiation.
1201 if (MacrosEnabled)
1202 if (const Macro *M = MacroMap.lookup(IDVal))
1203 return HandleMacroEntry(IDVal, IDLoc, M);
1204
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001205 // Otherwise, we have a normal instruction or directive.
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001206 if (IDVal[0] == '.' && IDVal != ".") {
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001207
1208 // Target hook for parsing target specific directives.
1209 if (!getTargetParser().ParseDirective(ID))
1210 return false;
1211
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001212 // Assembler features
Roman Divacky50e7a782010-10-28 16:22:58 +00001213 if (IDVal == ".set" || IDVal == ".equ")
Nico Weber4c4c7322011-01-28 03:04:41 +00001214 return ParseDirectiveSet(IDVal, true);
1215 if (IDVal == ".equiv")
1216 return ParseDirectiveSet(IDVal, false);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001217
Daniel Dunbara0d14262009-06-24 23:30:00 +00001218 // Data directives
1219
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001220 if (IDVal == ".ascii")
Rafael Espindola787c3372010-10-28 20:02:27 +00001221 return ParseDirectiveAscii(IDVal, false);
1222 if (IDVal == ".asciz" || IDVal == ".string")
1223 return ParseDirectiveAscii(IDVal, true);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001224
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001225 if (IDVal == ".byte")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001226 return ParseDirectiveValue(1);
Kevin Enderby9c656452009-09-10 20:51:44 +00001227 if (IDVal == ".short")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001228 return ParseDirectiveValue(2);
Rafael Espindolacc3acee2010-11-01 15:29:07 +00001229 if (IDVal == ".value")
1230 return ParseDirectiveValue(2);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001231 if (IDVal == ".2byte")
1232 return ParseDirectiveValue(2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001233 if (IDVal == ".long")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001234 return ParseDirectiveValue(4);
Rafael Espindola435279b2010-11-17 16:24:40 +00001235 if (IDVal == ".int")
1236 return ParseDirectiveValue(4);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001237 if (IDVal == ".4byte")
1238 return ParseDirectiveValue(4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001239 if (IDVal == ".quad")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001240 return ParseDirectiveValue(8);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001241 if (IDVal == ".8byte")
1242 return ParseDirectiveValue(8);
Roman Divacky14e66552011-01-28 14:20:32 +00001243 if (IDVal == ".single" || IDVal == ".float")
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001244 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1245 if (IDVal == ".double")
1246 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001247
Eli Friedman5d68ec22010-07-19 04:17:25 +00001248 if (IDVal == ".align") {
1249 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1250 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1251 }
1252 if (IDVal == ".align32") {
1253 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1254 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1255 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001256 if (IDVal == ".balign")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001257 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001258 if (IDVal == ".balignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001259 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001260 if (IDVal == ".balignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001261 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001262 if (IDVal == ".p2align")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001263 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001264 if (IDVal == ".p2alignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001265 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001266 if (IDVal == ".p2alignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001267 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1268
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001269 if (IDVal == ".org")
Daniel Dunbarc238b582009-06-25 22:44:51 +00001270 return ParseDirectiveOrg();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001271
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001272 if (IDVal == ".fill")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001273 return ParseDirectiveFill();
Rafael Espindolace8463f2011-04-07 20:26:23 +00001274 if (IDVal == ".space" || IDVal == ".skip")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001275 return ParseDirectiveSpace();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001276 if (IDVal == ".zero")
1277 return ParseDirectiveZero();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001278
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001279 // Symbol attribute directives
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001280
Benjamin Kramere14a3c52012-05-12 11:18:59 +00001281 if (IDVal == ".extern") {
1282 EatToEndOfStatement(); // .extern is the default, ignore it.
1283 return false;
1284 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001285 if (IDVal == ".globl" || IDVal == ".global")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001286 return ParseDirectiveSymbolAttribute(MCSA_Global);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001287 if (IDVal == ".indirect_symbol")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001288 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001289 if (IDVal == ".lazy_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001290 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001291 if (IDVal == ".no_dead_strip")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001292 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Kevin Enderbye8e98d72010-11-19 18:39:33 +00001293 if (IDVal == ".symbol_resolver")
1294 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001295 if (IDVal == ".private_extern")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001296 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001297 if (IDVal == ".reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001298 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001299 if (IDVal == ".weak_definition")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001300 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001301 if (IDVal == ".weak_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001302 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Kevin Enderbyf59cac52010-07-08 17:22:42 +00001303 if (IDVal == ".weak_def_can_be_hidden")
1304 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001305
Hans Wennborg5cc64912011-06-18 13:51:54 +00001306 if (IDVal == ".comm" || IDVal == ".common")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001307 return ParseDirectiveComm(/*IsLocal=*/false);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001308 if (IDVal == ".lcomm")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001309 return ParseDirectiveComm(/*IsLocal=*/true);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001310
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001311 if (IDVal == ".abort")
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001312 return ParseDirectiveAbort();
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001313 if (IDVal == ".include")
Kevin Enderby1f049b22009-07-14 23:21:55 +00001314 return ParseDirectiveInclude();
Kevin Enderbyc55acca2011-12-14 21:47:48 +00001315 if (IDVal == ".incbin")
1316 return ParseDirectiveIncbin();
Kevin Enderbya5c78322009-07-13 21:03:15 +00001317
Benjamin Kramer5cdf0ad2012-05-12 11:19:04 +00001318 if (IDVal == ".code16" || IDVal == ".code16gcc")
Roman Divackyf6fbd842011-01-31 20:56:49 +00001319 return TokError(Twine(IDVal) + " not supported yet");
Roman Divackycb727802011-01-28 19:29:48 +00001320
Rafael Espindola761cb062012-06-03 23:57:14 +00001321 // Macro-like directives
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001322 if (IDVal == ".rept")
1323 return ParseDirectiveRept(IDLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001324 if (IDVal == ".irp")
1325 return ParseDirectiveIrp(IDLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00001326 if (IDVal == ".irpc")
1327 return ParseDirectiveIrpc(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001328 if (IDVal == ".endr")
Rafael Espindola761cb062012-06-03 23:57:14 +00001329 return ParseDirectiveEndr(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001330
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001331 // Look up the handler in the handler table.
1332 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1333 DirectiveMap.lookup(IDVal);
1334 if (Handler.first)
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +00001335 return (*Handler.second)(Handler.first, IDVal, IDLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001336
Kevin Enderby9c656452009-09-10 20:51:44 +00001337
Jim Grosbach686c0182012-05-01 18:38:27 +00001338 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001339 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001340
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001341 CheckForValidSection();
1342
Chris Lattnera7f13542010-05-19 23:34:33 +00001343 // Canonicalize the opcode to lower case.
Chad Rosier8f138d12012-10-15 17:19:13 +00001344 SmallString<128> OpcodeStr;
Chris Lattnera7f13542010-05-19 23:34:33 +00001345 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
Chad Rosier8f138d12012-10-15 17:19:13 +00001346 OpcodeStr.push_back(tolower(IDVal[i]));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001347
Chad Rosier8f138d12012-10-15 17:19:13 +00001348 bool HadError = getTargetParser().ParseInstruction(OpcodeStr.str(), IDLoc,
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001349 ParsedOperands);
Chris Lattner2cf5f142009-06-22 01:29:09 +00001350
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001351 // Dump the parsed representation, if requested.
1352 if (getShowParsedOperands()) {
1353 SmallString<256> Str;
1354 raw_svector_ostream OS(Str);
1355 OS << "parsed instruction: [";
1356 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1357 if (i != 0)
1358 OS << ", ";
Jim Grosbachb7f689b2011-07-13 15:34:57 +00001359 ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001360 }
1361 OS << "]";
1362
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001363 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001364 }
1365
Kevin Enderby613b7572011-11-01 22:27:22 +00001366 // If we are generating dwarf for assembly source files and the current
1367 // section is the initial text section then generate a .loc directive for
1368 // the instruction.
1369 if (!HadError && getContext().getGenDwarfForAssembly() &&
1370 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1371 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1372 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1373 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001374 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001375 StringRef());
1376 }
1377
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001378 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001379 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001380 unsigned ErrorInfo;
1381 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Opcode,
Chad Rosier8f138d12012-10-15 17:19:13 +00001382 ParsedOperands, Out,
1383 ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001384 ParsingInlineAsm);
1385 }
Chris Lattner98986712010-01-14 22:21:20 +00001386
Chad Rosierb1f8c132012-10-18 15:49:34 +00001387 // Free any parsed operands. If parsing ms-style inline assembly the operands
1388 // will be freed by the ParseMSInlineAsm() function.
1389 if (!ParsingInlineAsm) {
1390 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1391 delete ParsedOperands[i];
1392 ParsedOperands.clear();
1393 }
Chris Lattner98986712010-01-14 22:21:20 +00001394
Chris Lattnercbf8a982010-09-11 16:18:25 +00001395 // Don't skip the rest of the line, the instruction parser is responsible for
1396 // that.
1397 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001398}
Chris Lattner9a023f72009-06-24 04:43:34 +00001399
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001400/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1401/// since they may not be able to be tokenized to get to the end of line token.
1402void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001403 if (!Lexer.is(AsmToken::EndOfStatement))
1404 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001405 // Eat EOL.
1406 Lex();
1407}
1408
1409/// ParseCppHashLineFilenameComment as this:
1410/// ::= # number "filename"
1411/// or just as a full line comment if it doesn't have a number and a string.
1412bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1413 Lex(); // Eat the hash token.
1414
1415 if (getLexer().isNot(AsmToken::Integer)) {
1416 // Consume the line since in cases it is not a well-formed line directive,
1417 // as if were simply a full line comment.
1418 EatToEndOfLine();
1419 return false;
1420 }
1421
1422 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001423 Lex();
1424
1425 if (getLexer().isNot(AsmToken::String)) {
1426 EatToEndOfLine();
1427 return false;
1428 }
1429
1430 StringRef Filename = getTok().getString();
1431 // Get rid of the enclosing quotes.
1432 Filename = Filename.substr(1, Filename.size()-2);
1433
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001434 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1435 CppHashLoc = L;
1436 CppHashFilename = Filename;
1437 CppHashLineNumber = LineNumber;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001438
1439 // Ignore any trailing characters, they're just comment.
1440 EatToEndOfLine();
1441 return false;
1442}
1443
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001444/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001445/// for the Filename and LineNo if any in the diagnostic.
1446void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1447 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1448 raw_ostream &OS = errs();
1449
1450 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1451 const SMLoc &DiagLoc = Diag.getLoc();
1452 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1453 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1454
1455 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1456 // before printing the message.
1457 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001458 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001459 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1460 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1461 }
1462
1463 // If we have not parsed a cpp hash line filename comment or the source
1464 // manager changed or buffer changed (like in a nested include) then just
1465 // print the normal diagnostic using its Filename and LineNo.
1466 if (!Parser->CppHashLineNumber ||
1467 &DiagSrcMgr != &Parser->SrcMgr ||
1468 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001469 if (Parser->SavedDiagHandler)
1470 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1471 else
1472 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001473 return;
1474 }
1475
1476 // Use the CppHashFilename and calculate a line number based on the
1477 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1478 // the diagnostic.
1479 const std::string Filename = Parser->CppHashFilename;
1480
1481 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1482 int CppHashLocLineNo =
1483 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1484 int LineNo = Parser->CppHashLineNumber - 1 +
1485 (DiagLocLineNo - CppHashLocLineNo);
1486
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001487 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1488 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001489 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001490 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001491
Benjamin Kramer04a04262011-10-16 10:48:29 +00001492 if (Parser->SavedDiagHandler)
1493 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1494 else
1495 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001496}
1497
Rafael Espindola799aacf2012-08-21 18:29:30 +00001498// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1499// difference being that that function accepts '@' as part of identifiers and
1500// we can't do that. AsmLexer.cpp should probably be changed to handle
1501// '@' as a special case when needed.
1502static bool isIdentifierChar(char c) {
1503 return isalnum(c) || c == '_' || c == '$' || c == '.';
1504}
1505
Rafael Espindola761cb062012-06-03 23:57:14 +00001506bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +00001507 const MacroParameters &Parameters,
1508 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001509 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001510 unsigned NParameters = Parameters.size();
1511 if (NParameters != 0 && NParameters != A.size())
1512 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001513
Preston Gurd7b6f2032012-09-19 20:36:12 +00001514 // A macro without parameters is handled differently on Darwin:
1515 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001516 while (!Body.empty()) {
1517 // Scan for the next substitution.
1518 std::size_t End = Body.size(), Pos = 0;
1519 for (; Pos != End; ++Pos) {
1520 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001521 if (!NParameters) {
1522 // This macro has no parameters, look for $0, $1, etc.
1523 if (Body[Pos] != '$' || Pos + 1 == End)
1524 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001525
Rafael Espindola65366442011-06-05 02:43:45 +00001526 char Next = Body[Pos + 1];
1527 if (Next == '$' || Next == 'n' || isdigit(Next))
1528 break;
1529 } else {
1530 // This macro has parameters, look for \foo, \bar, etc.
1531 if (Body[Pos] == '\\' && Pos + 1 != End)
1532 break;
1533 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001534 }
1535
1536 // Add the prefix.
1537 OS << Body.slice(0, Pos);
1538
1539 // Check if we reached the end.
1540 if (Pos == End)
1541 break;
1542
Rafael Espindola65366442011-06-05 02:43:45 +00001543 if (!NParameters) {
1544 switch (Body[Pos+1]) {
1545 // $$ => $
1546 case '$':
1547 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001548 break;
1549
Rafael Espindola65366442011-06-05 02:43:45 +00001550 // $n => number of arguments
1551 case 'n':
1552 OS << A.size();
1553 break;
1554
1555 // $[0-9] => argument
1556 default: {
1557 // Missing arguments are ignored.
1558 unsigned Index = Body[Pos+1] - '0';
1559 if (Index >= A.size())
1560 break;
1561
1562 // Otherwise substitute with the token values, with spaces eliminated.
Rafael Espindola28c1f6662012-06-03 22:41:23 +00001563 for (MacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001564 ie = A[Index].end(); it != ie; ++it)
1565 OS << it->getString();
1566 break;
1567 }
1568 }
1569 Pos += 2;
1570 } else {
1571 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001572 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001573 ++I;
1574
1575 const char *Begin = Body.data() + Pos +1;
1576 StringRef Argument(Begin, I - (Pos +1));
1577 unsigned Index = 0;
1578 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001579 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001580 break;
1581
Preston Gurd7b6f2032012-09-19 20:36:12 +00001582 if (Index == NParameters) {
1583 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1584 Pos += 3;
1585 else {
1586 OS << '\\' << Argument;
1587 Pos = I;
1588 }
1589 } else {
1590 for (MacroArgument::const_iterator it = A[Index].begin(),
1591 ie = A[Index].end(); it != ie; ++it)
1592 if (it->getKind() == AsmToken::String)
1593 OS << it->getStringContents();
1594 else
1595 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001596
Preston Gurd7b6f2032012-09-19 20:36:12 +00001597 Pos += 1 + Argument.size();
1598 }
Rafael Espindola65366442011-06-05 02:43:45 +00001599 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001600 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001601 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001602 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001603
Rafael Espindola65366442011-06-05 02:43:45 +00001604 return false;
1605}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001606
Rafael Espindola65366442011-06-05 02:43:45 +00001607MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1608 MemoryBuffer *I)
1609 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1610{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001611}
1612
Preston Gurd7b6f2032012-09-19 20:36:12 +00001613static bool IsOperator(AsmToken::TokenKind kind)
1614{
1615 switch (kind)
1616 {
1617 default:
1618 return false;
1619 case AsmToken::Plus:
1620 case AsmToken::Minus:
1621 case AsmToken::Tilde:
1622 case AsmToken::Slash:
1623 case AsmToken::Star:
1624 case AsmToken::Dot:
1625 case AsmToken::Equal:
1626 case AsmToken::EqualEqual:
1627 case AsmToken::Pipe:
1628 case AsmToken::PipePipe:
1629 case AsmToken::Caret:
1630 case AsmToken::Amp:
1631 case AsmToken::AmpAmp:
1632 case AsmToken::Exclaim:
1633 case AsmToken::ExclaimEqual:
1634 case AsmToken::Percent:
1635 case AsmToken::Less:
1636 case AsmToken::LessEqual:
1637 case AsmToken::LessLess:
1638 case AsmToken::LessGreater:
1639 case AsmToken::Greater:
1640 case AsmToken::GreaterEqual:
1641 case AsmToken::GreaterGreater:
1642 return true;
1643 }
1644}
1645
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001646/// ParseMacroArgument - Extract AsmTokens for a macro argument.
1647/// This is used for both default macro parameter values and the
1648/// arguments in macro invocations
Preston Gurd7b6f2032012-09-19 20:36:12 +00001649bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1650 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001651 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001652 unsigned AddTokens = 0;
1653
1654 // gas accepts arguments separated by whitespace, except on Darwin
1655 if (!IsDarwin)
1656 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001657
1658 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001659 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1660 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001661 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001662 }
1663
1664 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1665 // Spaces and commas cannot be mixed to delimit parameters
1666 if (ArgumentDelimiter == AsmToken::Eof)
1667 ArgumentDelimiter = AsmToken::Comma;
1668 else if (ArgumentDelimiter != AsmToken::Comma) {
1669 Lexer.setSkipSpace(true);
1670 return TokError("expected ' ' for macro argument separator");
1671 }
1672 break;
1673 }
1674
1675 if (Lexer.is(AsmToken::Space)) {
1676 Lex(); // Eat spaces
1677
1678 // Spaces can delimit parameters, but could also be part an expression.
1679 // If the token after a space is an operator, add the token and the next
1680 // one into this argument
1681 if (ArgumentDelimiter == AsmToken::Space ||
1682 ArgumentDelimiter == AsmToken::Eof) {
1683 if (IsOperator(Lexer.getKind())) {
1684 // Check to see whether the token is used as an operator,
1685 // or part of an identifier
1686 const char *NextChar = getTok().getEndLoc().getPointer() + 1;
1687 if (*NextChar == ' ')
1688 AddTokens = 2;
1689 }
1690
1691 if (!AddTokens && ParenLevel == 0) {
1692 if (ArgumentDelimiter == AsmToken::Eof &&
1693 !IsOperator(Lexer.getKind()))
1694 ArgumentDelimiter = AsmToken::Space;
1695 break;
1696 }
1697 }
1698 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001699
1700 // HandleMacroEntry relies on not advancing the lexer here
1701 // to be able to fill in the remaining default parameter values
1702 if (Lexer.is(AsmToken::EndOfStatement))
1703 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001704
1705 // Adjust the current parentheses level.
1706 if (Lexer.is(AsmToken::LParen))
1707 ++ParenLevel;
1708 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1709 --ParenLevel;
1710
1711 // Append the token to the current argument list.
1712 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001713 if (AddTokens)
1714 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001715 Lex();
1716 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001717
1718 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001719 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001720 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001721 return false;
1722}
1723
1724// Parse the macro instantiation arguments.
Rafael Espindola8a403d32012-08-08 14:51:03 +00001725bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001726 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001727 // Argument delimiter is initially unknown. It will be set by
1728 // ParseMacroArgument()
1729 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001730
1731 // Parse two kinds of macro invocations:
1732 // - macros defined without any parameters accept an arbitrary number of them
1733 // - macros defined with parameters accept at most that many of them
1734 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1735 ++Parameter) {
1736 MacroArgument MA;
1737
Preston Gurd7b6f2032012-09-19 20:36:12 +00001738 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001739 return true;
1740
Preston Gurd6c9176a2012-09-19 20:29:04 +00001741 if (!MA.empty() || !NParameters)
1742 A.push_back(MA);
1743 else if (NParameters) {
1744 if (!M->Parameters[Parameter].second.empty())
1745 A.push_back(M->Parameters[Parameter].second);
1746 }
Jim Grosbach97146442012-07-30 22:44:17 +00001747
Preston Gurd6c9176a2012-09-19 20:29:04 +00001748 // At the end of the statement, fill in remaining arguments that have
1749 // default values. If there aren't any, then the next argument is
1750 // required but missing
1751 if (Lexer.is(AsmToken::EndOfStatement)) {
1752 if (NParameters && Parameter < NParameters - 1) {
1753 if (M->Parameters[Parameter + 1].second.empty())
1754 return TokError("macro argument '" +
1755 Twine(M->Parameters[Parameter + 1].first) +
1756 "' is missing");
1757 else
1758 continue;
1759 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001760 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001761 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001762
1763 if (Lexer.is(AsmToken::Comma))
1764 Lex();
1765 }
1766 return TokError("Too many arguments");
1767}
1768
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001769bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1770 const Macro *M) {
1771 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1772 // this, although we should protect against infinite loops.
1773 if (ActiveMacros.size() == 20)
1774 return TokError("macros cannot be nested more than 20 levels deep");
1775
Rafael Espindola8a403d32012-08-08 14:51:03 +00001776 MacroArguments A;
1777 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001778 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001779
Jim Grosbach97146442012-07-30 22:44:17 +00001780 // Remove any trailing empty arguments. Do this after-the-fact as we have
1781 // to keep empty arguments in the middle of the list or positionality
1782 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001783 while (!A.empty() && A.back().empty())
1784 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001785
Rafael Espindola65366442011-06-05 02:43:45 +00001786 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1787 // to hold the macro body with substitutions.
1788 SmallString<256> Buf;
1789 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001790 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001791
Rafael Espindola8a403d32012-08-08 14:51:03 +00001792 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001793 return true;
1794
Rafael Espindola761cb062012-06-03 23:57:14 +00001795 // We include the .endmacro in the buffer as our queue to exit the macro
1796 // instantiation.
1797 OS << ".endmacro\n";
1798
Rafael Espindola65366442011-06-05 02:43:45 +00001799 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001800 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001801
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001802 // Create the macro instantiation object and add to the current macro
1803 // instantiation stack.
1804 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001805 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001806 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001807 ActiveMacros.push_back(MI);
1808
1809 // Jump to the macro instantiation and prime the lexer.
1810 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1811 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1812 Lex();
1813
1814 return false;
1815}
1816
1817void AsmParser::HandleMacroExit() {
1818 // Jump to the EndOfStatement we should return to, and consume it.
1819 JumpToLoc(ActiveMacros.back()->ExitLoc);
1820 Lex();
1821
1822 // Pop the instantiation entry.
1823 delete ActiveMacros.back();
1824 ActiveMacros.pop_back();
1825}
1826
Rafael Espindolae71cc862012-01-28 05:57:00 +00001827static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001828 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001829 case MCExpr::Binary: {
1830 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1831 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001832 break;
1833 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001834 case MCExpr::Target:
1835 case MCExpr::Constant:
1836 return false;
1837 case MCExpr::SymbolRef: {
1838 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001839 if (S.isVariable())
1840 return IsUsedIn(Sym, S.getVariableValue());
1841 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001842 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001843 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001844 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001845 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001846
1847 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001848}
1849
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001850bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1851 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001852 // FIXME: Use better location, we should use proper tokens.
1853 SMLoc EqualLoc = Lexer.getLoc();
1854
Daniel Dunbar821e3332009-08-31 08:09:28 +00001855 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001856 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001857 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001858
Rafael Espindolae71cc862012-01-28 05:57:00 +00001859 // Note: we don't count b as used in "a = b". This is to allow
1860 // a = b
1861 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001862
Daniel Dunbar3f872332009-07-28 16:08:33 +00001863 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001864 return TokError("unexpected token in assignment");
1865
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001866 // Error on assignment to '.'.
1867 if (Name == ".") {
1868 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1869 "(use '.space' or '.org').)"));
1870 }
1871
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001872 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001873 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001874
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001875 // Validate that the LHS is allowed to be a variable (either it has not been
1876 // used as a symbol, or it is an absolute symbol).
1877 MCSymbol *Sym = getContext().LookupSymbol(Name);
1878 if (Sym) {
1879 // Diagnose assignment to a label.
1880 //
1881 // FIXME: Diagnostics. Note the location of the definition as a label.
1882 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00001883 if (IsUsedIn(Sym, Value))
1884 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1885 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001886 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00001887 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1888 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00001889 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001890 return Error(EqualLoc, "redefinition of '" + Name + "'");
1891 else if (!Sym->isVariable())
1892 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00001893 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001894 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1895 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001896
1897 // Don't count these checks as uses.
1898 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001899 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001900 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001901
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001902 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001903
1904 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00001905 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001906 if (NoDeadStrip)
1907 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1908
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001909
1910 return false;
1911}
1912
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001913/// ParseIdentifier:
1914/// ::= identifier
1915/// ::= string
1916bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00001917 // The assembler has relaxed rules for accepting identifiers, in particular we
1918 // allow things like '.globl $foo', which would normally be separate
1919 // tokens. At this level, we have already lexed so we cannot (currently)
1920 // handle this as a context dependent token, instead we detect adjacent tokens
1921 // and return the combined identifier.
1922 if (Lexer.is(AsmToken::Dollar)) {
1923 SMLoc DollarLoc = getLexer().getLoc();
1924
1925 // Consume the dollar sign, and check for a following identifier.
1926 Lex();
1927 if (Lexer.isNot(AsmToken::Identifier))
1928 return true;
1929
1930 // We have a '$' followed by an identifier, make sure they are adjacent.
1931 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1932 return true;
1933
1934 // Construct the joined identifier and consume the token.
1935 Res = StringRef(DollarLoc.getPointer(),
1936 getTok().getIdentifier().size() + 1);
1937 Lex();
1938 return false;
1939 }
1940
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001941 if (Lexer.isNot(AsmToken::Identifier) &&
1942 Lexer.isNot(AsmToken::String))
1943 return true;
1944
Sean Callanan18b83232010-01-19 21:44:56 +00001945 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001946
Sean Callanan79ed1a82010-01-19 20:22:31 +00001947 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001948
1949 return false;
1950}
1951
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001952/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00001953/// ::= .equ identifier ',' expression
1954/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001955/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00001956bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001957 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001958
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001959 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00001960 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001961
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001962 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00001963 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001964 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001965
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001966 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001967}
1968
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001969bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001970 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001971
1972 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00001973 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001974 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1975 if (Str[i] != '\\') {
1976 Data += Str[i];
1977 continue;
1978 }
1979
1980 // Recognize escaped characters. Note that this escape semantics currently
1981 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1982 ++i;
1983 if (i == e)
1984 return TokError("unexpected backslash at end of string");
1985
1986 // Recognize octal sequences.
1987 if ((unsigned) (Str[i] - '0') <= 7) {
1988 // Consume up to three octal characters.
1989 unsigned Value = Str[i] - '0';
1990
1991 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1992 ++i;
1993 Value = Value * 8 + (Str[i] - '0');
1994
1995 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1996 ++i;
1997 Value = Value * 8 + (Str[i] - '0');
1998 }
1999 }
2000
2001 if (Value > 255)
2002 return TokError("invalid octal escape sequence (out of range)");
2003
2004 Data += (unsigned char) Value;
2005 continue;
2006 }
2007
2008 // Otherwise recognize individual escapes.
2009 switch (Str[i]) {
2010 default:
2011 // Just reject invalid escape sequences for now.
2012 return TokError("invalid escape sequence (unrecognized character)");
2013
2014 case 'b': Data += '\b'; break;
2015 case 'f': Data += '\f'; break;
2016 case 'n': Data += '\n'; break;
2017 case 'r': Data += '\r'; break;
2018 case 't': Data += '\t'; break;
2019 case '"': Data += '"'; break;
2020 case '\\': Data += '\\'; break;
2021 }
2022 }
2023
2024 return false;
2025}
2026
Daniel Dunbara0d14262009-06-24 23:30:00 +00002027/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002028/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2029bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002030 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002031 CheckForValidSection();
2032
Daniel Dunbara0d14262009-06-24 23:30:00 +00002033 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002034 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002035 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002036
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002037 std::string Data;
2038 if (ParseEscapedString(Data))
2039 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002040
2041 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002042 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002043 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2044
Sean Callanan79ed1a82010-01-19 20:22:31 +00002045 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002046
2047 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002048 break;
2049
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002050 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002051 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002052 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002053 }
2054 }
2055
Sean Callanan79ed1a82010-01-19 20:22:31 +00002056 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002057 return false;
2058}
2059
2060/// ParseDirectiveValue
2061/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2062bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002063 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002064 CheckForValidSection();
2065
Daniel Dunbara0d14262009-06-24 23:30:00 +00002066 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002067 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002068 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002069 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002070 return true;
2071
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002072 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002073 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2074 assert(Size <= 8 && "Invalid size");
2075 uint64_t IntValue = MCE->getValue();
2076 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2077 return Error(ExprLoc, "literal value out of range for directive");
2078 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2079 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002080 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002081
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002082 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002083 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002084
Daniel Dunbara0d14262009-06-24 23:30:00 +00002085 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002086 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002087 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002088 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002089 }
2090 }
2091
Sean Callanan79ed1a82010-01-19 20:22:31 +00002092 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002093 return false;
2094}
2095
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002096/// ParseDirectiveRealValue
2097/// ::= (.single | .double) [ expression (, expression)* ]
2098bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2099 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2100 CheckForValidSection();
2101
2102 for (;;) {
2103 // We don't truly support arithmetic on floating point expressions, so we
2104 // have to manually parse unary prefixes.
2105 bool IsNeg = false;
2106 if (getLexer().is(AsmToken::Minus)) {
2107 Lex();
2108 IsNeg = true;
2109 } else if (getLexer().is(AsmToken::Plus))
2110 Lex();
2111
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002112 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002113 getLexer().isNot(AsmToken::Real) &&
2114 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002115 return TokError("unexpected token in directive");
2116
2117 // Convert to an APFloat.
2118 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002119 StringRef IDVal = getTok().getString();
2120 if (getLexer().is(AsmToken::Identifier)) {
2121 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2122 Value = APFloat::getInf(Semantics);
2123 else if (!IDVal.compare_lower("nan"))
2124 Value = APFloat::getNaN(Semantics, false, ~0);
2125 else
2126 return TokError("invalid floating point literal");
2127 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002128 APFloat::opInvalidOp)
2129 return TokError("invalid floating point literal");
2130 if (IsNeg)
2131 Value.changeSign();
2132
2133 // Consume the numeric token.
2134 Lex();
2135
2136 // Emit the value as an integer.
2137 APInt AsInt = Value.bitcastToAPInt();
2138 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2139 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2140
2141 if (getLexer().is(AsmToken::EndOfStatement))
2142 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002143
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002144 if (getLexer().isNot(AsmToken::Comma))
2145 return TokError("unexpected token in directive");
2146 Lex();
2147 }
2148 }
2149
2150 Lex();
2151 return false;
2152}
2153
Daniel Dunbara0d14262009-06-24 23:30:00 +00002154/// ParseDirectiveSpace
2155/// ::= .space expression [ , expression ]
2156bool AsmParser::ParseDirectiveSpace() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002157 CheckForValidSection();
2158
Daniel Dunbara0d14262009-06-24 23:30:00 +00002159 int64_t NumBytes;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002160 if (ParseAbsoluteExpression(NumBytes))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002161 return true;
2162
2163 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002164 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2165 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002166 return TokError("unexpected token in '.space' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002167 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002168
Daniel Dunbar475839e2009-06-29 20:37:27 +00002169 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002170 return true;
2171
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002172 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002173 return TokError("unexpected token in '.space' directive");
2174 }
2175
Sean Callanan79ed1a82010-01-19 20:22:31 +00002176 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002177
2178 if (NumBytes <= 0)
2179 return TokError("invalid number of bytes in '.space' directive");
2180
2181 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002182 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002183
2184 return false;
2185}
2186
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002187/// ParseDirectiveZero
2188/// ::= .zero expression
2189bool AsmParser::ParseDirectiveZero() {
2190 CheckForValidSection();
2191
2192 int64_t NumBytes;
2193 if (ParseAbsoluteExpression(NumBytes))
2194 return true;
2195
Rafael Espindolae452b172010-10-05 19:42:57 +00002196 int64_t Val = 0;
2197 if (getLexer().is(AsmToken::Comma)) {
2198 Lex();
2199 if (ParseAbsoluteExpression(Val))
2200 return true;
2201 }
2202
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002203 if (getLexer().isNot(AsmToken::EndOfStatement))
2204 return TokError("unexpected token in '.zero' directive");
2205
2206 Lex();
2207
Rafael Espindolae452b172010-10-05 19:42:57 +00002208 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002209
2210 return false;
2211}
2212
Daniel Dunbara0d14262009-06-24 23:30:00 +00002213/// ParseDirectiveFill
2214/// ::= .fill expression , expression , expression
2215bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002216 CheckForValidSection();
2217
Daniel Dunbara0d14262009-06-24 23:30:00 +00002218 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002219 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002220 return true;
2221
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002222 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002223 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002224 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002225
Daniel Dunbara0d14262009-06-24 23:30:00 +00002226 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002227 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002228 return true;
2229
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002230 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002231 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002232 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002233
Daniel Dunbara0d14262009-06-24 23:30:00 +00002234 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002235 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002236 return true;
2237
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002238 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002239 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002240
Sean Callanan79ed1a82010-01-19 20:22:31 +00002241 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002242
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002243 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2244 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002245
2246 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002247 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002248
2249 return false;
2250}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002251
2252/// ParseDirectiveOrg
2253/// ::= .org expression [ , expression ]
2254bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002255 CheckForValidSection();
2256
Daniel Dunbar821e3332009-08-31 08:09:28 +00002257 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002258 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002259 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002260 return true;
2261
2262 // Parse optional fill expression.
2263 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002264 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2265 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002266 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002267 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002268
Daniel Dunbar475839e2009-06-29 20:37:27 +00002269 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002270 return true;
2271
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002272 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002273 return TokError("unexpected token in '.org' directive");
2274 }
2275
Sean Callanan79ed1a82010-01-19 20:22:31 +00002276 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002277
Jim Grosbachebd4c052012-01-27 00:37:08 +00002278 // Only limited forms of relocatable expressions are accepted here, it
2279 // has to be relative to the current section. The streamer will return
2280 // 'true' if the expression wasn't evaluatable.
2281 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2282 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002283
2284 return false;
2285}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002286
2287/// ParseDirectiveAlign
2288/// ::= {.align, ...} expression [ , expression [ , expression ]]
2289bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002290 CheckForValidSection();
2291
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002292 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002293 int64_t Alignment;
2294 if (ParseAbsoluteExpression(Alignment))
2295 return true;
2296
2297 SMLoc MaxBytesLoc;
2298 bool HasFillExpr = false;
2299 int64_t FillExpr = 0;
2300 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002301 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2302 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002303 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002304 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002305
2306 // The fill expression can be omitted while specifying a maximum number of
2307 // alignment bytes, e.g:
2308 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002309 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002310 HasFillExpr = true;
2311 if (ParseAbsoluteExpression(FillExpr))
2312 return true;
2313 }
2314
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002315 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2316 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002317 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002318 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002319
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002320 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002321 if (ParseAbsoluteExpression(MaxBytesToFill))
2322 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002323
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002324 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002325 return TokError("unexpected token in directive");
2326 }
2327 }
2328
Sean Callanan79ed1a82010-01-19 20:22:31 +00002329 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002330
Daniel Dunbar648ac512010-05-17 21:54:30 +00002331 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002332 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002333
2334 // Compute alignment in bytes.
2335 if (IsPow2) {
2336 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002337 if (Alignment >= 32) {
2338 Error(AlignmentLoc, "invalid alignment value");
2339 Alignment = 31;
2340 }
2341
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002342 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002343 }
2344
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002345 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002346 if (MaxBytesLoc.isValid()) {
2347 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002348 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2349 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002350 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002351 }
2352
2353 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002354 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2355 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002356 MaxBytesToFill = 0;
2357 }
2358 }
2359
Daniel Dunbar648ac512010-05-17 21:54:30 +00002360 // Check whether we should use optimal code alignment for this .align
2361 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002362 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002363 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2364 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002365 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002366 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002367 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002368 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2369 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002370 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002371
2372 return false;
2373}
2374
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002375/// ParseDirectiveSymbolAttribute
2376/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00002377bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002378 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002379 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002380 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00002381 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002382
2383 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00002384 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002385
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002386 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002387
Jim Grosbach10ec6502011-09-15 17:56:49 +00002388 // Assembler local symbols don't make any sense here. Complain loudly.
2389 if (Sym->isTemporary())
2390 return Error(Loc, "non-local symbol required in directive");
2391
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002392 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002393
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002394 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002395 break;
2396
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002397 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002398 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002399 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002400 }
2401 }
2402
Sean Callanan79ed1a82010-01-19 20:22:31 +00002403 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00002404 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002405}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002406
2407/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00002408/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2409bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002410 CheckForValidSection();
2411
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002412 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002413 StringRef Name;
2414 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002415 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002416
Daniel Dunbar76c4d762009-07-31 21:55:09 +00002417 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002418 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002419
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002420 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002421 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002422 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002423
2424 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002425 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002426 if (ParseAbsoluteExpression(Size))
2427 return true;
2428
2429 int64_t Pow2Alignment = 0;
2430 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002431 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00002432 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002433 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002434 if (ParseAbsoluteExpression(Pow2Alignment))
2435 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002436
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002437 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2438 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00002439 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2440
Chris Lattner258281d2010-01-19 06:22:22 +00002441 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002442 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2443 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00002444 if (!isPowerOf2_64(Pow2Alignment))
2445 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2446 Pow2Alignment = Log2_64(Pow2Alignment);
2447 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002448 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002449
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002450 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00002451 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002452
Sean Callanan79ed1a82010-01-19 20:22:31 +00002453 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002454
Chris Lattner1fc3d752009-07-09 17:25:12 +00002455 // NOTE: a size of zero for a .comm should create a undefined symbol
2456 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002457 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002458 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2459 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002460
Eric Christopherc260a3e2010-05-14 01:38:54 +00002461 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002462 // may internally end up wanting an alignment in bytes.
2463 // FIXME: Diagnose overflow.
2464 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002465 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2466 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002467
Daniel Dunbar8906ff12009-08-22 07:22:36 +00002468 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002469 return Error(IDLoc, "invalid symbol redefinition");
2470
Chris Lattner1fc3d752009-07-09 17:25:12 +00002471 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002472 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00002473 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002474 return false;
2475 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002476
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002477 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002478 return false;
2479}
Chris Lattner9be3fee2009-07-10 22:20:30 +00002480
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002481/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002482/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002483bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002484 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002485 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002486
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002487 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002488 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002489 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002490
Sean Callanan79ed1a82010-01-19 20:22:31 +00002491 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002492
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002493 if (Str.empty())
2494 Error(Loc, ".abort detected. Assembly stopping.");
2495 else
2496 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002497 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002498
2499 return false;
2500}
Kevin Enderby71148242009-07-14 21:35:03 +00002501
Kevin Enderby1f049b22009-07-14 23:21:55 +00002502/// ParseDirectiveInclude
2503/// ::= .include "filename"
2504bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002505 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002506 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002507
Sean Callanan18b83232010-01-19 21:44:56 +00002508 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002509 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002510 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00002511
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002512 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002513 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002514
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002515 // Strip the quotes.
2516 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002517
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002518 // Attempt to switch the lexer to the included file before consuming the end
2519 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00002520 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00002521 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002522 return true;
2523 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00002524
2525 return false;
2526}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00002527
Kevin Enderbyc55acca2011-12-14 21:47:48 +00002528/// ParseDirectiveIncbin
2529/// ::= .incbin "filename"
2530bool AsmParser::ParseDirectiveIncbin() {
2531 if (getLexer().isNot(AsmToken::String))
2532 return TokError("expected string in '.incbin' directive");
2533
2534 std::string Filename = getTok().getString();
2535 SMLoc IncbinLoc = getLexer().getLoc();
2536 Lex();
2537
2538 if (getLexer().isNot(AsmToken::EndOfStatement))
2539 return TokError("unexpected token in '.incbin' directive");
2540
2541 // Strip the quotes.
2542 Filename = Filename.substr(1, Filename.size()-2);
2543
2544 // Attempt to process the included file.
2545 if (ProcessIncbinFile(Filename)) {
2546 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2547 return true;
2548 }
2549
2550 return false;
2551}
2552
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002553/// ParseDirectiveIf
2554/// ::= .if expression
2555bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002556 TheCondStack.push_back(TheCondState);
2557 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00002558 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002559 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00002560 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002561 int64_t ExprValue;
2562 if (ParseAbsoluteExpression(ExprValue))
2563 return true;
2564
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002565 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002566 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002567
Sean Callanan79ed1a82010-01-19 20:22:31 +00002568 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002569
2570 TheCondState.CondMet = ExprValue;
2571 TheCondState.Ignore = !TheCondState.CondMet;
2572 }
2573
2574 return false;
2575}
2576
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002577/// ParseDirectiveIfb
2578/// ::= .ifb string
2579bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2580 TheCondStack.push_back(TheCondState);
2581 TheCondState.TheCond = AsmCond::IfCond;
2582
Benjamin Kramer29739e72012-05-12 16:52:21 +00002583 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002584 EatToEndOfStatement();
2585 } else {
2586 StringRef Str = ParseStringToEndOfStatement();
2587
2588 if (getLexer().isNot(AsmToken::EndOfStatement))
2589 return TokError("unexpected token in '.ifb' directive");
2590
2591 Lex();
2592
2593 TheCondState.CondMet = ExpectBlank == Str.empty();
2594 TheCondState.Ignore = !TheCondState.CondMet;
2595 }
2596
2597 return false;
2598}
2599
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002600/// ParseDirectiveIfc
2601/// ::= .ifc string1, string2
2602bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2603 TheCondStack.push_back(TheCondState);
2604 TheCondState.TheCond = AsmCond::IfCond;
2605
Benjamin Kramer29739e72012-05-12 16:52:21 +00002606 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002607 EatToEndOfStatement();
2608 } else {
2609 StringRef Str1 = ParseStringToComma();
2610
2611 if (getLexer().isNot(AsmToken::Comma))
2612 return TokError("unexpected token in '.ifc' directive");
2613
2614 Lex();
2615
2616 StringRef Str2 = ParseStringToEndOfStatement();
2617
2618 if (getLexer().isNot(AsmToken::EndOfStatement))
2619 return TokError("unexpected token in '.ifc' directive");
2620
2621 Lex();
2622
2623 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2624 TheCondState.Ignore = !TheCondState.CondMet;
2625 }
2626
2627 return false;
2628}
2629
2630/// ParseDirectiveIfdef
2631/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00002632bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2633 StringRef Name;
2634 TheCondStack.push_back(TheCondState);
2635 TheCondState.TheCond = AsmCond::IfCond;
2636
2637 if (TheCondState.Ignore) {
2638 EatToEndOfStatement();
2639 } else {
2640 if (ParseIdentifier(Name))
2641 return TokError("expected identifier after '.ifdef'");
2642
2643 Lex();
2644
2645 MCSymbol *Sym = getContext().LookupSymbol(Name);
2646
2647 if (expect_defined)
2648 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2649 else
2650 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2651 TheCondState.Ignore = !TheCondState.CondMet;
2652 }
2653
2654 return false;
2655}
2656
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002657/// ParseDirectiveElseIf
2658/// ::= .elseif expression
2659bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2660 if (TheCondState.TheCond != AsmCond::IfCond &&
2661 TheCondState.TheCond != AsmCond::ElseIfCond)
2662 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2663 " an .elseif");
2664 TheCondState.TheCond = AsmCond::ElseIfCond;
2665
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002666 bool LastIgnoreState = false;
2667 if (!TheCondStack.empty())
2668 LastIgnoreState = TheCondStack.back().Ignore;
2669 if (LastIgnoreState || TheCondState.CondMet) {
2670 TheCondState.Ignore = true;
2671 EatToEndOfStatement();
2672 }
2673 else {
2674 int64_t ExprValue;
2675 if (ParseAbsoluteExpression(ExprValue))
2676 return true;
2677
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002678 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002679 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002680
Sean Callanan79ed1a82010-01-19 20:22:31 +00002681 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002682 TheCondState.CondMet = ExprValue;
2683 TheCondState.Ignore = !TheCondState.CondMet;
2684 }
2685
2686 return false;
2687}
2688
2689/// ParseDirectiveElse
2690/// ::= .else
2691bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002692 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002693 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002694
Sean Callanan79ed1a82010-01-19 20:22:31 +00002695 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002696
2697 if (TheCondState.TheCond != AsmCond::IfCond &&
2698 TheCondState.TheCond != AsmCond::ElseIfCond)
2699 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2700 ".elseif");
2701 TheCondState.TheCond = AsmCond::ElseCond;
2702 bool LastIgnoreState = false;
2703 if (!TheCondStack.empty())
2704 LastIgnoreState = TheCondStack.back().Ignore;
2705 if (LastIgnoreState || TheCondState.CondMet)
2706 TheCondState.Ignore = true;
2707 else
2708 TheCondState.Ignore = false;
2709
2710 return false;
2711}
2712
2713/// ParseDirectiveEndIf
2714/// ::= .endif
2715bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002716 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002717 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002718
Sean Callanan79ed1a82010-01-19 20:22:31 +00002719 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002720
2721 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2722 TheCondStack.empty())
2723 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2724 ".else");
2725 if (!TheCondStack.empty()) {
2726 TheCondState = TheCondStack.back();
2727 TheCondStack.pop_back();
2728 }
2729
2730 return false;
2731}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002732
2733/// ParseDirectiveFile
Nick Lewycky44d798d2011-10-17 23:05:28 +00002734/// ::= .file [number] filename
2735/// ::= .file number directory filename
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002736bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002737 // FIXME: I'm not sure what this is.
2738 int64_t FileNumber = -1;
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002739 SMLoc FileNumberLoc = getLexer().getLoc();
Daniel Dunbareceec052010-07-12 17:45:27 +00002740 if (getLexer().is(AsmToken::Integer)) {
Sean Callanan18b83232010-01-19 21:44:56 +00002741 FileNumber = getTok().getIntVal();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002742 Lex();
Daniel Dunbareceec052010-07-12 17:45:27 +00002743
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002744 if (FileNumber < 1)
2745 return TokError("file number less than one");
2746 }
2747
Daniel Dunbareceec052010-07-12 17:45:27 +00002748 if (getLexer().isNot(AsmToken::String))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002749 return TokError("unexpected token in '.file' directive");
Daniel Dunbareceec052010-07-12 17:45:27 +00002750
Nick Lewycky44d798d2011-10-17 23:05:28 +00002751 // Usually the directory and filename together, otherwise just the directory.
2752 StringRef Path = getTok().getString();
2753 Path = Path.substr(1, Path.size()-2);
Sean Callanan79ed1a82010-01-19 20:22:31 +00002754 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002755
Nick Lewycky44d798d2011-10-17 23:05:28 +00002756 StringRef Directory;
2757 StringRef Filename;
2758 if (getLexer().is(AsmToken::String)) {
2759 if (FileNumber == -1)
2760 return TokError("explicit path specified, but no file number");
2761 Filename = getTok().getString();
2762 Filename = Filename.substr(1, Filename.size()-2);
2763 Directory = Path;
2764 Lex();
2765 } else {
2766 Filename = Path;
2767 }
2768
Daniel Dunbareceec052010-07-12 17:45:27 +00002769 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002770 return TokError("unexpected token in '.file' directive");
2771
Chris Lattnerd32e8032010-01-25 19:02:58 +00002772 if (FileNumber == -1)
Daniel Dunbareceec052010-07-12 17:45:27 +00002773 getStreamer().EmitFileDirective(Filename);
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002774 else {
Kevin Enderby8704b782012-01-11 18:04:47 +00002775 if (getContext().getGenDwarfForAssembly() == true)
2776 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2777 "used to generate dwarf debug info for assembly code");
2778
Nick Lewycky44d798d2011-10-17 23:05:28 +00002779 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002780 Error(FileNumberLoc, "file number already allocated");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002781 }
Daniel Dunbareceec052010-07-12 17:45:27 +00002782
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002783 return false;
2784}
2785
2786/// ParseDirectiveLine
2787/// ::= .line [number]
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002788bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbareceec052010-07-12 17:45:27 +00002789 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2790 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002791 return TokError("unexpected token in '.line' directive");
2792
Sean Callanan18b83232010-01-19 21:44:56 +00002793 int64_t LineNumber = getTok().getIntVal();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002794 (void) LineNumber;
Sean Callanan79ed1a82010-01-19 20:22:31 +00002795 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002796
2797 // FIXME: Do something with the .line.
2798 }
2799
Daniel Dunbareceec052010-07-12 17:45:27 +00002800 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar839348a2010-07-01 20:20:01 +00002801 return TokError("unexpected token in '.line' directive");
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002802
2803 return false;
2804}
2805
2806
2807/// ParseDirectiveLoc
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002808/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002809/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2810/// The first number is a file number, must have been previously assigned with
2811/// a .file directive, the second number is the line number and optionally the
2812/// third number is a column position (zero if not specified). The remaining
2813/// optional items are .loc sub-directives.
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002814bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002815
Daniel Dunbareceec052010-07-12 17:45:27 +00002816 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002817 return TokError("unexpected token in '.loc' directive");
Sean Callanan18b83232010-01-19 21:44:56 +00002818 int64_t FileNumber = getTok().getIntVal();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002819 if (FileNumber < 1)
2820 return TokError("file number less than one in '.loc' directive");
Kevin Enderby3f55c242010-10-04 20:17:24 +00002821 if (!getContext().isValidDwarfFileNumber(FileNumber))
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002822 return TokError("unassigned file number in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002823 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002824
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002825 int64_t LineNumber = 0;
2826 if (getLexer().is(AsmToken::Integer)) {
2827 LineNumber = getTok().getIntVal();
2828 if (LineNumber < 1)
2829 return TokError("line number less than one in '.loc' directive");
2830 Lex();
2831 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002832
2833 int64_t ColumnPos = 0;
2834 if (getLexer().is(AsmToken::Integer)) {
2835 ColumnPos = getTok().getIntVal();
2836 if (ColumnPos < 0)
2837 return TokError("column position less than zero in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002838 Lex();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002839 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002840
Kevin Enderbyc0957932010-09-30 16:52:03 +00002841 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002842 unsigned Isa = 0;
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002843 int64_t Discriminator = 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002844 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2845 for (;;) {
2846 if (getLexer().is(AsmToken::EndOfStatement))
2847 break;
2848
2849 StringRef Name;
2850 SMLoc Loc = getTok().getLoc();
2851 if (getParser().ParseIdentifier(Name))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002852 return TokError("unexpected token in '.loc' directive");
2853
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002854 if (Name == "basic_block")
2855 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2856 else if (Name == "prologue_end")
2857 Flags |= DWARF2_FLAG_PROLOGUE_END;
2858 else if (Name == "epilogue_begin")
2859 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2860 else if (Name == "is_stmt") {
2861 SMLoc Loc = getTok().getLoc();
2862 const MCExpr *Value;
2863 if (getParser().ParseExpression(Value))
2864 return true;
2865 // The expression must be the constant 0 or 1.
2866 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2867 int Value = MCE->getValue();
2868 if (Value == 0)
2869 Flags &= ~DWARF2_FLAG_IS_STMT;
2870 else if (Value == 1)
2871 Flags |= DWARF2_FLAG_IS_STMT;
2872 else
2873 return Error(Loc, "is_stmt value not 0 or 1");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002874 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002875 else {
2876 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2877 }
2878 }
2879 else if (Name == "isa") {
2880 SMLoc Loc = getTok().getLoc();
2881 const MCExpr *Value;
2882 if (getParser().ParseExpression(Value))
2883 return true;
2884 // The expression must be a constant greater or equal to 0.
2885 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2886 int Value = MCE->getValue();
2887 if (Value < 0)
2888 return Error(Loc, "isa number less than zero");
2889 Isa = Value;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002890 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002891 else {
2892 return Error(Loc, "isa number not a constant value");
2893 }
2894 }
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002895 else if (Name == "discriminator") {
2896 if (getParser().ParseAbsoluteExpression(Discriminator))
2897 return true;
2898 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002899 else {
2900 return Error(Loc, "unknown sub-directive in '.loc' directive");
2901 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002902
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002903 if (getLexer().is(AsmToken::EndOfStatement))
2904 break;
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002905 }
2906 }
2907
Rafael Espindolaaf6b58082010-11-16 21:20:32 +00002908 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
Devang Patel3f3bf932011-04-18 20:26:49 +00002909 Isa, Discriminator, StringRef());
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002910
2911 return false;
2912}
2913
Daniel Dunbar138abae2010-10-16 04:56:42 +00002914/// ParseDirectiveStabs
2915/// ::= .stabs string, number, number, number
2916bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2917 SMLoc DirectiveLoc) {
2918 return TokError("unsupported directive '" + Directive + "'");
2919}
2920
Rafael Espindolaf9efd832011-05-10 01:10:18 +00002921/// ParseDirectiveCFISections
2922/// ::= .cfi_sections section [, section]
2923bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2924 SMLoc DirectiveLoc) {
2925 StringRef Name;
2926 bool EH = false;
2927 bool Debug = false;
2928
2929 if (getParser().ParseIdentifier(Name))
2930 return TokError("Expected an identifier");
2931
2932 if (Name == ".eh_frame")
2933 EH = true;
2934 else if (Name == ".debug_frame")
2935 Debug = true;
2936
2937 if (getLexer().is(AsmToken::Comma)) {
2938 Lex();
2939
2940 if (getParser().ParseIdentifier(Name))
2941 return TokError("Expected an identifier");
2942
2943 if (Name == ".eh_frame")
2944 EH = true;
2945 else if (Name == ".debug_frame")
2946 Debug = true;
2947 }
2948
2949 getStreamer().EmitCFISections(EH, Debug);
2950
2951 return false;
2952}
2953
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002954/// ParseDirectiveCFIStartProc
2955/// ::= .cfi_startproc
2956bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2957 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002958 getStreamer().EmitCFIStartProc();
2959 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002960}
2961
2962/// ParseDirectiveCFIEndProc
2963/// ::= .cfi_endproc
2964bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002965 getStreamer().EmitCFIEndProc();
2966 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002967}
2968
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002969/// ParseRegisterOrRegisterNumber - parse register name or number.
2970bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2971 SMLoc DirectiveLoc) {
2972 unsigned RegNo;
2973
Jim Grosbach6f888a82011-06-02 17:14:04 +00002974 if (getLexer().isNot(AsmToken::Integer)) {
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002975 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2976 DirectiveLoc))
2977 return true;
Evan Cheng0e6a0522011-07-18 20:57:22 +00002978 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002979 } else
2980 return getParser().ParseAbsoluteExpression(Register);
Jim Grosbachde2f5f42011-02-11 19:05:56 +00002981
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002982 return false;
2983}
2984
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002985/// ParseDirectiveCFIDefCfa
2986/// ::= .cfi_def_cfa register, offset
2987bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2988 SMLoc DirectiveLoc) {
2989 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002990 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002991 return true;
2992
2993 if (getLexer().isNot(AsmToken::Comma))
2994 return TokError("unexpected token in directive");
2995 Lex();
2996
2997 int64_t Offset = 0;
2998 if (getParser().ParseAbsoluteExpression(Offset))
2999 return true;
3000
Rafael Espindola066c2f42011-04-12 23:59:07 +00003001 getStreamer().EmitCFIDefCfa(Register, Offset);
3002 return false;
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003003}
3004
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003005/// ParseDirectiveCFIDefCfaOffset
3006/// ::= .cfi_def_cfa_offset offset
3007bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3008 SMLoc DirectiveLoc) {
3009 int64_t Offset = 0;
3010 if (getParser().ParseAbsoluteExpression(Offset))
3011 return true;
3012
Rafael Espindola066c2f42011-04-12 23:59:07 +00003013 getStreamer().EmitCFIDefCfaOffset(Offset);
3014 return false;
Rafael Espindola53abbe52011-04-11 20:29:16 +00003015}
3016
3017/// ParseDirectiveCFIAdjustCfaOffset
3018/// ::= .cfi_adjust_cfa_offset adjustment
3019bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3020 SMLoc DirectiveLoc) {
3021 int64_t Adjustment = 0;
3022 if (getParser().ParseAbsoluteExpression(Adjustment))
3023 return true;
3024
Rafael Espindola5d7dcd32011-04-12 18:53:30 +00003025 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3026 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003027}
3028
3029/// ParseDirectiveCFIDefCfaRegister
3030/// ::= .cfi_def_cfa_register register
3031bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3032 SMLoc DirectiveLoc) {
3033 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003034 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003035 return true;
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003036
Rafael Espindola066c2f42011-04-12 23:59:07 +00003037 getStreamer().EmitCFIDefCfaRegister(Register);
3038 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003039}
3040
3041/// ParseDirectiveCFIOffset
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003042/// ::= .cfi_offset register, offset
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003043bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3044 int64_t Register = 0;
3045 int64_t Offset = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003046
3047 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003048 return true;
3049
3050 if (getLexer().isNot(AsmToken::Comma))
3051 return TokError("unexpected token in directive");
3052 Lex();
3053
3054 if (getParser().ParseAbsoluteExpression(Offset))
3055 return true;
3056
Rafael Espindola066c2f42011-04-12 23:59:07 +00003057 getStreamer().EmitCFIOffset(Register, Offset);
3058 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003059}
3060
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003061/// ParseDirectiveCFIRelOffset
3062/// ::= .cfi_rel_offset register, offset
3063bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3064 SMLoc DirectiveLoc) {
3065 int64_t Register = 0;
3066
3067 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3068 return true;
3069
3070 if (getLexer().isNot(AsmToken::Comma))
3071 return TokError("unexpected token in directive");
3072 Lex();
3073
3074 int64_t Offset = 0;
3075 if (getParser().ParseAbsoluteExpression(Offset))
3076 return true;
3077
Rafael Espindola25f492e2011-04-12 16:12:03 +00003078 getStreamer().EmitCFIRelOffset(Register, Offset);
3079 return false;
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003080}
3081
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003082static bool isValidEncoding(int64_t Encoding) {
3083 if (Encoding & ~0xff)
3084 return false;
3085
3086 if (Encoding == dwarf::DW_EH_PE_omit)
3087 return true;
3088
3089 const unsigned Format = Encoding & 0xf;
3090 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3091 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3092 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3093 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3094 return false;
3095
Rafael Espindolacaf11582010-12-29 04:31:26 +00003096 const unsigned Application = Encoding & 0x70;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003097 if (Application != dwarf::DW_EH_PE_absptr &&
Rafael Espindolacaf11582010-12-29 04:31:26 +00003098 Application != dwarf::DW_EH_PE_pcrel)
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003099 return false;
3100
3101 return true;
3102}
3103
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003104/// ParseDirectiveCFIPersonalityOrLsda
3105/// ::= .cfi_personality encoding, [symbol_name]
3106/// ::= .cfi_lsda encoding, [symbol_name]
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003107bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003108 SMLoc DirectiveLoc) {
3109 int64_t Encoding = 0;
3110 if (getParser().ParseAbsoluteExpression(Encoding))
3111 return true;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003112 if (Encoding == dwarf::DW_EH_PE_omit)
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003113 return false;
3114
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003115 if (!isValidEncoding(Encoding))
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003116 return TokError("unsupported encoding.");
3117
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003118 if (getLexer().isNot(AsmToken::Comma))
3119 return TokError("unexpected token in directive");
3120 Lex();
3121
3122 StringRef Name;
3123 if (getParser().ParseIdentifier(Name))
3124 return TokError("expected identifier in directive");
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003125
3126 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3127
3128 if (IDVal == ".cfi_personality")
Rafael Espindola066c2f42011-04-12 23:59:07 +00003129 getStreamer().EmitCFIPersonality(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003130 else {
3131 assert(IDVal == ".cfi_lsda");
Rafael Espindola066c2f42011-04-12 23:59:07 +00003132 getStreamer().EmitCFILsda(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003133 }
Rafael Espindola066c2f42011-04-12 23:59:07 +00003134 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003135}
3136
Rafael Espindolafe024d02010-12-28 18:36:23 +00003137/// ParseDirectiveCFIRememberState
3138/// ::= .cfi_remember_state
3139bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3140 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003141 getStreamer().EmitCFIRememberState();
3142 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003143}
3144
3145/// ParseDirectiveCFIRestoreState
3146/// ::= .cfi_remember_state
3147bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3148 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003149 getStreamer().EmitCFIRestoreState();
3150 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003151}
3152
Rafael Espindolac5754392011-04-12 15:31:05 +00003153/// ParseDirectiveCFISameValue
3154/// ::= .cfi_same_value register
3155bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3156 SMLoc DirectiveLoc) {
3157 int64_t Register = 0;
3158
3159 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3160 return true;
3161
3162 getStreamer().EmitCFISameValue(Register);
3163
3164 return false;
3165}
3166
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003167/// ParseDirectiveCFIRestore
3168/// ::= .cfi_restore register
3169bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003170 SMLoc DirectiveLoc) {
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003171 int64_t Register = 0;
3172 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3173 return true;
3174
3175 getStreamer().EmitCFIRestore(Register);
3176
3177 return false;
3178}
3179
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003180/// ParseDirectiveCFIEscape
3181/// ::= .cfi_escape expression[,...]
3182bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003183 SMLoc DirectiveLoc) {
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003184 std::string Values;
3185 int64_t CurrValue;
3186 if (getParser().ParseAbsoluteExpression(CurrValue))
3187 return true;
3188
3189 Values.push_back((uint8_t)CurrValue);
3190
3191 while (getLexer().is(AsmToken::Comma)) {
3192 Lex();
3193
3194 if (getParser().ParseAbsoluteExpression(CurrValue))
3195 return true;
3196
3197 Values.push_back((uint8_t)CurrValue);
3198 }
3199
3200 getStreamer().EmitCFIEscape(Values);
3201 return false;
3202}
3203
Rafael Espindola16d7d432012-01-23 21:51:52 +00003204/// ParseDirectiveCFISignalFrame
3205/// ::= .cfi_signal_frame
3206bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3207 SMLoc DirectiveLoc) {
3208 if (getLexer().isNot(AsmToken::EndOfStatement))
3209 return Error(getLexer().getLoc(),
3210 "unexpected token in '" + Directive + "' directive");
3211
3212 getStreamer().EmitCFISignalFrame();
3213
3214 return false;
3215}
3216
Daniel Dunbar3c802de2010-07-18 18:38:02 +00003217/// ParseDirectiveMacrosOnOff
3218/// ::= .macros_on
3219/// ::= .macros_off
3220bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3221 SMLoc DirectiveLoc) {
3222 if (getLexer().isNot(AsmToken::EndOfStatement))
3223 return Error(getLexer().getLoc(),
3224 "unexpected token in '" + Directive + "' directive");
3225
3226 getParser().MacrosEnabled = Directive == ".macros_on";
3227
3228 return false;
3229}
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003230
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003231/// ParseDirectiveMacro
Rafael Espindola65366442011-06-05 02:43:45 +00003232/// ::= .macro name [parameters]
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003233bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3234 SMLoc DirectiveLoc) {
3235 StringRef Name;
3236 if (getParser().ParseIdentifier(Name))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003237 return TokError("expected identifier in '.macro' directive");
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003238
Rafael Espindola8a403d32012-08-08 14:51:03 +00003239 MacroParameters Parameters;
Preston Gurd7b6f2032012-09-19 20:36:12 +00003240 // Argument delimiter is initially unknown. It will be set by
3241 // ParseMacroArgument()
3242 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindola65366442011-06-05 02:43:45 +00003243 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Rafael Espindola7996d042012-08-21 16:06:48 +00003244 for (;;) {
3245 MacroParameter Parameter;
Preston Gurd6c9176a2012-09-19 20:29:04 +00003246 if (getParser().ParseIdentifier(Parameter.first))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003247 return TokError("expected identifier in '.macro' directive");
Preston Gurd6c9176a2012-09-19 20:29:04 +00003248
3249 if (getLexer().is(AsmToken::Equal)) {
3250 Lex();
Preston Gurd7b6f2032012-09-19 20:36:12 +00003251 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
Preston Gurd6c9176a2012-09-19 20:29:04 +00003252 return true;
3253 }
3254
Rafael Espindola65366442011-06-05 02:43:45 +00003255 Parameters.push_back(Parameter);
3256
Preston Gurd7b6f2032012-09-19 20:36:12 +00003257 if (getLexer().is(AsmToken::Comma))
3258 Lex();
3259 else if (getLexer().is(AsmToken::EndOfStatement))
Rafael Espindola65366442011-06-05 02:43:45 +00003260 break;
Rafael Espindola65366442011-06-05 02:43:45 +00003261 }
3262 }
3263
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003264 // Eat the end of statement.
3265 Lex();
3266
3267 AsmToken EndToken, StartToken = getTok();
3268
3269 // Lex the macro definition.
3270 for (;;) {
3271 // Check whether we have reached the end of the file.
3272 if (getLexer().is(AsmToken::Eof))
3273 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3274
3275 // Otherwise, check whether we have reach the .endmacro.
3276 if (getLexer().is(AsmToken::Identifier) &&
3277 (getTok().getIdentifier() == ".endm" ||
3278 getTok().getIdentifier() == ".endmacro")) {
3279 EndToken = getTok();
3280 Lex();
3281 if (getLexer().isNot(AsmToken::EndOfStatement))
3282 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3283 "' directive");
3284 break;
3285 }
3286
3287 // Otherwise, scan til the end of the statement.
3288 getParser().EatToEndOfStatement();
3289 }
3290
3291 if (getParser().MacroMap.lookup(Name)) {
3292 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3293 }
3294
3295 const char *BodyStart = StartToken.getLoc().getPointer();
3296 const char *BodyEnd = EndToken.getLoc().getPointer();
3297 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Rafael Espindola65366442011-06-05 02:43:45 +00003298 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003299 return false;
3300}
3301
3302/// ParseDirectiveEndMacro
3303/// ::= .endm
3304/// ::= .endmacro
3305bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
Rafael Espindola8a403d32012-08-08 14:51:03 +00003306 SMLoc DirectiveLoc) {
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003307 if (getLexer().isNot(AsmToken::EndOfStatement))
3308 return TokError("unexpected token in '" + Directive + "' directive");
3309
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00003310 // If we are inside a macro instantiation, terminate the current
3311 // instantiation.
3312 if (!getParser().ActiveMacros.empty()) {
3313 getParser().HandleMacroExit();
3314 return false;
3315 }
3316
3317 // Otherwise, this .endmacro is a stray entry in the file; well formed
3318 // .endmacro directives are handled during the macro definition parsing.
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003319 return TokError("unexpected '" + Directive + "' in file, "
3320 "no current macro definition");
3321}
3322
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +00003323/// ParseDirectivePurgeMacro
3324/// ::= .purgem
3325bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3326 SMLoc DirectiveLoc) {
3327 StringRef Name;
3328 if (getParser().ParseIdentifier(Name))
3329 return TokError("expected identifier in '.purgem' directive");
3330
3331 if (getLexer().isNot(AsmToken::EndOfStatement))
3332 return TokError("unexpected token in '.purgem' directive");
3333
3334 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3335 if (I == getParser().MacroMap.end())
3336 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3337
3338 // Undefine the macro.
3339 delete I->getValue();
3340 getParser().MacroMap.erase(I);
3341 return false;
3342}
3343
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003344bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
Rafael Espindola3ff57092010-11-02 17:22:24 +00003345 getParser().CheckForValidSection();
3346
3347 const MCExpr *Value;
3348
3349 if (getParser().ParseExpression(Value))
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003350 return true;
3351
3352 if (getLexer().isNot(AsmToken::EndOfStatement))
3353 return TokError("unexpected token in directive");
3354
3355 if (DirName[1] == 's')
Rafael Espindola3ff57092010-11-02 17:22:24 +00003356 getStreamer().EmitSLEB128Value(Value);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003357 else
Rafael Espindola3ff57092010-11-02 17:22:24 +00003358 getStreamer().EmitULEB128Value(Value);
3359
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003360 return false;
3361}
3362
Rafael Espindola761cb062012-06-03 23:57:14 +00003363Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003364 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003365
Rafael Espindola761cb062012-06-03 23:57:14 +00003366 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003367 for (;;) {
3368 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003369 if (getLexer().is(AsmToken::Eof)) {
3370 Error(DirectiveLoc, "no matching '.endr' in definition");
3371 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003372 }
3373
Rafael Espindola761cb062012-06-03 23:57:14 +00003374 if (Lexer.is(AsmToken::Identifier) &&
3375 (getTok().getIdentifier() == ".rept")) {
3376 ++NestLevel;
3377 }
3378
3379 // Otherwise, check whether we have reached the .endr.
3380 if (Lexer.is(AsmToken::Identifier) &&
3381 getTok().getIdentifier() == ".endr") {
3382 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003383 EndToken = getTok();
3384 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003385 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3386 TokError("unexpected token in '.endr' directive");
3387 return 0;
3388 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003389 break;
3390 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003391 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003392 }
3393
Rafael Espindola761cb062012-06-03 23:57:14 +00003394 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003395 EatToEndOfStatement();
3396 }
3397
3398 const char *BodyStart = StartToken.getLoc().getPointer();
3399 const char *BodyEnd = EndToken.getLoc().getPointer();
3400 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3401
Rafael Espindola761cb062012-06-03 23:57:14 +00003402 // We Are Anonymous.
3403 StringRef Name;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003404 MacroParameters Parameters;
Rafael Espindola761cb062012-06-03 23:57:14 +00003405 return new Macro(Name, Body, Parameters);
3406}
3407
3408void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3409 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003410 OS << ".endr\n";
3411
3412 MemoryBuffer *Instantiation =
3413 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3414
Rafael Espindola761cb062012-06-03 23:57:14 +00003415 // Create the macro instantiation object and add to the current macro
3416 // instantiation stack.
3417 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3418 getTok().getLoc(),
3419 Instantiation);
3420 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003421
Rafael Espindola761cb062012-06-03 23:57:14 +00003422 // Jump to the macro instantiation and prime the lexer.
3423 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3424 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3425 Lex();
3426}
3427
3428bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3429 int64_t Count;
3430 if (ParseAbsoluteExpression(Count))
3431 return TokError("unexpected token in '.rept' directive");
3432
3433 if (Count < 0)
3434 return TokError("Count is negative");
3435
3436 if (Lexer.isNot(AsmToken::EndOfStatement))
3437 return TokError("unexpected token in '.rept' directive");
3438
3439 // Eat the end of statement.
3440 Lex();
3441
3442 // Lex the rept definition.
3443 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3444 if (!M)
3445 return true;
3446
3447 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3448 // to hold the macro body with substitutions.
3449 SmallString<256> Buf;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003450 MacroParameters Parameters;
3451 MacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003452 raw_svector_ostream OS(Buf);
3453 while (Count--) {
3454 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3455 return true;
3456 }
3457 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003458
3459 return false;
3460}
3461
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003462/// ParseDirectiveIrp
3463/// ::= .irp symbol,values
3464bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003465 MacroParameters Parameters;
3466 MacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003467
Preston Gurd6c9176a2012-09-19 20:29:04 +00003468 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003469 return TokError("expected identifier in '.irp' directive");
3470
3471 Parameters.push_back(Parameter);
3472
3473 if (Lexer.isNot(AsmToken::Comma))
3474 return TokError("expected comma in '.irp' directive");
3475
3476 Lex();
3477
Rafael Espindola8a403d32012-08-08 14:51:03 +00003478 MacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003479 if (ParseMacroArguments(0, A))
3480 return true;
3481
3482 // Eat the end of statement.
3483 Lex();
3484
3485 // Lex the irp definition.
3486 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3487 if (!M)
3488 return true;
3489
3490 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3491 // to hold the macro body with substitutions.
3492 SmallString<256> Buf;
3493 raw_svector_ostream OS(Buf);
3494
Rafael Espindola7996d042012-08-21 16:06:48 +00003495 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3496 MacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003497 Args.push_back(*i);
3498
3499 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3500 return true;
3501 }
3502
3503 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3504
3505 return false;
3506}
3507
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003508/// ParseDirectiveIrpc
3509/// ::= .irpc symbol,values
3510bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003511 MacroParameters Parameters;
3512 MacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003513
Preston Gurd6c9176a2012-09-19 20:29:04 +00003514 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003515 return TokError("expected identifier in '.irpc' directive");
3516
3517 Parameters.push_back(Parameter);
3518
3519 if (Lexer.isNot(AsmToken::Comma))
3520 return TokError("expected comma in '.irpc' directive");
3521
3522 Lex();
3523
Rafael Espindola8a403d32012-08-08 14:51:03 +00003524 MacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003525 if (ParseMacroArguments(0, A))
3526 return true;
3527
3528 if (A.size() != 1 || A.front().size() != 1)
3529 return TokError("unexpected token in '.irpc' directive");
3530
3531 // Eat the end of statement.
3532 Lex();
3533
3534 // Lex the irpc definition.
3535 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3536 if (!M)
3537 return true;
3538
3539 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3540 // to hold the macro body with substitutions.
3541 SmallString<256> Buf;
3542 raw_svector_ostream OS(Buf);
3543
3544 StringRef Values = A.front().front().getString();
3545 std::size_t I, End = Values.size();
3546 for (I = 0; I < End; ++I) {
3547 MacroArgument Arg;
3548 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3549
Rafael Espindola8a403d32012-08-08 14:51:03 +00003550 MacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003551 Args.push_back(Arg);
3552
3553 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3554 return true;
3555 }
3556
3557 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3558
3559 return false;
3560}
3561
Rafael Espindola761cb062012-06-03 23:57:14 +00003562bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3563 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003564 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003565
3566 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003567 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003568 assert(getLexer().is(AsmToken::EndOfStatement));
3569
Rafael Espindola761cb062012-06-03 23:57:14 +00003570 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003571 return false;
3572}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003573
Chad Rosierb1f8c132012-10-18 15:49:34 +00003574namespace {
3575enum AsmOpRewriteKind {
3576 AOK_Imm,
3577 AOK_Input,
3578 AOK_Output
3579};
3580
3581struct AsmOpRewrite {
3582 AsmOpRewriteKind Kind;
3583 SMLoc Loc;
3584 unsigned Len;
3585
3586public:
3587 AsmOpRewrite(AsmOpRewriteKind kind, SMLoc loc, unsigned len)
3588 : Kind(kind), Loc(loc), Len(len) { }
3589};
3590}
3591
3592bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3593 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003594 SmallVectorImpl<void *> &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003595 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003596 SmallVectorImpl<std::string> &Clobbers,
3597 const MCInstrInfo *MII,
3598 const MCInstPrinter *IP,
3599 MCAsmParserSemaCallback &SI) {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003600 SmallVector<void*, 4> InputDecls;
3601 SmallVector<void*, 4> OutputDecls;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003602 SmallVector<std::string, 4> InputConstraints;
3603 SmallVector<std::string, 4> OutputConstraints;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003604 std::set<std::string> ClobberRegs;
3605
3606 SmallVector<struct AsmOpRewrite, 4> AsmStrRewrites;
3607
3608 // Prime the lexer.
3609 Lex();
3610
3611 // While we have input, parse each statement.
3612 unsigned InputIdx = 0;
3613 unsigned OutputIdx = 0;
3614 while (getLexer().isNot(AsmToken::Eof)) {
3615 if (ParseStatement()) return true;
3616
3617 if (isInstruction()) {
3618 const MCInstrDesc &Desc = MII->get(getOpcode());
3619
3620 // Build the list of clobbers, outputs and inputs.
3621 for (unsigned i = 1, e = ParsedOperands.size(); i != e; ++i) {
3622 MCParsedAsmOperand *Operand = ParsedOperands[i];
3623
3624 // Immediate.
3625 if (Operand->isImm()) {
3626 AsmStrRewrites.push_back(AsmOpRewrite(AOK_Imm,
3627 Operand->getStartLoc(),
3628 Operand->getNameLen()));
3629 continue;
3630 }
3631
3632 // Register operand.
3633 if (Operand->isReg()) {
3634 unsigned NumDefs = Desc.getNumDefs();
3635 // Clobber.
3636 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3637 std::string Reg;
3638 raw_string_ostream OS(Reg);
3639 IP->printRegName(OS, Operand->getReg());
3640 ClobberRegs.insert(StringRef(OS.str()));
3641 }
3642 continue;
3643 }
3644
3645 // Expr/Input or Output.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003646 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc);
3647 if (OpDecl) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003648 bool isOutput = (i == 1) && Desc.mayStore();
3649 if (isOutput) {
3650 std::string Constraint = "=";
3651 ++InputIdx;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003652 OutputDecls.push_back(OpDecl);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003653 Constraint += Operand->getConstraint().str();
3654 OutputConstraints.push_back(Constraint);
3655 AsmStrRewrites.push_back(AsmOpRewrite(AOK_Output,
3656 Operand->getStartLoc(),
3657 Operand->getNameLen()));
3658 } else {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003659 InputDecls.push_back(OpDecl);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003660 InputConstraints.push_back(Operand->getConstraint().str());
3661 AsmStrRewrites.push_back(AsmOpRewrite(AOK_Input,
3662 Operand->getStartLoc(),
3663 Operand->getNameLen()));
3664 }
3665 }
3666 }
3667 // Free any parsed operands.
3668 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
3669 delete ParsedOperands[i];
3670 ParsedOperands.clear();
3671 }
3672 }
3673
3674 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003675 NumOutputs = OutputDecls.size();
3676 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00003677
3678 // Set the unique clobbers.
3679 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3680 E = ClobberRegs.end(); I != E; ++I)
3681 Clobbers.push_back(*I);
3682
3683 // Merge the various outputs and inputs. Output are expected first.
3684 if (NumOutputs || NumInputs) {
3685 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003686 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003687 Constraints.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003688 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003689 OpDecls[i] = OutputDecls[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003690 Constraints[i] = OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003691 }
3692 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003693 OpDecls[j] = InputDecls[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003694 Constraints[j] = InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003695 }
3696 }
3697
3698 // Build the IR assembly string.
3699 std::string AsmStringIR;
3700 raw_string_ostream OS(AsmStringIR);
3701 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
3702 for (SmallVectorImpl<struct AsmOpRewrite>::iterator
3703 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3704 const char *Loc = (*I).Loc.getPointer();
3705
3706 // Emit everything up to the immediate/expression.
3707 OS << StringRef(Start, Loc - Start);
3708
3709 // Rewrite expressions in $N notation.
3710 switch ((*I).Kind) {
3711 case AOK_Imm:
3712 OS << Twine("$$") + StringRef(Loc, (*I).Len);
3713 break;
3714 case AOK_Input:
3715 OS << '$';
3716 OS << InputIdx++;
3717 break;
3718 case AOK_Output:
3719 OS << '$';
3720 OS << OutputIdx++;
3721 break;
3722 }
3723
3724 // Skip the original expression.
3725 Start = Loc + (*I).Len;
3726 }
3727
3728 // Emit the remainder of the asm string.
3729 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
3730 if (Start != AsmEnd)
3731 OS << StringRef(Start, AsmEnd - Start);
3732
3733 AsmString = OS.str();
3734 return false;
3735}
3736
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003737/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003738MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003739 MCContext &C, MCStreamer &Out,
3740 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003741 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003742}