blob: 7be86fdba6d7990539fdba7ebb8e4ea06d5aff15 [file] [log] [blame]
Chris Lattner27aa7d22009-06-21 20:16:42 +00001//===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This class implements the parser for assembly files.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbarb95a0792010-09-24 01:59:56 +000014#include "llvm/ADT/APFloat.h"
Daniel Dunbar7c0a3342009-08-26 22:49:51 +000015#include "llvm/ADT/SmallString.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000016#include "llvm/ADT/StringMap.h"
Daniel Dunbarf9507ff2009-07-27 23:20:52 +000017#include "llvm/ADT/Twine.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000018#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000019#include "llvm/MC/MCContext.h"
Evan Cheng94b95502011-07-26 00:24:13 +000020#include "llvm/MC/MCDwarf.h"
Daniel Dunbar28c251b2009-08-31 08:06:59 +000021#include "llvm/MC/MCExpr.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000022#include "llvm/MC/MCParser/AsmCond.h"
23#include "llvm/MC/MCParser/AsmLexer.h"
24#include "llvm/MC/MCParser/MCAsmParser.h"
25#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Evan Chenge76a33b2011-07-20 05:58:47 +000026#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000027#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000028#include "llvm/MC/MCStreamer.h"
Daniel Dunbardce0f3c2009-06-29 23:43:14 +000029#include "llvm/MC/MCSymbol.h"
Evan Cheng94b95502011-07-26 00:24:13 +000030#include "llvm/MC/MCTargetAsmParser.h"
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000031#include "llvm/Support/CommandLine.h"
Benjamin Kramer518ff562012-01-28 15:28:41 +000032#include "llvm/Support/ErrorHandling.h"
Jim Grosbach254cf032011-06-29 16:05:14 +000033#include "llvm/Support/MathExtras.h"
Kevin Enderbyf187ac52010-06-28 21:45:58 +000034#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000035#include "llvm/Support/SourceMgr.h"
Chris Lattnerb0789ed2009-06-21 20:54:55 +000036#include "llvm/Support/raw_ostream.h"
Nick Lewycky476b2422010-12-19 20:43:38 +000037#include <cctype>
Daniel Dunbaraef87e32010-07-18 18:31:38 +000038#include <vector>
Chris Lattner27aa7d22009-06-21 20:16:42 +000039using namespace llvm;
40
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000041static cl::opt<bool>
42FatalAssemblerWarnings("fatal-assembler-warnings",
43 cl::desc("Consider warnings as error"));
44
Daniel Dunbar81ea00f2010-07-12 17:54:38 +000045namespace {
46
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000047/// \brief Helper class for tracking macro definitions.
48struct Macro {
49 StringRef Name;
50 StringRef Body;
Rafael Espindola65366442011-06-05 02:43:45 +000051 std::vector<StringRef> Parameters;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000052
53public:
Rafael Espindola65366442011-06-05 02:43:45 +000054 Macro(StringRef N, StringRef B, const std::vector<StringRef> &P) :
55 Name(N), Body(B), Parameters(P) {}
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000056};
57
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000058/// \brief Helper class for storing information about an active macro
59/// instantiation.
60struct MacroInstantiation {
61 /// The macro being instantiated.
62 const Macro *TheMacro;
63
64 /// The macro instantiation with substitutions.
65 MemoryBuffer *Instantiation;
66
67 /// The location of the instantiation.
68 SMLoc InstantiationLoc;
69
70 /// The location where parsing should resume upon instantiation completion.
71 SMLoc ExitLoc;
72
73public:
Daniel Dunbar7a570d02010-07-18 19:00:10 +000074 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000075 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000076};
77
Daniel Dunbaraef87e32010-07-18 18:31:38 +000078/// \brief The concrete assembly parser instance.
79class AsmParser : public MCAsmParser {
Daniel Dunbar3c802de2010-07-18 18:38:02 +000080 friend class GenericAsmParser;
81
Daniel Dunbaraef87e32010-07-18 18:31:38 +000082 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
83 void operator=(const AsmParser &); // DO NOT IMPLEMENT
84private:
85 AsmLexer Lexer;
86 MCContext &Ctx;
87 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +000088 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +000089 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +000090 SourceMgr::DiagHandlerTy SavedDiagHandler;
91 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +000092 MCAsmParserExtension *GenericParser;
93 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +000094
Daniel Dunbaraef87e32010-07-18 18:31:38 +000095 /// This is the current buffer index we're lexing from as managed by the
96 /// SourceMgr object.
97 int CurBuffer;
98
99 AsmCond TheCondState;
100 std::vector<AsmCond> TheCondStack;
101
102 /// DirectiveMap - This is a table handlers for directives. Each handler is
103 /// invoked after the directive identifier is read and is responsible for
104 /// parsing and validating the rest of the directive. The handler is passed
105 /// in the directive name and the location of the directive keyword.
106 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000107
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000108 /// MacroMap - Map of currently defined macros.
109 StringMap<Macro*> MacroMap;
110
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000111 /// ActiveMacros - Stack of active macro instantiations.
112 std::vector<MacroInstantiation*> ActiveMacros;
113
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000114 /// ActiveRept - Stack of active .rept directives.
115 std::vector<SMLoc> ActiveRept;
116
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000117 /// Boolean tracking whether macro substitution is enabled.
118 unsigned MacrosEnabled : 1;
119
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000120 /// Flag tracking whether any errors have been encountered.
121 unsigned HadError : 1;
122
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000123 /// The values from the last parsed cpp hash file line comment if any.
124 StringRef CppHashFilename;
125 int64_t CppHashLineNumber;
126 SMLoc CppHashLoc;
127
Devang Patel0db58bf2012-01-31 18:14:05 +0000128 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
129 unsigned AssemblerDialect;
130
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000131public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000132 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000133 const MCAsmInfo &MAI);
134 ~AsmParser();
135
136 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
137
138 void AddDirectiveHandler(MCAsmParserExtension *Object,
139 StringRef Directive,
140 DirectiveHandler Handler) {
141 DirectiveMap[Directive] = std::make_pair(Object, Handler);
142 }
143
144public:
145 /// @name MCAsmParser Interface
146 /// {
147
148 virtual SourceMgr &getSourceManager() { return SrcMgr; }
149 virtual MCAsmLexer &getLexer() { return Lexer; }
150 virtual MCContext &getContext() { return Ctx; }
151 virtual MCStreamer &getStreamer() { return Out; }
Devang Patel0db58bf2012-01-31 18:14:05 +0000152 virtual unsigned getAssemblerDialect() {
153 if (AssemblerDialect == ~0U)
154 return MAI.getAssemblerDialect();
155 else
156 return AssemblerDialect;
157 }
158 virtual void setAssemblerDialect(unsigned i) {
159 AssemblerDialect = i;
160 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000161
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000162 virtual bool Warning(SMLoc L, const Twine &Msg,
163 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
164 virtual bool Error(SMLoc L, const Twine &Msg,
165 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000166
167 const AsmToken &Lex();
168
169 bool ParseExpression(const MCExpr *&Res);
170 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
171 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
172 virtual bool ParseAbsoluteExpression(int64_t &Res);
173
174 /// }
175
176private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000177 void CheckForValidSection();
178
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000179 bool ParseStatement();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000180 void EatToEndOfLine();
181 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000182
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000183 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
Rafael Espindola65366442011-06-05 02:43:45 +0000184 bool expandMacro(SmallString<256> &Buf, StringRef Body,
185 const std::vector<StringRef> &Parameters,
186 const std::vector<std::vector<AsmToken> > &A,
187 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000188 void HandleMacroExit();
189
190 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000191 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000192 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
193 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000194 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000195 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000196
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000197 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
198 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000199 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
200 /// This returns true on failure.
201 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000202
203 /// \brief Reset the current lexer position to that given by \arg Loc. The
204 /// current token is not set; clients should ensure Lex() is called
205 /// subsequently.
206 void JumpToLoc(SMLoc Loc);
207
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000208 void EatToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000209
210 /// \brief Parse up to the end of statement and a return the contents from the
211 /// current token until the end of the statement; the current token on exit
212 /// will be either the EndOfStatement or EOF.
213 StringRef ParseStringToEndOfStatement();
214
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000215 /// \brief Parse until the end of a statement or a comma is encountered,
216 /// return the contents from the current token up to the end or comma.
217 StringRef ParseStringToComma();
218
Nico Weber4c4c7322011-01-28 03:04:41 +0000219 bool ParseAssignment(StringRef Name, bool allow_redef);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000220
221 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
222 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
223 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000224 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000225
226 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
227 /// and set \arg Res to the identifier contents.
228 bool ParseIdentifier(StringRef &Res);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000229
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000230 // Directive Parsing.
Rafael Espindola787c3372010-10-28 20:02:27 +0000231
232 // ".ascii", ".asciiz", ".string"
233 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000234 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000235 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000236 bool ParseDirectiveFill(); // ".fill"
237 bool ParseDirectiveSpace(); // ".space"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000238 bool ParseDirectiveZero(); // ".zero"
Nico Weber4c4c7322011-01-28 03:04:41 +0000239 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000240 bool ParseDirectiveOrg(); // ".org"
241 // ".align{,32}", ".p2align{,w,l}"
242 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
243
244 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
245 /// accepts a single symbol (which should be a label or an external).
246 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000247
248 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
249
250 bool ParseDirectiveAbort(); // ".abort"
251 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000252 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000253
254 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000255 // ".ifb" or ".ifnb", depending on ExpectBlank.
256 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000257 // ".ifc" or ".ifnc", depending on ExpectEqual.
258 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000259 // ".ifdef" or ".ifndef", depending on expect_defined
260 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000261 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
262 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
263 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
264
265 /// ParseEscapedString - Parse the current token as a string which may include
266 /// escaped characters and return the string contents.
267 bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000268
269 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
270 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000271
272 bool ParseDirectiveRept(SMLoc DirectiveLoc);
273 bool ParseDirectiveEndRept(SMLoc DirectiveLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000274};
275
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000276/// \brief Generic implementations of directive handling, etc. which is shared
277/// (or the default, at least) for all assembler parser.
278class GenericAsmParser : public MCAsmParserExtension {
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000279 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
280 void AddDirectiveHandler(StringRef Directive) {
281 getParser().AddDirectiveHandler(this, Directive,
282 HandleDirective<GenericAsmParser, Handler>);
283 }
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000284public:
285 GenericAsmParser() {}
286
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000287 AsmParser &getParser() {
288 return (AsmParser&) this->MCAsmParserExtension::getParser();
289 }
290
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000291 virtual void Initialize(MCAsmParser &Parser) {
292 // Call the base implementation.
293 this->MCAsmParserExtension::Initialize(Parser);
294
295 // Debugging directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000296 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
297 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
298 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
Daniel Dunbar138abae2010-10-16 04:56:42 +0000299 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000300
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000301 // CFI directives.
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000302 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
303 ".cfi_sections");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000304 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
305 ".cfi_startproc");
306 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
307 ".cfi_endproc");
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000308 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
309 ".cfi_def_cfa");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000310 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
311 ".cfi_def_cfa_offset");
Rafael Espindola53abbe52011-04-11 20:29:16 +0000312 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
313 ".cfi_adjust_cfa_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000314 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
315 ".cfi_def_cfa_register");
316 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
317 ".cfi_offset");
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000318 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
319 ".cfi_rel_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000320 AddDirectiveHandler<
321 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
322 AddDirectiveHandler<
323 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
Rafael Espindolafe024d02010-12-28 18:36:23 +0000324 AddDirectiveHandler<
325 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
326 AddDirectiveHandler<
327 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
Rafael Espindolac5754392011-04-12 15:31:05 +0000328 AddDirectiveHandler<
329 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000330 AddDirectiveHandler<
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000331 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
332 AddDirectiveHandler<
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000333 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
Rafael Espindola16d7d432012-01-23 21:51:52 +0000334 AddDirectiveHandler<
335 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000336
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000337 // Macro directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000338 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
339 ".macros_on");
340 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
341 ".macros_off");
342 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
343 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
344 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000345 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000346
347 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
348 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000349 }
350
Roman Divacky54b0f4f2011-01-27 17:16:37 +0000351 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
352
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000353 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
354 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
355 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar138abae2010-10-16 04:56:42 +0000356 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000357 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000358 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
359 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000360 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000361 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola53abbe52011-04-11 20:29:16 +0000362 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000363 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
364 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000365 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000366 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
Rafael Espindolafe024d02010-12-28 18:36:23 +0000367 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
368 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac5754392011-04-12 15:31:05 +0000369 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000370 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000371 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
Rafael Espindola16d7d432012-01-23 21:51:52 +0000372 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000373
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000374 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000375 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
376 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000377 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000378
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000379 bool ParseDirectiveLEB128(StringRef, SMLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000380};
381
382}
383
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000384namespace llvm {
385
386extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000387extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000388extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000389
390}
391
Chris Lattneraaec2052010-01-19 19:46:13 +0000392enum { DEFAULT_ADDRSPACE = 0 };
393
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000394AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000395 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000396 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Rafael Espindola5d7dcd32011-04-12 18:53:30 +0000397 GenericParser(new GenericAsmParser), PlatformParser(0),
Devang Patel0db58bf2012-01-31 18:14:05 +0000398 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
399 AssemblerDialect(~0U) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000400 // Save the old handler.
401 SavedDiagHandler = SrcMgr.getDiagHandler();
402 SavedDiagContext = SrcMgr.getDiagContext();
403 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000404 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000405 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000406
407 // Initialize the generic parser.
408 GenericParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000409
410 // Initialize the platform / file format parser.
411 //
412 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
413 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000414 if (_MAI.hasMicrosoftFastStdCallMangling()) {
415 PlatformParser = createCOFFAsmParser();
416 PlatformParser->Initialize(*this);
417 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000418 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000419 PlatformParser->Initialize(*this);
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000420 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000421 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000422 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000423 }
Chris Lattnerebb89b42009-09-27 21:16:52 +0000424}
425
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000426AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000427 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
428
429 // Destroy any macros.
430 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
431 ie = MacroMap.end(); it != ie; ++it)
432 delete it->getValue();
433
Daniel Dunbare4749702010-07-12 18:12:02 +0000434 delete PlatformParser;
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000435 delete GenericParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000436}
437
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000438void AsmParser::PrintMacroInstantiations() {
439 // Print the active macro instantiation stack.
440 for (std::vector<MacroInstantiation*>::const_reverse_iterator
441 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000442 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
443 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000444}
445
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000446bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000447 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000448 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000449 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000450 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000451 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000452}
453
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000454bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000455 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000456 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000457 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000458 return true;
459}
460
Sean Callananfd0b0282010-01-21 00:19:58 +0000461bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000462 std::string IncludedFile;
463 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000464 if (NewBuf == -1)
465 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000466
Sean Callananfd0b0282010-01-21 00:19:58 +0000467 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000468
Sean Callananfd0b0282010-01-21 00:19:58 +0000469 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000470
Sean Callananfd0b0282010-01-21 00:19:58 +0000471 return false;
472}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000473
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000474/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000475/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000476/// returns true on failure.
477bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
478 std::string IncludedFile;
479 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
480 if (NewBuf == -1)
481 return true;
482
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000483 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000484 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
485 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000486 return false;
487}
488
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000489void AsmParser::JumpToLoc(SMLoc Loc) {
490 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
491 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
492}
493
Sean Callananfd0b0282010-01-21 00:19:58 +0000494const AsmToken &AsmParser::Lex() {
495 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000496
Sean Callananfd0b0282010-01-21 00:19:58 +0000497 if (tok->is(AsmToken::Eof)) {
498 // If this is the end of an included file, pop the parent file off the
499 // include stack.
500 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
501 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000502 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000503 tok = &Lexer.Lex();
504 }
505 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000506
Sean Callananfd0b0282010-01-21 00:19:58 +0000507 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000508 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000509
Sean Callananfd0b0282010-01-21 00:19:58 +0000510 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000511}
512
Chris Lattner79180e22010-04-05 23:15:42 +0000513bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000514 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000515 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000516 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000517
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000518 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000519 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000520
521 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000522 AsmCond StartingCondState = TheCondState;
523
Kevin Enderby613b7572011-11-01 22:27:22 +0000524 // If we are generating dwarf for assembly source files save the initial text
525 // section and generate a .file directive.
526 if (getContext().getGenDwarfForAssembly()) {
527 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000528 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
529 getStreamer().EmitLabel(SectionStartSym);
530 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000531 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
532 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
533 }
534
Chris Lattnerb717fb02009-07-02 21:53:43 +0000535 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000536 while (Lexer.isNot(AsmToken::Eof)) {
Chris Lattnerb717fb02009-07-02 21:53:43 +0000537 if (!ParseStatement()) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000538
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000539 // We had an error, validate that one was emitted and recover by skipping to
540 // the next line.
541 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000542 EatToEndOfStatement();
543 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000544
545 if (TheCondState.TheCond != StartingCondState.TheCond ||
546 TheCondState.Ignore != StartingCondState.Ignore)
547 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000548
549 // Check to see there are no empty DwarfFile slots.
550 const std::vector<MCDwarfFile *> &MCDwarfFiles =
551 getContext().getMCDwarfFiles();
552 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000553 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000554 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000555 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000556
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000557 // Check to see that all assembler local symbols were actually defined.
558 // Targets that don't do subsections via symbols may not want this, though,
559 // so conservatively exclude them. Only do this if we're finalizing, though,
560 // as otherwise we won't necessarilly have seen everything yet.
561 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
562 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
563 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
564 e = Symbols.end();
565 i != e; ++i) {
566 MCSymbol *Sym = i->getValue();
567 // Variable symbols may not be marked as defined, so check those
568 // explicitly. If we know it's a variable, we have a definition for
569 // the purposes of this check.
570 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
571 // FIXME: We would really like to refer back to where the symbol was
572 // first referenced for a source location. We need to add something
573 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000574 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
575 "assembler local symbol '" + Sym->getName() +
576 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000577 }
578 }
579
580
Chris Lattner79180e22010-04-05 23:15:42 +0000581 // Finalize the output stream if there are no errors and if the client wants
582 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000583 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000584 Out.Finish();
585
Chris Lattnerb717fb02009-07-02 21:53:43 +0000586 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000587}
588
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000589void AsmParser::CheckForValidSection() {
590 if (!getStreamer().getCurrentSection()) {
591 TokError("expected section directive before assembly directive");
592 Out.SwitchSection(Ctx.getMachOSection(
593 "__TEXT", "__text",
594 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
595 0, SectionKind::getText()));
596 }
597}
598
Chris Lattner2cf5f142009-06-22 01:29:09 +0000599/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
600void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000601 while (Lexer.isNot(AsmToken::EndOfStatement) &&
602 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000603 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000604
Chris Lattner2cf5f142009-06-22 01:29:09 +0000605 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000606 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000607 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000608}
609
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000610StringRef AsmParser::ParseStringToEndOfStatement() {
611 const char *Start = getTok().getLoc().getPointer();
612
613 while (Lexer.isNot(AsmToken::EndOfStatement) &&
614 Lexer.isNot(AsmToken::Eof))
615 Lex();
616
617 const char *End = getTok().getLoc().getPointer();
618 return StringRef(Start, End - Start);
619}
Chris Lattnerc4193832009-06-22 05:51:26 +0000620
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000621StringRef AsmParser::ParseStringToComma() {
622 const char *Start = getTok().getLoc().getPointer();
623
624 while (Lexer.isNot(AsmToken::EndOfStatement) &&
625 Lexer.isNot(AsmToken::Comma) &&
626 Lexer.isNot(AsmToken::Eof))
627 Lex();
628
629 const char *End = getTok().getLoc().getPointer();
630 return StringRef(Start, End - Start);
631}
632
Chris Lattner74ec1a32009-06-22 06:32:03 +0000633/// ParseParenExpr - Parse a paren expression and return it.
634/// NOTE: This assumes the leading '(' has already been consumed.
635///
636/// parenexpr ::= expr)
637///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000638bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000639 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000640 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000641 return TokError("expected ')' in parentheses expression");
Chris Lattnerb4307b32010-01-15 19:28:38 +0000642 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000643 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000644 return false;
645}
Chris Lattnerc4193832009-06-22 05:51:26 +0000646
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000647/// ParseBracketExpr - Parse a bracket expression and return it.
648/// NOTE: This assumes the leading '[' has already been consumed.
649///
650/// bracketexpr ::= expr]
651///
652bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
653 if (ParseExpression(Res)) return true;
654 if (Lexer.isNot(AsmToken::RBrac))
655 return TokError("expected ']' in brackets expression");
656 EndLoc = Lexer.getLoc();
657 Lex();
658 return false;
659}
660
Chris Lattner74ec1a32009-06-22 06:32:03 +0000661/// ParsePrimaryExpr - Parse a primary expression and return it.
662/// primaryexpr ::= (parenexpr
663/// primaryexpr ::= symbol
664/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000665/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000666/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000667bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000668 switch (Lexer.getKind()) {
669 default:
670 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000671 // If we have an error assume that we've already handled it.
672 case AsmToken::Error:
673 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000674 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000675 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000676 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000677 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000678 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000679 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000680 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000681 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000682 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000683 EndLoc = Lexer.getLoc();
684
685 StringRef Identifier;
686 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000687 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000688
Daniel Dunbarfffff912009-10-16 01:34:54 +0000689 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000690 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000691 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000692
693 // Lookup the symbol variant if used.
694 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000695 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000696 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000697 if (Variant == MCSymbolRefExpr::VK_Invalid) {
698 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000699 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000700 }
701 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000702
Daniel Dunbarfffff912009-10-16 01:34:54 +0000703 // If this is an absolute variable reference, substitute it now to preserve
704 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000705 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000706 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000707 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000708
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000709 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000710 return false;
711 }
712
713 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000714 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000715 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000716 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000717 case AsmToken::Integer: {
718 SMLoc Loc = getTok().getLoc();
719 int64_t IntVal = getTok().getIntVal();
720 Res = MCConstantExpr::Create(IntVal, getContext());
Chris Lattnerb4307b32010-01-15 19:28:38 +0000721 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000722 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000723 // Look for 'b' or 'f' following an Integer as a directional label
724 if (Lexer.getKind() == AsmToken::Identifier) {
725 StringRef IDVal = getTok().getString();
726 if (IDVal == "f" || IDVal == "b"){
727 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
728 IDVal == "f" ? 1 : 0);
729 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
730 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000731 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000732 return Error(Loc, "invalid reference to undefined symbol");
733 EndLoc = Lexer.getLoc();
734 Lex(); // Eat identifier.
735 }
736 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000737 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000738 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000739 case AsmToken::Real: {
740 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000741 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000742 Res = MCConstantExpr::Create(IntVal, getContext());
743 Lex(); // Eat token.
744 return false;
745 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000746 case AsmToken::Dot: {
747 // This is a '.' reference, which references the current PC. Emit a
748 // temporary label to the streamer and refer to it.
749 MCSymbol *Sym = Ctx.CreateTempSymbol();
750 Out.EmitLabel(Sym);
751 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
752 EndLoc = Lexer.getLoc();
753 Lex(); // Eat identifier.
754 return false;
755 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000756 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000757 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000758 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000759 case AsmToken::LBrac:
760 if (!PlatformParser->HasBracketExpressions())
761 return TokError("brackets expression not supported on this target");
762 Lex(); // Eat the '['.
763 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000764 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000765 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000766 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000767 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000768 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000769 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000770 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000771 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000772 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000773 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000774 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000775 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000776 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000777 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000778 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000779 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000780 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000781 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000782 }
783}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000784
Chris Lattnerb4307b32010-01-15 19:28:38 +0000785bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000786 SMLoc EndLoc;
787 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000788}
789
Daniel Dunbarcceba832010-09-17 02:47:07 +0000790const MCExpr *
791AsmParser::ApplyModifierToExpr(const MCExpr *E,
792 MCSymbolRefExpr::VariantKind Variant) {
793 // Recurse over the given expression, rebuilding it to apply the given variant
794 // if there is exactly one symbol.
795 switch (E->getKind()) {
796 case MCExpr::Target:
797 case MCExpr::Constant:
798 return 0;
799
800 case MCExpr::SymbolRef: {
801 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
802
803 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
804 TokError("invalid variant on expression '" +
805 getTok().getIdentifier() + "' (already modified)");
806 return E;
807 }
808
809 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
810 }
811
812 case MCExpr::Unary: {
813 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
814 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
815 if (!Sub)
816 return 0;
817 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
818 }
819
820 case MCExpr::Binary: {
821 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
822 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
823 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
824
825 if (!LHS && !RHS)
826 return 0;
827
828 if (!LHS) LHS = BE->getLHS();
829 if (!RHS) RHS = BE->getRHS();
830
831 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
832 }
833 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000834
Craig Topper85814382012-02-07 05:05:23 +0000835 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000836}
837
Chris Lattner74ec1a32009-06-22 06:32:03 +0000838/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000839///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000840/// expr ::= expr &&,|| expr -> lowest.
841/// expr ::= expr |,^,&,! expr
842/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
843/// expr ::= expr <<,>> expr
844/// expr ::= expr +,- expr
845/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000846/// expr ::= primaryexpr
847///
Chris Lattner54482b42010-01-15 19:39:23 +0000848bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000849 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000850 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000851 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
852 return true;
853
Daniel Dunbarcceba832010-09-17 02:47:07 +0000854 // As a special case, we support 'a op b @ modifier' by rewriting the
855 // expression to include the modifier. This is inefficient, but in general we
856 // expect users to use 'a@modifier op b'.
857 if (Lexer.getKind() == AsmToken::At) {
858 Lex();
859
860 if (Lexer.isNot(AsmToken::Identifier))
861 return TokError("unexpected symbol modifier following '@'");
862
863 MCSymbolRefExpr::VariantKind Variant =
864 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
865 if (Variant == MCSymbolRefExpr::VK_Invalid)
866 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
867
868 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
869 if (!ModifiedRes) {
870 return TokError("invalid modifier '" + getTok().getIdentifier() +
871 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000872 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000873
Daniel Dunbarcceba832010-09-17 02:47:07 +0000874 Res = ModifiedRes;
875 Lex();
876 }
877
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000878 // Try to constant fold it up front, if possible.
879 int64_t Value;
880 if (Res->EvaluateAsAbsolute(Value))
881 Res = MCConstantExpr::Create(Value, getContext());
882
883 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000884}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000885
Chris Lattnerb4307b32010-01-15 19:28:38 +0000886bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000887 Res = 0;
888 return ParseParenExpr(Res, EndLoc) ||
889 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000890}
891
Daniel Dunbar475839e2009-06-29 20:37:27 +0000892bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000893 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000894
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000895 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000896 if (ParseExpression(Expr))
897 return true;
898
Daniel Dunbare00b0112009-10-16 01:57:52 +0000899 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000900 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000901
902 return false;
903}
904
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000905static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000906 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000907 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000908 default:
909 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000910
Jim Grosbachfbe16812011-08-20 16:24:13 +0000911 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000912 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000913 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000914 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000915 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000916 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000917 return 1;
918
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000919
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000920 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +0000921 //
922 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +0000923 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000924 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000925 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000926 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000927 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000928 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000929 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000930 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000931 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000932
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000933 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000934 case AsmToken::EqualEqual:
935 Kind = MCBinaryExpr::EQ;
936 return 3;
937 case AsmToken::ExclaimEqual:
938 case AsmToken::LessGreater:
939 Kind = MCBinaryExpr::NE;
940 return 3;
941 case AsmToken::Less:
942 Kind = MCBinaryExpr::LT;
943 return 3;
944 case AsmToken::LessEqual:
945 Kind = MCBinaryExpr::LTE;
946 return 3;
947 case AsmToken::Greater:
948 Kind = MCBinaryExpr::GT;
949 return 3;
950 case AsmToken::GreaterEqual:
951 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000952 return 3;
953
Jim Grosbachfbe16812011-08-20 16:24:13 +0000954 // Intermediate Precedence: <<, >>
955 case AsmToken::LessLess:
956 Kind = MCBinaryExpr::Shl;
957 return 4;
958 case AsmToken::GreaterGreater:
959 Kind = MCBinaryExpr::Shr;
960 return 4;
961
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000962 // High Intermediate Precedence: +, -
963 case AsmToken::Plus:
964 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000965 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000966 case AsmToken::Minus:
967 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000968 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000969
Jim Grosbachfbe16812011-08-20 16:24:13 +0000970 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +0000971 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000972 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000973 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000974 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000975 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000976 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000977 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000978 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000979 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000980 }
981}
982
983
984/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
985/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000986bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
987 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000988 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000989 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000990 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000991
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000992 // If the next token is lower precedence than we are allowed to eat, return
993 // successfully with what we ate already.
994 if (TokPrec < Precedence)
995 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000996
Sean Callanan79ed1a82010-01-19 20:22:31 +0000997 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000998
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000999 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001000 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001001 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001002
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001003 // If BinOp binds less tightly with RHS than the operator after RHS, let
1004 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001005 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001006 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001007 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001008 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001009 }
1010
Daniel Dunbar475839e2009-06-29 20:37:27 +00001011 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001012 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001013 }
1014}
1015
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001016
1017
1018
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001019/// ParseStatement:
1020/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001021/// ::= Label* Directive ...Operands... EndOfStatement
1022/// ::= Label* Identifier OperandList* EndOfStatement
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001023bool AsmParser::ParseStatement() {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001024 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001025 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001026 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001027 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001028 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001029
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001030 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001031 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001032 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001033 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001034 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001035 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001036 if (Lexer.is(AsmToken::Hash))
1037 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001038
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001039 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001040 if (Lexer.is(AsmToken::Integer)) {
1041 LocalLabelVal = getTok().getIntVal();
1042 if (LocalLabelVal < 0) {
1043 if (!TheCondState.Ignore)
1044 return TokError("unexpected token at start of statement");
1045 IDVal = "";
1046 }
1047 else {
1048 IDVal = getTok().getString();
1049 Lex(); // Consume the integer token to be used as an identifier token.
1050 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001051 if (!TheCondState.Ignore)
1052 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001053 }
1054 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001055
1056 } else if (Lexer.is(AsmToken::Dot)) {
1057 // Treat '.' as a valid identifier in this context.
1058 Lex();
1059 IDVal = ".";
1060
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001061 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001062 if (!TheCondState.Ignore)
1063 return TokError("unexpected token at start of statement");
1064 IDVal = "";
1065 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001066
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001067
Chris Lattner7834fac2010-04-17 18:14:27 +00001068 // Handle conditional assembly here before checking for skipping. We
1069 // have to do this so that .endif isn't skipped in a ".if 0" block for
1070 // example.
1071 if (IDVal == ".if")
1072 return ParseDirectiveIf(IDLoc);
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00001073 if (IDVal == ".ifb")
1074 return ParseDirectiveIfb(IDLoc, true);
1075 if (IDVal == ".ifnb")
1076 return ParseDirectiveIfb(IDLoc, false);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00001077 if (IDVal == ".ifc")
1078 return ParseDirectiveIfc(IDLoc, true);
1079 if (IDVal == ".ifnc")
1080 return ParseDirectiveIfc(IDLoc, false);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00001081 if (IDVal == ".ifdef")
1082 return ParseDirectiveIfdef(IDLoc, true);
1083 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1084 return ParseDirectiveIfdef(IDLoc, false);
Chris Lattner7834fac2010-04-17 18:14:27 +00001085 if (IDVal == ".elseif")
1086 return ParseDirectiveElseIf(IDLoc);
1087 if (IDVal == ".else")
1088 return ParseDirectiveElse(IDLoc);
1089 if (IDVal == ".endif")
1090 return ParseDirectiveEndIf(IDLoc);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001091
Chris Lattner7834fac2010-04-17 18:14:27 +00001092 // If we are in a ".if 0" block, ignore this statement.
1093 if (TheCondState.Ignore) {
1094 EatToEndOfStatement();
1095 return false;
1096 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001097
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001098 // FIXME: Recurse on local labels?
1099
1100 // See what kind of statement we have.
1101 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001102 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001103 CheckForValidSection();
1104
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001105 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001106 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001107
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001108 // Diagnose attempt to use '.' as a label.
1109 if (IDVal == ".")
1110 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1111
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001112 // Diagnose attempt to use a variable as a label.
1113 //
1114 // FIXME: Diagnostics. Note the location of the definition as a label.
1115 // FIXME: This doesn't diagnose assignment to a symbol which has been
1116 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001117 MCSymbol *Sym;
1118 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001119 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001120 else
1121 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001122 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001123 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001124
Daniel Dunbar959fd882009-08-26 22:13:22 +00001125 // Emit the label.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001126 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001127
Kevin Enderby94c2e852011-12-09 18:09:40 +00001128 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001129 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001130 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001131 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1132 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001133
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001134 // Consume any end of statement token, if present, to avoid spurious
1135 // AddBlankLine calls().
1136 if (Lexer.is(AsmToken::EndOfStatement)) {
1137 Lex();
1138 if (Lexer.is(AsmToken::Eof))
1139 return false;
1140 }
1141
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001142 return ParseStatement();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001143 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001144
Daniel Dunbar3f872332009-07-28 16:08:33 +00001145 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001146 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001147 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001148
Nico Weber4c4c7322011-01-28 03:04:41 +00001149 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001150
1151 default: // Normal instruction or directive.
1152 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001153 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001154
1155 // If macros are enabled, check to see if this is a macro instantiation.
1156 if (MacrosEnabled)
1157 if (const Macro *M = MacroMap.lookup(IDVal))
1158 return HandleMacroEntry(IDVal, IDLoc, M);
1159
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001160 // Otherwise, we have a normal instruction or directive.
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001161 if (IDVal[0] == '.' && IDVal != ".") {
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001162 // Assembler features
Roman Divacky50e7a782010-10-28 16:22:58 +00001163 if (IDVal == ".set" || IDVal == ".equ")
Nico Weber4c4c7322011-01-28 03:04:41 +00001164 return ParseDirectiveSet(IDVal, true);
1165 if (IDVal == ".equiv")
1166 return ParseDirectiveSet(IDVal, false);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001167
Daniel Dunbara0d14262009-06-24 23:30:00 +00001168 // Data directives
1169
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001170 if (IDVal == ".ascii")
Rafael Espindola787c3372010-10-28 20:02:27 +00001171 return ParseDirectiveAscii(IDVal, false);
1172 if (IDVal == ".asciz" || IDVal == ".string")
1173 return ParseDirectiveAscii(IDVal, true);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001174
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001175 if (IDVal == ".byte")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001176 return ParseDirectiveValue(1);
Kevin Enderby9c656452009-09-10 20:51:44 +00001177 if (IDVal == ".short")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001178 return ParseDirectiveValue(2);
Rafael Espindolacc3acee2010-11-01 15:29:07 +00001179 if (IDVal == ".value")
1180 return ParseDirectiveValue(2);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001181 if (IDVal == ".2byte")
1182 return ParseDirectiveValue(2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001183 if (IDVal == ".long")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001184 return ParseDirectiveValue(4);
Rafael Espindola435279b2010-11-17 16:24:40 +00001185 if (IDVal == ".int")
1186 return ParseDirectiveValue(4);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001187 if (IDVal == ".4byte")
1188 return ParseDirectiveValue(4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001189 if (IDVal == ".quad")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001190 return ParseDirectiveValue(8);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001191 if (IDVal == ".8byte")
1192 return ParseDirectiveValue(8);
Roman Divacky14e66552011-01-28 14:20:32 +00001193 if (IDVal == ".single" || IDVal == ".float")
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001194 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1195 if (IDVal == ".double")
1196 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001197
Eli Friedman5d68ec22010-07-19 04:17:25 +00001198 if (IDVal == ".align") {
1199 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1200 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1201 }
1202 if (IDVal == ".align32") {
1203 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1204 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1205 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001206 if (IDVal == ".balign")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001207 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001208 if (IDVal == ".balignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001209 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001210 if (IDVal == ".balignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001211 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001212 if (IDVal == ".p2align")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001213 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001214 if (IDVal == ".p2alignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001215 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001216 if (IDVal == ".p2alignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001217 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1218
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001219 if (IDVal == ".org")
Daniel Dunbarc238b582009-06-25 22:44:51 +00001220 return ParseDirectiveOrg();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001221
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001222 if (IDVal == ".fill")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001223 return ParseDirectiveFill();
Rafael Espindolace8463f2011-04-07 20:26:23 +00001224 if (IDVal == ".space" || IDVal == ".skip")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001225 return ParseDirectiveSpace();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001226 if (IDVal == ".zero")
1227 return ParseDirectiveZero();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001228
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001229 // Symbol attribute directives
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001230
Benjamin Kramere14a3c52012-05-12 11:18:59 +00001231 if (IDVal == ".extern") {
1232 EatToEndOfStatement(); // .extern is the default, ignore it.
1233 return false;
1234 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001235 if (IDVal == ".globl" || IDVal == ".global")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001236 return ParseDirectiveSymbolAttribute(MCSA_Global);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001237 if (IDVal == ".indirect_symbol")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001238 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001239 if (IDVal == ".lazy_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001240 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001241 if (IDVal == ".no_dead_strip")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001242 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Kevin Enderbye8e98d72010-11-19 18:39:33 +00001243 if (IDVal == ".symbol_resolver")
1244 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001245 if (IDVal == ".private_extern")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001246 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001247 if (IDVal == ".reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001248 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001249 if (IDVal == ".weak_definition")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001250 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001251 if (IDVal == ".weak_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001252 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Kevin Enderbyf59cac52010-07-08 17:22:42 +00001253 if (IDVal == ".weak_def_can_be_hidden")
1254 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001255
Hans Wennborg5cc64912011-06-18 13:51:54 +00001256 if (IDVal == ".comm" || IDVal == ".common")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001257 return ParseDirectiveComm(/*IsLocal=*/false);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001258 if (IDVal == ".lcomm")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001259 return ParseDirectiveComm(/*IsLocal=*/true);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001260
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001261 if (IDVal == ".abort")
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001262 return ParseDirectiveAbort();
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001263 if (IDVal == ".include")
Kevin Enderby1f049b22009-07-14 23:21:55 +00001264 return ParseDirectiveInclude();
Kevin Enderbyc55acca2011-12-14 21:47:48 +00001265 if (IDVal == ".incbin")
1266 return ParseDirectiveIncbin();
Kevin Enderbya5c78322009-07-13 21:03:15 +00001267
Benjamin Kramer5cdf0ad2012-05-12 11:19:04 +00001268 if (IDVal == ".code16" || IDVal == ".code16gcc")
Roman Divackyf6fbd842011-01-31 20:56:49 +00001269 return TokError(Twine(IDVal) + " not supported yet");
Roman Divackycb727802011-01-28 19:29:48 +00001270
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001271 if (IDVal == ".rept")
1272 return ParseDirectiveRept(IDLoc);
1273 if (IDVal == ".endr")
1274 return ParseDirectiveEndRept(IDLoc);
1275
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001276 // Look up the handler in the handler table.
1277 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1278 DirectiveMap.lookup(IDVal);
1279 if (Handler.first)
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +00001280 return (*Handler.second)(Handler.first, IDVal, IDLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001281
Kevin Enderby9c656452009-09-10 20:51:44 +00001282 // Target hook for parsing target specific directives.
1283 if (!getTargetParser().ParseDirective(ID))
1284 return false;
1285
Jim Grosbach686c0182012-05-01 18:38:27 +00001286 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001287 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001288
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001289 CheckForValidSection();
1290
Chris Lattnera7f13542010-05-19 23:34:33 +00001291 // Canonicalize the opcode to lower case.
1292 SmallString<128> Opcode;
1293 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1294 Opcode.push_back(tolower(IDVal[i]));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001295
Chris Lattner98986712010-01-14 22:21:20 +00001296 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
Chris Lattnera7f13542010-05-19 23:34:33 +00001297 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001298 ParsedOperands);
Chris Lattner2cf5f142009-06-22 01:29:09 +00001299
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001300 // Dump the parsed representation, if requested.
1301 if (getShowParsedOperands()) {
1302 SmallString<256> Str;
1303 raw_svector_ostream OS(Str);
1304 OS << "parsed instruction: [";
1305 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1306 if (i != 0)
1307 OS << ", ";
Jim Grosbachb7f689b2011-07-13 15:34:57 +00001308 ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001309 }
1310 OS << "]";
1311
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001312 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001313 }
1314
Kevin Enderby613b7572011-11-01 22:27:22 +00001315 // If we are generating dwarf for assembly source files and the current
1316 // section is the initial text section then generate a .loc directive for
1317 // the instruction.
1318 if (!HadError && getContext().getGenDwarfForAssembly() &&
1319 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1320 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1321 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1322 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001323 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001324 StringRef());
1325 }
1326
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001327 // If parsing succeeded, match the instruction.
Chris Lattner7036f8b2010-09-29 01:42:58 +00001328 if (!HadError)
1329 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1330 Out);
Chris Lattner98986712010-01-14 22:21:20 +00001331
Chris Lattner98986712010-01-14 22:21:20 +00001332 // Free any parsed operands.
1333 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1334 delete ParsedOperands[i];
1335
Chris Lattnercbf8a982010-09-11 16:18:25 +00001336 // Don't skip the rest of the line, the instruction parser is responsible for
1337 // that.
1338 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001339}
Chris Lattner9a023f72009-06-24 04:43:34 +00001340
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001341/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1342/// since they may not be able to be tokenized to get to the end of line token.
1343void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001344 if (!Lexer.is(AsmToken::EndOfStatement))
1345 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001346 // Eat EOL.
1347 Lex();
1348}
1349
1350/// ParseCppHashLineFilenameComment as this:
1351/// ::= # number "filename"
1352/// or just as a full line comment if it doesn't have a number and a string.
1353bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1354 Lex(); // Eat the hash token.
1355
1356 if (getLexer().isNot(AsmToken::Integer)) {
1357 // Consume the line since in cases it is not a well-formed line directive,
1358 // as if were simply a full line comment.
1359 EatToEndOfLine();
1360 return false;
1361 }
1362
1363 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001364 Lex();
1365
1366 if (getLexer().isNot(AsmToken::String)) {
1367 EatToEndOfLine();
1368 return false;
1369 }
1370
1371 StringRef Filename = getTok().getString();
1372 // Get rid of the enclosing quotes.
1373 Filename = Filename.substr(1, Filename.size()-2);
1374
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001375 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1376 CppHashLoc = L;
1377 CppHashFilename = Filename;
1378 CppHashLineNumber = LineNumber;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001379
1380 // Ignore any trailing characters, they're just comment.
1381 EatToEndOfLine();
1382 return false;
1383}
1384
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001385/// DiagHandler - will use the the last parsed cpp hash line filename comment
1386/// for the Filename and LineNo if any in the diagnostic.
1387void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1388 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1389 raw_ostream &OS = errs();
1390
1391 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1392 const SMLoc &DiagLoc = Diag.getLoc();
1393 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1394 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1395
1396 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1397 // before printing the message.
1398 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001399 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001400 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1401 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1402 }
1403
1404 // If we have not parsed a cpp hash line filename comment or the source
1405 // manager changed or buffer changed (like in a nested include) then just
1406 // print the normal diagnostic using its Filename and LineNo.
1407 if (!Parser->CppHashLineNumber ||
1408 &DiagSrcMgr != &Parser->SrcMgr ||
1409 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001410 if (Parser->SavedDiagHandler)
1411 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1412 else
1413 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001414 return;
1415 }
1416
1417 // Use the CppHashFilename and calculate a line number based on the
1418 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1419 // the diagnostic.
1420 const std::string Filename = Parser->CppHashFilename;
1421
1422 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1423 int CppHashLocLineNo =
1424 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1425 int LineNo = Parser->CppHashLineNumber - 1 +
1426 (DiagLocLineNo - CppHashLocLineNo);
1427
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001428 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1429 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001430 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001431 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001432
Benjamin Kramer04a04262011-10-16 10:48:29 +00001433 if (Parser->SavedDiagHandler)
1434 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1435 else
1436 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001437}
1438
Rafael Espindola65366442011-06-05 02:43:45 +00001439bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1440 const std::vector<StringRef> &Parameters,
1441 const std::vector<std::vector<AsmToken> > &A,
1442 const SMLoc &L) {
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001443 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001444 unsigned NParameters = Parameters.size();
1445 if (NParameters != 0 && NParameters != A.size())
1446 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001447
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001448 while (!Body.empty()) {
1449 // Scan for the next substitution.
1450 std::size_t End = Body.size(), Pos = 0;
1451 for (; Pos != End; ++Pos) {
1452 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001453 if (!NParameters) {
1454 // This macro has no parameters, look for $0, $1, etc.
1455 if (Body[Pos] != '$' || Pos + 1 == End)
1456 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001457
Rafael Espindola65366442011-06-05 02:43:45 +00001458 char Next = Body[Pos + 1];
1459 if (Next == '$' || Next == 'n' || isdigit(Next))
1460 break;
1461 } else {
1462 // This macro has parameters, look for \foo, \bar, etc.
1463 if (Body[Pos] == '\\' && Pos + 1 != End)
1464 break;
1465 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001466 }
1467
1468 // Add the prefix.
1469 OS << Body.slice(0, Pos);
1470
1471 // Check if we reached the end.
1472 if (Pos == End)
1473 break;
1474
Rafael Espindola65366442011-06-05 02:43:45 +00001475 if (!NParameters) {
1476 switch (Body[Pos+1]) {
1477 // $$ => $
1478 case '$':
1479 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001480 break;
1481
Rafael Espindola65366442011-06-05 02:43:45 +00001482 // $n => number of arguments
1483 case 'n':
1484 OS << A.size();
1485 break;
1486
1487 // $[0-9] => argument
1488 default: {
1489 // Missing arguments are ignored.
1490 unsigned Index = Body[Pos+1] - '0';
1491 if (Index >= A.size())
1492 break;
1493
1494 // Otherwise substitute with the token values, with spaces eliminated.
1495 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1496 ie = A[Index].end(); it != ie; ++it)
1497 OS << it->getString();
1498 break;
1499 }
1500 }
1501 Pos += 2;
1502 } else {
1503 unsigned I = Pos + 1;
1504 while (isalnum(Body[I]) && I + 1 != End)
1505 ++I;
1506
1507 const char *Begin = Body.data() + Pos +1;
1508 StringRef Argument(Begin, I - (Pos +1));
1509 unsigned Index = 0;
1510 for (; Index < NParameters; ++Index)
1511 if (Parameters[Index] == Argument)
1512 break;
1513
1514 // FIXME: We should error at the macro definition.
1515 if (Index == NParameters)
1516 return Error(L, "Parameter not found");
1517
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001518 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1519 ie = A[Index].end(); it != ie; ++it)
1520 OS << it->getString();
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001521
Rafael Espindola65366442011-06-05 02:43:45 +00001522 Pos += 1 + Argument.size();
1523 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001524 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001525 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001526 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001527
1528 // We include the .endmacro in the buffer as our queue to exit the macro
1529 // instantiation.
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001530 OS << ".endmacro\n";
Rafael Espindola65366442011-06-05 02:43:45 +00001531 return false;
1532}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001533
Rafael Espindola65366442011-06-05 02:43:45 +00001534MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1535 MemoryBuffer *I)
1536 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1537{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001538}
1539
1540bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1541 const Macro *M) {
1542 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1543 // this, although we should protect against infinite loops.
1544 if (ActiveMacros.size() == 20)
1545 return TokError("macros cannot be nested more than 20 levels deep");
1546
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001547 // Parse the macro instantiation arguments.
1548 std::vector<std::vector<AsmToken> > MacroArguments;
1549 MacroArguments.push_back(std::vector<AsmToken>());
1550 unsigned ParenLevel = 0;
1551 for (;;) {
1552 if (Lexer.is(AsmToken::Eof))
1553 return TokError("unexpected token in macro instantiation");
1554 if (Lexer.is(AsmToken::EndOfStatement))
1555 break;
1556
1557 // If we aren't inside parentheses and this is a comma, start a new token
1558 // list.
1559 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1560 MacroArguments.push_back(std::vector<AsmToken>());
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001561 } else {
Daniel Dunbare25c6b92010-08-10 17:38:52 +00001562 // Adjust the current parentheses level.
1563 if (Lexer.is(AsmToken::LParen))
1564 ++ParenLevel;
1565 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1566 --ParenLevel;
1567
1568 // Append the token to the current argument list.
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001569 MacroArguments.back().push_back(getTok());
1570 }
1571 Lex();
1572 }
Jim Grosbach68f89a62012-04-16 21:18:49 +00001573 // If the last argument didn't end up with any tokens, it's not a real
1574 // argument and we should remove it from the list. This happens with either
1575 // a tailing comma or an empty argument list.
1576 if (MacroArguments.back().empty())
1577 MacroArguments.pop_back();
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001578
Rafael Espindola65366442011-06-05 02:43:45 +00001579 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1580 // to hold the macro body with substitutions.
1581 SmallString<256> Buf;
1582 StringRef Body = M->Body;
1583
1584 if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1585 return true;
1586
1587 MemoryBuffer *Instantiation =
1588 MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1589
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001590 // Create the macro instantiation object and add to the current macro
1591 // instantiation stack.
1592 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001593 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001594 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001595 ActiveMacros.push_back(MI);
1596
1597 // Jump to the macro instantiation and prime the lexer.
1598 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1599 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1600 Lex();
1601
1602 return false;
1603}
1604
1605void AsmParser::HandleMacroExit() {
1606 // Jump to the EndOfStatement we should return to, and consume it.
1607 JumpToLoc(ActiveMacros.back()->ExitLoc);
1608 Lex();
1609
1610 // Pop the instantiation entry.
1611 delete ActiveMacros.back();
1612 ActiveMacros.pop_back();
1613}
1614
Rafael Espindolae71cc862012-01-28 05:57:00 +00001615static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001616 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001617 case MCExpr::Binary: {
1618 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1619 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001620 break;
1621 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001622 case MCExpr::Target:
1623 case MCExpr::Constant:
1624 return false;
1625 case MCExpr::SymbolRef: {
1626 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001627 if (S.isVariable())
1628 return IsUsedIn(Sym, S.getVariableValue());
1629 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001630 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001631 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001632 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001633 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001634
1635 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001636}
1637
Nico Weber4c4c7322011-01-28 03:04:41 +00001638bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001639 // FIXME: Use better location, we should use proper tokens.
1640 SMLoc EqualLoc = Lexer.getLoc();
1641
Daniel Dunbar821e3332009-08-31 08:09:28 +00001642 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001643 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001644 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001645
Rafael Espindolae71cc862012-01-28 05:57:00 +00001646 // Note: we don't count b as used in "a = b". This is to allow
1647 // a = b
1648 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001649
Daniel Dunbar3f872332009-07-28 16:08:33 +00001650 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001651 return TokError("unexpected token in assignment");
1652
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001653 // Error on assignment to '.'.
1654 if (Name == ".") {
1655 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1656 "(use '.space' or '.org').)"));
1657 }
1658
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001659 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001660 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001661
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001662 // Validate that the LHS is allowed to be a variable (either it has not been
1663 // used as a symbol, or it is an absolute symbol).
1664 MCSymbol *Sym = getContext().LookupSymbol(Name);
1665 if (Sym) {
1666 // Diagnose assignment to a label.
1667 //
1668 // FIXME: Diagnostics. Note the location of the definition as a label.
1669 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00001670 if (IsUsedIn(Sym, Value))
1671 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1672 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001673 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00001674 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1675 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00001676 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001677 return Error(EqualLoc, "redefinition of '" + Name + "'");
1678 else if (!Sym->isVariable())
1679 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00001680 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001681 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1682 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001683
1684 // Don't count these checks as uses.
1685 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001686 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001687 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001688
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001689 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001690
1691 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00001692 Out.EmitAssignment(Sym, Value);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001693
1694 return false;
1695}
1696
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001697/// ParseIdentifier:
1698/// ::= identifier
1699/// ::= string
1700bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00001701 // The assembler has relaxed rules for accepting identifiers, in particular we
1702 // allow things like '.globl $foo', which would normally be separate
1703 // tokens. At this level, we have already lexed so we cannot (currently)
1704 // handle this as a context dependent token, instead we detect adjacent tokens
1705 // and return the combined identifier.
1706 if (Lexer.is(AsmToken::Dollar)) {
1707 SMLoc DollarLoc = getLexer().getLoc();
1708
1709 // Consume the dollar sign, and check for a following identifier.
1710 Lex();
1711 if (Lexer.isNot(AsmToken::Identifier))
1712 return true;
1713
1714 // We have a '$' followed by an identifier, make sure they are adjacent.
1715 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1716 return true;
1717
1718 // Construct the joined identifier and consume the token.
1719 Res = StringRef(DollarLoc.getPointer(),
1720 getTok().getIdentifier().size() + 1);
1721 Lex();
1722 return false;
1723 }
1724
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001725 if (Lexer.isNot(AsmToken::Identifier) &&
1726 Lexer.isNot(AsmToken::String))
1727 return true;
1728
Sean Callanan18b83232010-01-19 21:44:56 +00001729 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001730
Sean Callanan79ed1a82010-01-19 20:22:31 +00001731 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001732
1733 return false;
1734}
1735
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001736/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00001737/// ::= .equ identifier ',' expression
1738/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001739/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00001740bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001741 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001742
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001743 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00001744 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001745
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001746 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00001747 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001748 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001749
Nico Weber4c4c7322011-01-28 03:04:41 +00001750 return ParseAssignment(Name, allow_redef);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001751}
1752
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001753bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001754 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001755
1756 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00001757 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001758 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1759 if (Str[i] != '\\') {
1760 Data += Str[i];
1761 continue;
1762 }
1763
1764 // Recognize escaped characters. Note that this escape semantics currently
1765 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1766 ++i;
1767 if (i == e)
1768 return TokError("unexpected backslash at end of string");
1769
1770 // Recognize octal sequences.
1771 if ((unsigned) (Str[i] - '0') <= 7) {
1772 // Consume up to three octal characters.
1773 unsigned Value = Str[i] - '0';
1774
1775 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1776 ++i;
1777 Value = Value * 8 + (Str[i] - '0');
1778
1779 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1780 ++i;
1781 Value = Value * 8 + (Str[i] - '0');
1782 }
1783 }
1784
1785 if (Value > 255)
1786 return TokError("invalid octal escape sequence (out of range)");
1787
1788 Data += (unsigned char) Value;
1789 continue;
1790 }
1791
1792 // Otherwise recognize individual escapes.
1793 switch (Str[i]) {
1794 default:
1795 // Just reject invalid escape sequences for now.
1796 return TokError("invalid escape sequence (unrecognized character)");
1797
1798 case 'b': Data += '\b'; break;
1799 case 'f': Data += '\f'; break;
1800 case 'n': Data += '\n'; break;
1801 case 'r': Data += '\r'; break;
1802 case 't': Data += '\t'; break;
1803 case '"': Data += '"'; break;
1804 case '\\': Data += '\\'; break;
1805 }
1806 }
1807
1808 return false;
1809}
1810
Daniel Dunbara0d14262009-06-24 23:30:00 +00001811/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00001812/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1813bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001814 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001815 CheckForValidSection();
1816
Daniel Dunbara0d14262009-06-24 23:30:00 +00001817 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001818 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00001819 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001820
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001821 std::string Data;
1822 if (ParseEscapedString(Data))
1823 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001824
1825 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001826 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001827 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1828
Sean Callanan79ed1a82010-01-19 20:22:31 +00001829 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001830
1831 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001832 break;
1833
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001834 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00001835 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001836 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001837 }
1838 }
1839
Sean Callanan79ed1a82010-01-19 20:22:31 +00001840 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001841 return false;
1842}
1843
1844/// ParseDirectiveValue
1845/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1846bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001847 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001848 CheckForValidSection();
1849
Daniel Dunbara0d14262009-06-24 23:30:00 +00001850 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00001851 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00001852 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00001853 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001854 return true;
1855
Daniel Dunbar414c0c42010-05-23 18:36:38 +00001856 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00001857 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1858 assert(Size <= 8 && "Invalid size");
1859 uint64_t IntValue = MCE->getValue();
1860 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1861 return Error(ExprLoc, "literal value out of range for directive");
1862 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1863 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001864 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001865
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001866 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001867 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001868
Daniel Dunbara0d14262009-06-24 23:30:00 +00001869 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001870 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001871 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001872 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001873 }
1874 }
1875
Sean Callanan79ed1a82010-01-19 20:22:31 +00001876 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001877 return false;
1878}
1879
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001880/// ParseDirectiveRealValue
1881/// ::= (.single | .double) [ expression (, expression)* ]
1882bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1883 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1884 CheckForValidSection();
1885
1886 for (;;) {
1887 // We don't truly support arithmetic on floating point expressions, so we
1888 // have to manually parse unary prefixes.
1889 bool IsNeg = false;
1890 if (getLexer().is(AsmToken::Minus)) {
1891 Lex();
1892 IsNeg = true;
1893 } else if (getLexer().is(AsmToken::Plus))
1894 Lex();
1895
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001896 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00001897 getLexer().isNot(AsmToken::Real) &&
1898 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001899 return TokError("unexpected token in directive");
1900
1901 // Convert to an APFloat.
1902 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00001903 StringRef IDVal = getTok().getString();
1904 if (getLexer().is(AsmToken::Identifier)) {
1905 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1906 Value = APFloat::getInf(Semantics);
1907 else if (!IDVal.compare_lower("nan"))
1908 Value = APFloat::getNaN(Semantics, false, ~0);
1909 else
1910 return TokError("invalid floating point literal");
1911 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001912 APFloat::opInvalidOp)
1913 return TokError("invalid floating point literal");
1914 if (IsNeg)
1915 Value.changeSign();
1916
1917 // Consume the numeric token.
1918 Lex();
1919
1920 // Emit the value as an integer.
1921 APInt AsInt = Value.bitcastToAPInt();
1922 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1923 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1924
1925 if (getLexer().is(AsmToken::EndOfStatement))
1926 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001927
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001928 if (getLexer().isNot(AsmToken::Comma))
1929 return TokError("unexpected token in directive");
1930 Lex();
1931 }
1932 }
1933
1934 Lex();
1935 return false;
1936}
1937
Daniel Dunbara0d14262009-06-24 23:30:00 +00001938/// ParseDirectiveSpace
1939/// ::= .space expression [ , expression ]
1940bool AsmParser::ParseDirectiveSpace() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001941 CheckForValidSection();
1942
Daniel Dunbara0d14262009-06-24 23:30:00 +00001943 int64_t NumBytes;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001944 if (ParseAbsoluteExpression(NumBytes))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001945 return true;
1946
1947 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001948 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1949 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001950 return TokError("unexpected token in '.space' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001951 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001952
Daniel Dunbar475839e2009-06-29 20:37:27 +00001953 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001954 return true;
1955
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001956 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001957 return TokError("unexpected token in '.space' directive");
1958 }
1959
Sean Callanan79ed1a82010-01-19 20:22:31 +00001960 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001961
1962 if (NumBytes <= 0)
1963 return TokError("invalid number of bytes in '.space' directive");
1964
1965 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001966 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001967
1968 return false;
1969}
1970
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001971/// ParseDirectiveZero
1972/// ::= .zero expression
1973bool AsmParser::ParseDirectiveZero() {
1974 CheckForValidSection();
1975
1976 int64_t NumBytes;
1977 if (ParseAbsoluteExpression(NumBytes))
1978 return true;
1979
Rafael Espindolae452b172010-10-05 19:42:57 +00001980 int64_t Val = 0;
1981 if (getLexer().is(AsmToken::Comma)) {
1982 Lex();
1983 if (ParseAbsoluteExpression(Val))
1984 return true;
1985 }
1986
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001987 if (getLexer().isNot(AsmToken::EndOfStatement))
1988 return TokError("unexpected token in '.zero' directive");
1989
1990 Lex();
1991
Rafael Espindolae452b172010-10-05 19:42:57 +00001992 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001993
1994 return false;
1995}
1996
Daniel Dunbara0d14262009-06-24 23:30:00 +00001997/// ParseDirectiveFill
1998/// ::= .fill expression , expression , expression
1999bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002000 CheckForValidSection();
2001
Daniel Dunbara0d14262009-06-24 23:30:00 +00002002 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002003 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002004 return true;
2005
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002006 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002007 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002008 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002009
Daniel Dunbara0d14262009-06-24 23:30:00 +00002010 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002011 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002012 return true;
2013
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002014 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002015 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002016 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002017
Daniel Dunbara0d14262009-06-24 23:30:00 +00002018 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002019 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002020 return true;
2021
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002022 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002023 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002024
Sean Callanan79ed1a82010-01-19 20:22:31 +00002025 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002026
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002027 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2028 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002029
2030 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002031 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002032
2033 return false;
2034}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002035
2036/// ParseDirectiveOrg
2037/// ::= .org expression [ , expression ]
2038bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002039 CheckForValidSection();
2040
Daniel Dunbar821e3332009-08-31 08:09:28 +00002041 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002042 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002043 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002044 return true;
2045
2046 // Parse optional fill expression.
2047 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002048 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2049 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002050 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002051 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002052
Daniel Dunbar475839e2009-06-29 20:37:27 +00002053 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002054 return true;
2055
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002056 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002057 return TokError("unexpected token in '.org' directive");
2058 }
2059
Sean Callanan79ed1a82010-01-19 20:22:31 +00002060 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002061
Jim Grosbachebd4c052012-01-27 00:37:08 +00002062 // Only limited forms of relocatable expressions are accepted here, it
2063 // has to be relative to the current section. The streamer will return
2064 // 'true' if the expression wasn't evaluatable.
2065 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2066 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002067
2068 return false;
2069}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002070
2071/// ParseDirectiveAlign
2072/// ::= {.align, ...} expression [ , expression [ , expression ]]
2073bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002074 CheckForValidSection();
2075
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002076 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002077 int64_t Alignment;
2078 if (ParseAbsoluteExpression(Alignment))
2079 return true;
2080
2081 SMLoc MaxBytesLoc;
2082 bool HasFillExpr = false;
2083 int64_t FillExpr = 0;
2084 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002085 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2086 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002087 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002088 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002089
2090 // The fill expression can be omitted while specifying a maximum number of
2091 // alignment bytes, e.g:
2092 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002093 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002094 HasFillExpr = true;
2095 if (ParseAbsoluteExpression(FillExpr))
2096 return true;
2097 }
2098
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002099 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2100 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002101 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002102 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002103
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002104 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002105 if (ParseAbsoluteExpression(MaxBytesToFill))
2106 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002107
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002108 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002109 return TokError("unexpected token in directive");
2110 }
2111 }
2112
Sean Callanan79ed1a82010-01-19 20:22:31 +00002113 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002114
Daniel Dunbar648ac512010-05-17 21:54:30 +00002115 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002116 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002117
2118 // Compute alignment in bytes.
2119 if (IsPow2) {
2120 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002121 if (Alignment >= 32) {
2122 Error(AlignmentLoc, "invalid alignment value");
2123 Alignment = 31;
2124 }
2125
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002126 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002127 }
2128
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002129 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002130 if (MaxBytesLoc.isValid()) {
2131 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002132 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2133 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002134 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002135 }
2136
2137 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002138 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2139 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002140 MaxBytesToFill = 0;
2141 }
2142 }
2143
Daniel Dunbar648ac512010-05-17 21:54:30 +00002144 // Check whether we should use optimal code alignment for this .align
2145 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002146 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002147 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2148 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002149 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002150 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002151 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002152 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2153 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002154 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002155
2156 return false;
2157}
2158
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002159/// ParseDirectiveSymbolAttribute
2160/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00002161bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002162 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002163 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002164 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00002165 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002166
2167 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00002168 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002169
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002170 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002171
Jim Grosbach10ec6502011-09-15 17:56:49 +00002172 // Assembler local symbols don't make any sense here. Complain loudly.
2173 if (Sym->isTemporary())
2174 return Error(Loc, "non-local symbol required in directive");
2175
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002176 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002177
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002178 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002179 break;
2180
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002181 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002182 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002183 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002184 }
2185 }
2186
Sean Callanan79ed1a82010-01-19 20:22:31 +00002187 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00002188 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002189}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002190
2191/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00002192/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2193bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002194 CheckForValidSection();
2195
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002196 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002197 StringRef Name;
2198 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002199 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002200
Daniel Dunbar76c4d762009-07-31 21:55:09 +00002201 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002202 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002203
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002204 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002205 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002206 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002207
2208 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002209 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002210 if (ParseAbsoluteExpression(Size))
2211 return true;
2212
2213 int64_t Pow2Alignment = 0;
2214 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002215 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00002216 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002217 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002218 if (ParseAbsoluteExpression(Pow2Alignment))
2219 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002220
Chris Lattner258281d2010-01-19 06:22:22 +00002221 // If this target takes alignments in bytes (not log) validate and convert.
2222 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2223 if (!isPowerOf2_64(Pow2Alignment))
2224 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2225 Pow2Alignment = Log2_64(Pow2Alignment);
2226 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002227 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002228
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002229 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00002230 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002231
Sean Callanan79ed1a82010-01-19 20:22:31 +00002232 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002233
Chris Lattner1fc3d752009-07-09 17:25:12 +00002234 // NOTE: a size of zero for a .comm should create a undefined symbol
2235 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002236 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002237 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2238 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002239
Eric Christopherc260a3e2010-05-14 01:38:54 +00002240 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002241 // may internally end up wanting an alignment in bytes.
2242 // FIXME: Diagnose overflow.
2243 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002244 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2245 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002246
Daniel Dunbar8906ff12009-08-22 07:22:36 +00002247 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002248 return Error(IDLoc, "invalid symbol redefinition");
2249
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002250 // '.lcomm' is equivalent to '.zerofill'.
Chris Lattner1fc3d752009-07-09 17:25:12 +00002251 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002252 if (IsLocal) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002253 getStreamer().EmitZerofill(Ctx.getMachOSection(
2254 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2255 0, SectionKind::getBSS()),
2256 Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002257 return false;
2258 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002259
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002260 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002261 return false;
2262}
Chris Lattner9be3fee2009-07-10 22:20:30 +00002263
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002264/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002265/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002266bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002267 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002268 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002269
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002270 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002271 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002272 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002273
Sean Callanan79ed1a82010-01-19 20:22:31 +00002274 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002275
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002276 if (Str.empty())
2277 Error(Loc, ".abort detected. Assembly stopping.");
2278 else
2279 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002280 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002281
2282 return false;
2283}
Kevin Enderby71148242009-07-14 21:35:03 +00002284
Kevin Enderby1f049b22009-07-14 23:21:55 +00002285/// ParseDirectiveInclude
2286/// ::= .include "filename"
2287bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002288 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002289 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002290
Sean Callanan18b83232010-01-19 21:44:56 +00002291 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002292 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002293 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00002294
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002295 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002296 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002297
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002298 // Strip the quotes.
2299 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002300
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002301 // Attempt to switch the lexer to the included file before consuming the end
2302 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00002303 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00002304 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002305 return true;
2306 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00002307
2308 return false;
2309}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00002310
Kevin Enderbyc55acca2011-12-14 21:47:48 +00002311/// ParseDirectiveIncbin
2312/// ::= .incbin "filename"
2313bool AsmParser::ParseDirectiveIncbin() {
2314 if (getLexer().isNot(AsmToken::String))
2315 return TokError("expected string in '.incbin' directive");
2316
2317 std::string Filename = getTok().getString();
2318 SMLoc IncbinLoc = getLexer().getLoc();
2319 Lex();
2320
2321 if (getLexer().isNot(AsmToken::EndOfStatement))
2322 return TokError("unexpected token in '.incbin' directive");
2323
2324 // Strip the quotes.
2325 Filename = Filename.substr(1, Filename.size()-2);
2326
2327 // Attempt to process the included file.
2328 if (ProcessIncbinFile(Filename)) {
2329 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2330 return true;
2331 }
2332
2333 return false;
2334}
2335
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002336/// ParseDirectiveIf
2337/// ::= .if expression
2338bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002339 TheCondStack.push_back(TheCondState);
2340 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00002341 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002342 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00002343 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002344 int64_t ExprValue;
2345 if (ParseAbsoluteExpression(ExprValue))
2346 return true;
2347
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002348 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002349 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002350
Sean Callanan79ed1a82010-01-19 20:22:31 +00002351 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002352
2353 TheCondState.CondMet = ExprValue;
2354 TheCondState.Ignore = !TheCondState.CondMet;
2355 }
2356
2357 return false;
2358}
2359
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002360/// ParseDirectiveIfb
2361/// ::= .ifb string
2362bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2363 TheCondStack.push_back(TheCondState);
2364 TheCondState.TheCond = AsmCond::IfCond;
2365
Benjamin Kramer29739e72012-05-12 16:52:21 +00002366 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002367 EatToEndOfStatement();
2368 } else {
2369 StringRef Str = ParseStringToEndOfStatement();
2370
2371 if (getLexer().isNot(AsmToken::EndOfStatement))
2372 return TokError("unexpected token in '.ifb' directive");
2373
2374 Lex();
2375
2376 TheCondState.CondMet = ExpectBlank == Str.empty();
2377 TheCondState.Ignore = !TheCondState.CondMet;
2378 }
2379
2380 return false;
2381}
2382
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002383/// ParseDirectiveIfc
2384/// ::= .ifc string1, string2
2385bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2386 TheCondStack.push_back(TheCondState);
2387 TheCondState.TheCond = AsmCond::IfCond;
2388
Benjamin Kramer29739e72012-05-12 16:52:21 +00002389 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002390 EatToEndOfStatement();
2391 } else {
2392 StringRef Str1 = ParseStringToComma();
2393
2394 if (getLexer().isNot(AsmToken::Comma))
2395 return TokError("unexpected token in '.ifc' directive");
2396
2397 Lex();
2398
2399 StringRef Str2 = ParseStringToEndOfStatement();
2400
2401 if (getLexer().isNot(AsmToken::EndOfStatement))
2402 return TokError("unexpected token in '.ifc' directive");
2403
2404 Lex();
2405
2406 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2407 TheCondState.Ignore = !TheCondState.CondMet;
2408 }
2409
2410 return false;
2411}
2412
2413/// ParseDirectiveIfdef
2414/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00002415bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2416 StringRef Name;
2417 TheCondStack.push_back(TheCondState);
2418 TheCondState.TheCond = AsmCond::IfCond;
2419
2420 if (TheCondState.Ignore) {
2421 EatToEndOfStatement();
2422 } else {
2423 if (ParseIdentifier(Name))
2424 return TokError("expected identifier after '.ifdef'");
2425
2426 Lex();
2427
2428 MCSymbol *Sym = getContext().LookupSymbol(Name);
2429
2430 if (expect_defined)
2431 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2432 else
2433 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2434 TheCondState.Ignore = !TheCondState.CondMet;
2435 }
2436
2437 return false;
2438}
2439
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002440/// ParseDirectiveElseIf
2441/// ::= .elseif expression
2442bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2443 if (TheCondState.TheCond != AsmCond::IfCond &&
2444 TheCondState.TheCond != AsmCond::ElseIfCond)
2445 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2446 " an .elseif");
2447 TheCondState.TheCond = AsmCond::ElseIfCond;
2448
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002449 bool LastIgnoreState = false;
2450 if (!TheCondStack.empty())
2451 LastIgnoreState = TheCondStack.back().Ignore;
2452 if (LastIgnoreState || TheCondState.CondMet) {
2453 TheCondState.Ignore = true;
2454 EatToEndOfStatement();
2455 }
2456 else {
2457 int64_t ExprValue;
2458 if (ParseAbsoluteExpression(ExprValue))
2459 return true;
2460
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002461 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002462 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002463
Sean Callanan79ed1a82010-01-19 20:22:31 +00002464 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002465 TheCondState.CondMet = ExprValue;
2466 TheCondState.Ignore = !TheCondState.CondMet;
2467 }
2468
2469 return false;
2470}
2471
2472/// ParseDirectiveElse
2473/// ::= .else
2474bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002475 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002476 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002477
Sean Callanan79ed1a82010-01-19 20:22:31 +00002478 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002479
2480 if (TheCondState.TheCond != AsmCond::IfCond &&
2481 TheCondState.TheCond != AsmCond::ElseIfCond)
2482 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2483 ".elseif");
2484 TheCondState.TheCond = AsmCond::ElseCond;
2485 bool LastIgnoreState = false;
2486 if (!TheCondStack.empty())
2487 LastIgnoreState = TheCondStack.back().Ignore;
2488 if (LastIgnoreState || TheCondState.CondMet)
2489 TheCondState.Ignore = true;
2490 else
2491 TheCondState.Ignore = false;
2492
2493 return false;
2494}
2495
2496/// ParseDirectiveEndIf
2497/// ::= .endif
2498bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002499 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002500 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002501
Sean Callanan79ed1a82010-01-19 20:22:31 +00002502 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002503
2504 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2505 TheCondStack.empty())
2506 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2507 ".else");
2508 if (!TheCondStack.empty()) {
2509 TheCondState = TheCondStack.back();
2510 TheCondStack.pop_back();
2511 }
2512
2513 return false;
2514}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002515
2516/// ParseDirectiveFile
Nick Lewycky44d798d2011-10-17 23:05:28 +00002517/// ::= .file [number] filename
2518/// ::= .file number directory filename
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002519bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002520 // FIXME: I'm not sure what this is.
2521 int64_t FileNumber = -1;
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002522 SMLoc FileNumberLoc = getLexer().getLoc();
Daniel Dunbareceec052010-07-12 17:45:27 +00002523 if (getLexer().is(AsmToken::Integer)) {
Sean Callanan18b83232010-01-19 21:44:56 +00002524 FileNumber = getTok().getIntVal();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002525 Lex();
Daniel Dunbareceec052010-07-12 17:45:27 +00002526
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002527 if (FileNumber < 1)
2528 return TokError("file number less than one");
2529 }
2530
Daniel Dunbareceec052010-07-12 17:45:27 +00002531 if (getLexer().isNot(AsmToken::String))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002532 return TokError("unexpected token in '.file' directive");
Daniel Dunbareceec052010-07-12 17:45:27 +00002533
Nick Lewycky44d798d2011-10-17 23:05:28 +00002534 // Usually the directory and filename together, otherwise just the directory.
2535 StringRef Path = getTok().getString();
2536 Path = Path.substr(1, Path.size()-2);
Sean Callanan79ed1a82010-01-19 20:22:31 +00002537 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002538
Nick Lewycky44d798d2011-10-17 23:05:28 +00002539 StringRef Directory;
2540 StringRef Filename;
2541 if (getLexer().is(AsmToken::String)) {
2542 if (FileNumber == -1)
2543 return TokError("explicit path specified, but no file number");
2544 Filename = getTok().getString();
2545 Filename = Filename.substr(1, Filename.size()-2);
2546 Directory = Path;
2547 Lex();
2548 } else {
2549 Filename = Path;
2550 }
2551
Daniel Dunbareceec052010-07-12 17:45:27 +00002552 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002553 return TokError("unexpected token in '.file' directive");
2554
Chris Lattnerd32e8032010-01-25 19:02:58 +00002555 if (FileNumber == -1)
Daniel Dunbareceec052010-07-12 17:45:27 +00002556 getStreamer().EmitFileDirective(Filename);
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002557 else {
Kevin Enderby8704b782012-01-11 18:04:47 +00002558 if (getContext().getGenDwarfForAssembly() == true)
2559 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2560 "used to generate dwarf debug info for assembly code");
2561
Nick Lewycky44d798d2011-10-17 23:05:28 +00002562 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002563 Error(FileNumberLoc, "file number already allocated");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002564 }
Daniel Dunbareceec052010-07-12 17:45:27 +00002565
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002566 return false;
2567}
2568
2569/// ParseDirectiveLine
2570/// ::= .line [number]
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002571bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbareceec052010-07-12 17:45:27 +00002572 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2573 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002574 return TokError("unexpected token in '.line' directive");
2575
Sean Callanan18b83232010-01-19 21:44:56 +00002576 int64_t LineNumber = getTok().getIntVal();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002577 (void) LineNumber;
Sean Callanan79ed1a82010-01-19 20:22:31 +00002578 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002579
2580 // FIXME: Do something with the .line.
2581 }
2582
Daniel Dunbareceec052010-07-12 17:45:27 +00002583 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar839348a2010-07-01 20:20:01 +00002584 return TokError("unexpected token in '.line' directive");
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002585
2586 return false;
2587}
2588
2589
2590/// ParseDirectiveLoc
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002591/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002592/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2593/// The first number is a file number, must have been previously assigned with
2594/// a .file directive, the second number is the line number and optionally the
2595/// third number is a column position (zero if not specified). The remaining
2596/// optional items are .loc sub-directives.
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002597bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002598
Daniel Dunbareceec052010-07-12 17:45:27 +00002599 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002600 return TokError("unexpected token in '.loc' directive");
Sean Callanan18b83232010-01-19 21:44:56 +00002601 int64_t FileNumber = getTok().getIntVal();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002602 if (FileNumber < 1)
2603 return TokError("file number less than one in '.loc' directive");
Kevin Enderby3f55c242010-10-04 20:17:24 +00002604 if (!getContext().isValidDwarfFileNumber(FileNumber))
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002605 return TokError("unassigned file number in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002606 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002607
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002608 int64_t LineNumber = 0;
2609 if (getLexer().is(AsmToken::Integer)) {
2610 LineNumber = getTok().getIntVal();
2611 if (LineNumber < 1)
2612 return TokError("line number less than one in '.loc' directive");
2613 Lex();
2614 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002615
2616 int64_t ColumnPos = 0;
2617 if (getLexer().is(AsmToken::Integer)) {
2618 ColumnPos = getTok().getIntVal();
2619 if (ColumnPos < 0)
2620 return TokError("column position less than zero in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002621 Lex();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002622 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002623
Kevin Enderbyc0957932010-09-30 16:52:03 +00002624 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002625 unsigned Isa = 0;
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002626 int64_t Discriminator = 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002627 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2628 for (;;) {
2629 if (getLexer().is(AsmToken::EndOfStatement))
2630 break;
2631
2632 StringRef Name;
2633 SMLoc Loc = getTok().getLoc();
2634 if (getParser().ParseIdentifier(Name))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002635 return TokError("unexpected token in '.loc' directive");
2636
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002637 if (Name == "basic_block")
2638 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2639 else if (Name == "prologue_end")
2640 Flags |= DWARF2_FLAG_PROLOGUE_END;
2641 else if (Name == "epilogue_begin")
2642 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2643 else if (Name == "is_stmt") {
2644 SMLoc Loc = getTok().getLoc();
2645 const MCExpr *Value;
2646 if (getParser().ParseExpression(Value))
2647 return true;
2648 // The expression must be the constant 0 or 1.
2649 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2650 int Value = MCE->getValue();
2651 if (Value == 0)
2652 Flags &= ~DWARF2_FLAG_IS_STMT;
2653 else if (Value == 1)
2654 Flags |= DWARF2_FLAG_IS_STMT;
2655 else
2656 return Error(Loc, "is_stmt value not 0 or 1");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002657 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002658 else {
2659 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2660 }
2661 }
2662 else if (Name == "isa") {
2663 SMLoc Loc = getTok().getLoc();
2664 const MCExpr *Value;
2665 if (getParser().ParseExpression(Value))
2666 return true;
2667 // The expression must be a constant greater or equal to 0.
2668 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2669 int Value = MCE->getValue();
2670 if (Value < 0)
2671 return Error(Loc, "isa number less than zero");
2672 Isa = Value;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002673 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002674 else {
2675 return Error(Loc, "isa number not a constant value");
2676 }
2677 }
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002678 else if (Name == "discriminator") {
2679 if (getParser().ParseAbsoluteExpression(Discriminator))
2680 return true;
2681 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002682 else {
2683 return Error(Loc, "unknown sub-directive in '.loc' directive");
2684 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002685
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002686 if (getLexer().is(AsmToken::EndOfStatement))
2687 break;
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002688 }
2689 }
2690
Rafael Espindolaaf6b58082010-11-16 21:20:32 +00002691 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
Devang Patel3f3bf932011-04-18 20:26:49 +00002692 Isa, Discriminator, StringRef());
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002693
2694 return false;
2695}
2696
Daniel Dunbar138abae2010-10-16 04:56:42 +00002697/// ParseDirectiveStabs
2698/// ::= .stabs string, number, number, number
2699bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2700 SMLoc DirectiveLoc) {
2701 return TokError("unsupported directive '" + Directive + "'");
2702}
2703
Rafael Espindolaf9efd832011-05-10 01:10:18 +00002704/// ParseDirectiveCFISections
2705/// ::= .cfi_sections section [, section]
2706bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2707 SMLoc DirectiveLoc) {
2708 StringRef Name;
2709 bool EH = false;
2710 bool Debug = false;
2711
2712 if (getParser().ParseIdentifier(Name))
2713 return TokError("Expected an identifier");
2714
2715 if (Name == ".eh_frame")
2716 EH = true;
2717 else if (Name == ".debug_frame")
2718 Debug = true;
2719
2720 if (getLexer().is(AsmToken::Comma)) {
2721 Lex();
2722
2723 if (getParser().ParseIdentifier(Name))
2724 return TokError("Expected an identifier");
2725
2726 if (Name == ".eh_frame")
2727 EH = true;
2728 else if (Name == ".debug_frame")
2729 Debug = true;
2730 }
2731
2732 getStreamer().EmitCFISections(EH, Debug);
2733
2734 return false;
2735}
2736
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002737/// ParseDirectiveCFIStartProc
2738/// ::= .cfi_startproc
2739bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2740 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002741 getStreamer().EmitCFIStartProc();
2742 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002743}
2744
2745/// ParseDirectiveCFIEndProc
2746/// ::= .cfi_endproc
2747bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002748 getStreamer().EmitCFIEndProc();
2749 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002750}
2751
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002752/// ParseRegisterOrRegisterNumber - parse register name or number.
2753bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2754 SMLoc DirectiveLoc) {
2755 unsigned RegNo;
2756
Jim Grosbach6f888a82011-06-02 17:14:04 +00002757 if (getLexer().isNot(AsmToken::Integer)) {
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002758 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2759 DirectiveLoc))
2760 return true;
Evan Cheng0e6a0522011-07-18 20:57:22 +00002761 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002762 } else
2763 return getParser().ParseAbsoluteExpression(Register);
Jim Grosbachde2f5f42011-02-11 19:05:56 +00002764
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002765 return false;
2766}
2767
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002768/// ParseDirectiveCFIDefCfa
2769/// ::= .cfi_def_cfa register, offset
2770bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2771 SMLoc DirectiveLoc) {
2772 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002773 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002774 return true;
2775
2776 if (getLexer().isNot(AsmToken::Comma))
2777 return TokError("unexpected token in directive");
2778 Lex();
2779
2780 int64_t Offset = 0;
2781 if (getParser().ParseAbsoluteExpression(Offset))
2782 return true;
2783
Rafael Espindola066c2f42011-04-12 23:59:07 +00002784 getStreamer().EmitCFIDefCfa(Register, Offset);
2785 return false;
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002786}
2787
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002788/// ParseDirectiveCFIDefCfaOffset
2789/// ::= .cfi_def_cfa_offset offset
2790bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2791 SMLoc DirectiveLoc) {
2792 int64_t Offset = 0;
2793 if (getParser().ParseAbsoluteExpression(Offset))
2794 return true;
2795
Rafael Espindola066c2f42011-04-12 23:59:07 +00002796 getStreamer().EmitCFIDefCfaOffset(Offset);
2797 return false;
Rafael Espindola53abbe52011-04-11 20:29:16 +00002798}
2799
2800/// ParseDirectiveCFIAdjustCfaOffset
2801/// ::= .cfi_adjust_cfa_offset adjustment
2802bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2803 SMLoc DirectiveLoc) {
2804 int64_t Adjustment = 0;
2805 if (getParser().ParseAbsoluteExpression(Adjustment))
2806 return true;
2807
Rafael Espindola5d7dcd32011-04-12 18:53:30 +00002808 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2809 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002810}
2811
2812/// ParseDirectiveCFIDefCfaRegister
2813/// ::= .cfi_def_cfa_register register
2814bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2815 SMLoc DirectiveLoc) {
2816 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002817 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002818 return true;
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002819
Rafael Espindola066c2f42011-04-12 23:59:07 +00002820 getStreamer().EmitCFIDefCfaRegister(Register);
2821 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002822}
2823
2824/// ParseDirectiveCFIOffset
Rafael Espindolaa61842b2011-04-11 21:49:50 +00002825/// ::= .cfi_offset register, offset
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002826bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2827 int64_t Register = 0;
2828 int64_t Offset = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002829
2830 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002831 return true;
2832
2833 if (getLexer().isNot(AsmToken::Comma))
2834 return TokError("unexpected token in directive");
2835 Lex();
2836
2837 if (getParser().ParseAbsoluteExpression(Offset))
2838 return true;
2839
Rafael Espindola066c2f42011-04-12 23:59:07 +00002840 getStreamer().EmitCFIOffset(Register, Offset);
2841 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002842}
2843
Rafael Espindolaa61842b2011-04-11 21:49:50 +00002844/// ParseDirectiveCFIRelOffset
2845/// ::= .cfi_rel_offset register, offset
2846bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2847 SMLoc DirectiveLoc) {
2848 int64_t Register = 0;
2849
2850 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2851 return true;
2852
2853 if (getLexer().isNot(AsmToken::Comma))
2854 return TokError("unexpected token in directive");
2855 Lex();
2856
2857 int64_t Offset = 0;
2858 if (getParser().ParseAbsoluteExpression(Offset))
2859 return true;
2860
Rafael Espindola25f492e2011-04-12 16:12:03 +00002861 getStreamer().EmitCFIRelOffset(Register, Offset);
2862 return false;
Rafael Espindolaa61842b2011-04-11 21:49:50 +00002863}
2864
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002865static bool isValidEncoding(int64_t Encoding) {
2866 if (Encoding & ~0xff)
2867 return false;
2868
2869 if (Encoding == dwarf::DW_EH_PE_omit)
2870 return true;
2871
2872 const unsigned Format = Encoding & 0xf;
2873 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2874 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2875 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2876 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2877 return false;
2878
Rafael Espindolacaf11582010-12-29 04:31:26 +00002879 const unsigned Application = Encoding & 0x70;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002880 if (Application != dwarf::DW_EH_PE_absptr &&
Rafael Espindolacaf11582010-12-29 04:31:26 +00002881 Application != dwarf::DW_EH_PE_pcrel)
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002882 return false;
2883
2884 return true;
2885}
2886
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002887/// ParseDirectiveCFIPersonalityOrLsda
2888/// ::= .cfi_personality encoding, [symbol_name]
2889/// ::= .cfi_lsda encoding, [symbol_name]
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002890bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002891 SMLoc DirectiveLoc) {
2892 int64_t Encoding = 0;
2893 if (getParser().ParseAbsoluteExpression(Encoding))
2894 return true;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002895 if (Encoding == dwarf::DW_EH_PE_omit)
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002896 return false;
2897
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002898 if (!isValidEncoding(Encoding))
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002899 return TokError("unsupported encoding.");
2900
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002901 if (getLexer().isNot(AsmToken::Comma))
2902 return TokError("unexpected token in directive");
2903 Lex();
2904
2905 StringRef Name;
2906 if (getParser().ParseIdentifier(Name))
2907 return TokError("expected identifier in directive");
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002908
2909 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2910
2911 if (IDVal == ".cfi_personality")
Rafael Espindola066c2f42011-04-12 23:59:07 +00002912 getStreamer().EmitCFIPersonality(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002913 else {
2914 assert(IDVal == ".cfi_lsda");
Rafael Espindola066c2f42011-04-12 23:59:07 +00002915 getStreamer().EmitCFILsda(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002916 }
Rafael Espindola066c2f42011-04-12 23:59:07 +00002917 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002918}
2919
Rafael Espindolafe024d02010-12-28 18:36:23 +00002920/// ParseDirectiveCFIRememberState
2921/// ::= .cfi_remember_state
2922bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2923 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002924 getStreamer().EmitCFIRememberState();
2925 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00002926}
2927
2928/// ParseDirectiveCFIRestoreState
2929/// ::= .cfi_remember_state
2930bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2931 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002932 getStreamer().EmitCFIRestoreState();
2933 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00002934}
2935
Rafael Espindolac5754392011-04-12 15:31:05 +00002936/// ParseDirectiveCFISameValue
2937/// ::= .cfi_same_value register
2938bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2939 SMLoc DirectiveLoc) {
2940 int64_t Register = 0;
2941
2942 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2943 return true;
2944
2945 getStreamer().EmitCFISameValue(Register);
2946
2947 return false;
2948}
2949
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00002950/// ParseDirectiveCFIRestore
2951/// ::= .cfi_restore register
2952bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
2953 SMLoc DirectiveLoc) {
2954 int64_t Register = 0;
2955 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2956 return true;
2957
2958 getStreamer().EmitCFIRestore(Register);
2959
2960 return false;
2961}
2962
Rafael Espindola6f0b1812011-12-29 20:24:47 +00002963/// ParseDirectiveCFIEscape
2964/// ::= .cfi_escape expression[,...]
2965bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
2966 SMLoc DirectiveLoc) {
2967 std::string Values;
2968 int64_t CurrValue;
2969 if (getParser().ParseAbsoluteExpression(CurrValue))
2970 return true;
2971
2972 Values.push_back((uint8_t)CurrValue);
2973
2974 while (getLexer().is(AsmToken::Comma)) {
2975 Lex();
2976
2977 if (getParser().ParseAbsoluteExpression(CurrValue))
2978 return true;
2979
2980 Values.push_back((uint8_t)CurrValue);
2981 }
2982
2983 getStreamer().EmitCFIEscape(Values);
2984 return false;
2985}
2986
Rafael Espindola16d7d432012-01-23 21:51:52 +00002987/// ParseDirectiveCFISignalFrame
2988/// ::= .cfi_signal_frame
2989bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
2990 SMLoc DirectiveLoc) {
2991 if (getLexer().isNot(AsmToken::EndOfStatement))
2992 return Error(getLexer().getLoc(),
2993 "unexpected token in '" + Directive + "' directive");
2994
2995 getStreamer().EmitCFISignalFrame();
2996
2997 return false;
2998}
2999
Daniel Dunbar3c802de2010-07-18 18:38:02 +00003000/// ParseDirectiveMacrosOnOff
3001/// ::= .macros_on
3002/// ::= .macros_off
3003bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3004 SMLoc DirectiveLoc) {
3005 if (getLexer().isNot(AsmToken::EndOfStatement))
3006 return Error(getLexer().getLoc(),
3007 "unexpected token in '" + Directive + "' directive");
3008
3009 getParser().MacrosEnabled = Directive == ".macros_on";
3010
3011 return false;
3012}
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003013
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003014/// ParseDirectiveMacro
Rafael Espindola65366442011-06-05 02:43:45 +00003015/// ::= .macro name [parameters]
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003016bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3017 SMLoc DirectiveLoc) {
3018 StringRef Name;
3019 if (getParser().ParseIdentifier(Name))
3020 return TokError("expected identifier in directive");
3021
Rafael Espindola65366442011-06-05 02:43:45 +00003022 std::vector<StringRef> Parameters;
3023 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3024 for(;;) {
3025 StringRef Parameter;
3026 if (getParser().ParseIdentifier(Parameter))
3027 return TokError("expected identifier in directive");
3028 Parameters.push_back(Parameter);
3029
3030 if (getLexer().isNot(AsmToken::Comma))
3031 break;
3032 Lex();
3033 }
3034 }
3035
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003036 if (getLexer().isNot(AsmToken::EndOfStatement))
3037 return TokError("unexpected token in '.macro' directive");
3038
3039 // Eat the end of statement.
3040 Lex();
3041
3042 AsmToken EndToken, StartToken = getTok();
3043
3044 // Lex the macro definition.
3045 for (;;) {
3046 // Check whether we have reached the end of the file.
3047 if (getLexer().is(AsmToken::Eof))
3048 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3049
3050 // Otherwise, check whether we have reach the .endmacro.
3051 if (getLexer().is(AsmToken::Identifier) &&
3052 (getTok().getIdentifier() == ".endm" ||
3053 getTok().getIdentifier() == ".endmacro")) {
3054 EndToken = getTok();
3055 Lex();
3056 if (getLexer().isNot(AsmToken::EndOfStatement))
3057 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3058 "' directive");
3059 break;
3060 }
3061
3062 // Otherwise, scan til the end of the statement.
3063 getParser().EatToEndOfStatement();
3064 }
3065
3066 if (getParser().MacroMap.lookup(Name)) {
3067 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3068 }
3069
3070 const char *BodyStart = StartToken.getLoc().getPointer();
3071 const char *BodyEnd = EndToken.getLoc().getPointer();
3072 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Rafael Espindola65366442011-06-05 02:43:45 +00003073 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003074 return false;
3075}
3076
3077/// ParseDirectiveEndMacro
3078/// ::= .endm
3079/// ::= .endmacro
3080bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3081 SMLoc DirectiveLoc) {
3082 if (getLexer().isNot(AsmToken::EndOfStatement))
3083 return TokError("unexpected token in '" + Directive + "' directive");
3084
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00003085 // If we are inside a macro instantiation, terminate the current
3086 // instantiation.
3087 if (!getParser().ActiveMacros.empty()) {
3088 getParser().HandleMacroExit();
3089 return false;
3090 }
3091
3092 // Otherwise, this .endmacro is a stray entry in the file; well formed
3093 // .endmacro directives are handled during the macro definition parsing.
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003094 return TokError("unexpected '" + Directive + "' in file, "
3095 "no current macro definition");
3096}
3097
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +00003098/// ParseDirectivePurgeMacro
3099/// ::= .purgem
3100bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3101 SMLoc DirectiveLoc) {
3102 StringRef Name;
3103 if (getParser().ParseIdentifier(Name))
3104 return TokError("expected identifier in '.purgem' directive");
3105
3106 if (getLexer().isNot(AsmToken::EndOfStatement))
3107 return TokError("unexpected token in '.purgem' directive");
3108
3109 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3110 if (I == getParser().MacroMap.end())
3111 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3112
3113 // Undefine the macro.
3114 delete I->getValue();
3115 getParser().MacroMap.erase(I);
3116 return false;
3117}
3118
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003119bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
Rafael Espindola3ff57092010-11-02 17:22:24 +00003120 getParser().CheckForValidSection();
3121
3122 const MCExpr *Value;
3123
3124 if (getParser().ParseExpression(Value))
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003125 return true;
3126
3127 if (getLexer().isNot(AsmToken::EndOfStatement))
3128 return TokError("unexpected token in directive");
3129
3130 if (DirName[1] == 's')
Rafael Espindola3ff57092010-11-02 17:22:24 +00003131 getStreamer().EmitSLEB128Value(Value);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003132 else
Rafael Espindola3ff57092010-11-02 17:22:24 +00003133 getStreamer().EmitULEB128Value(Value);
3134
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003135 return false;
3136}
3137
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003138bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3139 const MCExpr *Value;
3140
3141 if (ParseExpression(Value))
3142 return true;
3143
3144 int64_t Count;
3145 if (!Value->EvaluateAsAbsolute(Count))
3146 return TokError("Cannot evaluate value");
3147
3148 if (Count < 0)
3149 return TokError("Count is negative");
3150
3151 AsmToken EndToken, StartToken = getTok();
3152 unsigned Nest = 1;
3153
3154 // Lex the macro definition.
3155 for (;;) {
3156 // Check whether we have reached the end of the file.
3157 if (getLexer().is(AsmToken::Eof))
3158 return Error(DirectiveLoc, "no matching '.endr' in definition");
3159
3160 // Chcek if we have a nested .rept.
3161 if (getLexer().is(AsmToken::Identifier) &&
3162 (getTok().getIdentifier() == ".rept")) {
3163 Nest++;
3164 EatToEndOfStatement();
3165 continue;
3166 }
3167
3168 // Otherwise, check whether we have reach the .endr.
3169 if (getLexer().is(AsmToken::Identifier) &&
3170 (getTok().getIdentifier() == ".endr")) {
3171 Nest--;
3172 if (Nest == 0) {
3173 EndToken = getTok();
3174 Lex();
3175 if (getLexer().isNot(AsmToken::EndOfStatement))
3176 return TokError("unexpected token in '.endr' directive");
3177 break;
3178 }
3179 }
3180
3181 // Otherwise, scan til the end of the statement.
3182 EatToEndOfStatement();
3183 }
3184
3185 const char *BodyStart = StartToken.getLoc().getPointer();
3186 const char *BodyEnd = EndToken.getLoc().getPointer();
3187 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3188
3189 SmallString<256> Buf;
3190 raw_svector_ostream OS(Buf);
3191 for (int i = 0; i < Count; i++)
3192 OS << Body;
3193 OS << ".endr\n";
3194
3195 MemoryBuffer *Instantiation =
3196 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3197
3198 CurBuffer = SrcMgr.AddNewSourceBuffer(Instantiation, SMLoc());
3199 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3200
3201 ActiveRept.push_back(getTok().getLoc());
3202
3203 return false;
3204}
3205
3206bool AsmParser::ParseDirectiveEndRept(SMLoc DirectiveLoc) {
3207 if (ActiveRept.empty())
3208 return TokError("unexpected '.endr' directive, no current .rept");
3209
3210 // The only .repl that should get here are the ones created by
3211 // ParseDirectiveRept.
3212 assert(getLexer().is(AsmToken::EndOfStatement));
3213
3214 JumpToLoc(ActiveRept.back());
3215 ActiveRept.pop_back();
3216 return false;
3217}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003218
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003219/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003220MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003221 MCContext &C, MCStreamer &Out,
3222 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003223 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003224}