blob: f2618e190afb08594e41403a7e05b30d48ef2706 [file] [log] [blame]
Chris Lattner27aa7d22009-06-21 20:16:42 +00001//===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This class implements the parser for assembly files.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbarb95a0792010-09-24 01:59:56 +000014#include "llvm/ADT/APFloat.h"
Daniel Dunbar7c0a3342009-08-26 22:49:51 +000015#include "llvm/ADT/SmallString.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000016#include "llvm/ADT/StringMap.h"
Daniel Dunbarf9507ff2009-07-27 23:20:52 +000017#include "llvm/ADT/Twine.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000018#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000019#include "llvm/MC/MCContext.h"
Evan Cheng94b95502011-07-26 00:24:13 +000020#include "llvm/MC/MCDwarf.h"
Daniel Dunbar28c251b2009-08-31 08:06:59 +000021#include "llvm/MC/MCExpr.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000022#include "llvm/MC/MCParser/AsmCond.h"
23#include "llvm/MC/MCParser/AsmLexer.h"
24#include "llvm/MC/MCParser/MCAsmParser.h"
25#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Evan Chenge76a33b2011-07-20 05:58:47 +000026#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000027#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000028#include "llvm/MC/MCStreamer.h"
Daniel Dunbardce0f3c2009-06-29 23:43:14 +000029#include "llvm/MC/MCSymbol.h"
Evan Cheng94b95502011-07-26 00:24:13 +000030#include "llvm/MC/MCTargetAsmParser.h"
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000031#include "llvm/Support/CommandLine.h"
Benjamin Kramer518ff562012-01-28 15:28:41 +000032#include "llvm/Support/ErrorHandling.h"
Jim Grosbach254cf032011-06-29 16:05:14 +000033#include "llvm/Support/MathExtras.h"
Kevin Enderbyf187ac52010-06-28 21:45:58 +000034#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000035#include "llvm/Support/SourceMgr.h"
Chris Lattnerb0789ed2009-06-21 20:54:55 +000036#include "llvm/Support/raw_ostream.h"
Nick Lewycky476b2422010-12-19 20:43:38 +000037#include <cctype>
Daniel Dunbaraef87e32010-07-18 18:31:38 +000038#include <vector>
Chris Lattner27aa7d22009-06-21 20:16:42 +000039using namespace llvm;
40
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000041static cl::opt<bool>
42FatalAssemblerWarnings("fatal-assembler-warnings",
43 cl::desc("Consider warnings as error"));
44
Daniel Dunbar81ea00f2010-07-12 17:54:38 +000045namespace {
46
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000047/// \brief Helper class for tracking macro definitions.
Rafael Espindola28c1f6662012-06-03 22:41:23 +000048typedef std::vector<AsmToken> MacroArgument;
49
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000050struct Macro {
51 StringRef Name;
52 StringRef Body;
Rafael Espindola65366442011-06-05 02:43:45 +000053 std::vector<StringRef> Parameters;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000054
55public:
Rafael Espindola65366442011-06-05 02:43:45 +000056 Macro(StringRef N, StringRef B, const std::vector<StringRef> &P) :
57 Name(N), Body(B), Parameters(P) {}
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000058};
59
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000060/// \brief Helper class for storing information about an active macro
61/// instantiation.
62struct MacroInstantiation {
63 /// The macro being instantiated.
64 const Macro *TheMacro;
65
66 /// The macro instantiation with substitutions.
67 MemoryBuffer *Instantiation;
68
69 /// The location of the instantiation.
70 SMLoc InstantiationLoc;
71
72 /// The location where parsing should resume upon instantiation completion.
73 SMLoc ExitLoc;
74
75public:
Daniel Dunbar7a570d02010-07-18 19:00:10 +000076 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000077 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000078};
79
Daniel Dunbaraef87e32010-07-18 18:31:38 +000080/// \brief The concrete assembly parser instance.
81class AsmParser : public MCAsmParser {
Daniel Dunbar3c802de2010-07-18 18:38:02 +000082 friend class GenericAsmParser;
83
Daniel Dunbaraef87e32010-07-18 18:31:38 +000084 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
85 void operator=(const AsmParser &); // DO NOT IMPLEMENT
86private:
87 AsmLexer Lexer;
88 MCContext &Ctx;
89 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +000090 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +000091 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +000092 SourceMgr::DiagHandlerTy SavedDiagHandler;
93 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +000094 MCAsmParserExtension *GenericParser;
95 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +000096
Daniel Dunbaraef87e32010-07-18 18:31:38 +000097 /// This is the current buffer index we're lexing from as managed by the
98 /// SourceMgr object.
99 int CurBuffer;
100
101 AsmCond TheCondState;
102 std::vector<AsmCond> TheCondStack;
103
104 /// DirectiveMap - This is a table handlers for directives. Each handler is
105 /// invoked after the directive identifier is read and is responsible for
106 /// parsing and validating the rest of the directive. The handler is passed
107 /// in the directive name and the location of the directive keyword.
108 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000109
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000110 /// MacroMap - Map of currently defined macros.
111 StringMap<Macro*> MacroMap;
112
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000113 /// ActiveMacros - Stack of active macro instantiations.
114 std::vector<MacroInstantiation*> ActiveMacros;
115
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000116 /// Boolean tracking whether macro substitution is enabled.
117 unsigned MacrosEnabled : 1;
118
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000119 /// Flag tracking whether any errors have been encountered.
120 unsigned HadError : 1;
121
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000122 /// The values from the last parsed cpp hash file line comment if any.
123 StringRef CppHashFilename;
124 int64_t CppHashLineNumber;
125 SMLoc CppHashLoc;
126
Devang Patel0db58bf2012-01-31 18:14:05 +0000127 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
128 unsigned AssemblerDialect;
129
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000130public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000131 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000132 const MCAsmInfo &MAI);
133 ~AsmParser();
134
135 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
136
137 void AddDirectiveHandler(MCAsmParserExtension *Object,
138 StringRef Directive,
139 DirectiveHandler Handler) {
140 DirectiveMap[Directive] = std::make_pair(Object, Handler);
141 }
142
143public:
144 /// @name MCAsmParser Interface
145 /// {
146
147 virtual SourceMgr &getSourceManager() { return SrcMgr; }
148 virtual MCAsmLexer &getLexer() { return Lexer; }
149 virtual MCContext &getContext() { return Ctx; }
150 virtual MCStreamer &getStreamer() { return Out; }
Devang Patel0db58bf2012-01-31 18:14:05 +0000151 virtual unsigned getAssemblerDialect() {
152 if (AssemblerDialect == ~0U)
153 return MAI.getAssemblerDialect();
154 else
155 return AssemblerDialect;
156 }
157 virtual void setAssemblerDialect(unsigned i) {
158 AssemblerDialect = i;
159 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000160
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000161 virtual bool Warning(SMLoc L, const Twine &Msg,
162 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
163 virtual bool Error(SMLoc L, const Twine &Msg,
164 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000165
166 const AsmToken &Lex();
167
168 bool ParseExpression(const MCExpr *&Res);
169 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
170 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
171 virtual bool ParseAbsoluteExpression(int64_t &Res);
172
173 /// }
174
175private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000176 void CheckForValidSection();
177
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000178 bool ParseStatement();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000179 void EatToEndOfLine();
180 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000181
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000182 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
Rafael Espindola761cb062012-06-03 23:57:14 +0000183 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola65366442011-06-05 02:43:45 +0000184 const std::vector<StringRef> &Parameters,
Rafael Espindola28c1f6662012-06-03 22:41:23 +0000185 const std::vector<MacroArgument> &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000186 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000187 void HandleMacroExit();
188
189 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000190 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000191 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
192 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000193 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000194 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000195
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000196 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
197 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000198 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
199 /// This returns true on failure.
200 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000201
202 /// \brief Reset the current lexer position to that given by \arg Loc. The
203 /// current token is not set; clients should ensure Lex() is called
204 /// subsequently.
205 void JumpToLoc(SMLoc Loc);
206
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000207 void EatToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000208
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000209 bool ParseMacroArgument(MacroArgument &MA);
210 bool ParseMacroArguments(const Macro *M, std::vector<MacroArgument> &A);
211
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000212 /// \brief Parse up to the end of statement and a return the contents from the
213 /// current token until the end of the statement; the current token on exit
214 /// will be either the EndOfStatement or EOF.
215 StringRef ParseStringToEndOfStatement();
216
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000217 /// \brief Parse until the end of a statement or a comma is encountered,
218 /// return the contents from the current token up to the end or comma.
219 StringRef ParseStringToComma();
220
Nico Weber4c4c7322011-01-28 03:04:41 +0000221 bool ParseAssignment(StringRef Name, bool allow_redef);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000222
223 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
224 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
225 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000226 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000227
228 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
229 /// and set \arg Res to the identifier contents.
230 bool ParseIdentifier(StringRef &Res);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000231
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000232 // Directive Parsing.
Rafael Espindola787c3372010-10-28 20:02:27 +0000233
234 // ".ascii", ".asciiz", ".string"
235 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000236 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000237 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000238 bool ParseDirectiveFill(); // ".fill"
239 bool ParseDirectiveSpace(); // ".space"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000240 bool ParseDirectiveZero(); // ".zero"
Nico Weber4c4c7322011-01-28 03:04:41 +0000241 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000242 bool ParseDirectiveOrg(); // ".org"
243 // ".align{,32}", ".p2align{,w,l}"
244 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
245
246 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
247 /// accepts a single symbol (which should be a label or an external).
248 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000249
250 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
251
252 bool ParseDirectiveAbort(); // ".abort"
253 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000254 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000255
256 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000257 // ".ifb" or ".ifnb", depending on ExpectBlank.
258 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000259 // ".ifc" or ".ifnc", depending on ExpectEqual.
260 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000261 // ".ifdef" or ".ifndef", depending on expect_defined
262 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000263 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
264 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
265 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
266
267 /// ParseEscapedString - Parse the current token as a string which may include
268 /// escaped characters and return the string contents.
269 bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000270
271 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
272 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000273
Rafael Espindola761cb062012-06-03 23:57:14 +0000274 // Macro-like directives
275 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
276 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
277 raw_svector_ostream &OS);
278 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000279 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindola761cb062012-06-03 23:57:14 +0000280 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000281};
282
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000283/// \brief Generic implementations of directive handling, etc. which is shared
284/// (or the default, at least) for all assembler parser.
285class GenericAsmParser : public MCAsmParserExtension {
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000286 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
287 void AddDirectiveHandler(StringRef Directive) {
288 getParser().AddDirectiveHandler(this, Directive,
289 HandleDirective<GenericAsmParser, Handler>);
290 }
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000291public:
292 GenericAsmParser() {}
293
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000294 AsmParser &getParser() {
295 return (AsmParser&) this->MCAsmParserExtension::getParser();
296 }
297
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000298 virtual void Initialize(MCAsmParser &Parser) {
299 // Call the base implementation.
300 this->MCAsmParserExtension::Initialize(Parser);
301
302 // Debugging directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000303 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
304 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
305 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
Daniel Dunbar138abae2010-10-16 04:56:42 +0000306 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000307
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000308 // CFI directives.
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000309 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
310 ".cfi_sections");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000311 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
312 ".cfi_startproc");
313 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
314 ".cfi_endproc");
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000315 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
316 ".cfi_def_cfa");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000317 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
318 ".cfi_def_cfa_offset");
Rafael Espindola53abbe52011-04-11 20:29:16 +0000319 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
320 ".cfi_adjust_cfa_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000321 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
322 ".cfi_def_cfa_register");
323 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
324 ".cfi_offset");
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000325 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
326 ".cfi_rel_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000327 AddDirectiveHandler<
328 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
329 AddDirectiveHandler<
330 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
Rafael Espindolafe024d02010-12-28 18:36:23 +0000331 AddDirectiveHandler<
332 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
333 AddDirectiveHandler<
334 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
Rafael Espindolac5754392011-04-12 15:31:05 +0000335 AddDirectiveHandler<
336 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000337 AddDirectiveHandler<
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000338 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
339 AddDirectiveHandler<
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000340 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
Rafael Espindola16d7d432012-01-23 21:51:52 +0000341 AddDirectiveHandler<
342 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000343
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000344 // Macro directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000345 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
346 ".macros_on");
347 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
348 ".macros_off");
349 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
350 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
351 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000352 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000353
354 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
355 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000356 }
357
Roman Divacky54b0f4f2011-01-27 17:16:37 +0000358 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
359
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000360 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
361 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
362 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar138abae2010-10-16 04:56:42 +0000363 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000364 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000365 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
366 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000367 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000368 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola53abbe52011-04-11 20:29:16 +0000369 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000370 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
371 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000372 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000373 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
Rafael Espindolafe024d02010-12-28 18:36:23 +0000374 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
375 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac5754392011-04-12 15:31:05 +0000376 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000377 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000378 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
Rafael Espindola16d7d432012-01-23 21:51:52 +0000379 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000380
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000381 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000382 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
383 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000384 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000385
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000386 bool ParseDirectiveLEB128(StringRef, SMLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000387};
388
389}
390
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000391namespace llvm {
392
393extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000394extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000395extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000396
397}
398
Chris Lattneraaec2052010-01-19 19:46:13 +0000399enum { DEFAULT_ADDRSPACE = 0 };
400
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000401AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000402 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000403 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Rafael Espindola5d7dcd32011-04-12 18:53:30 +0000404 GenericParser(new GenericAsmParser), PlatformParser(0),
Devang Patel0db58bf2012-01-31 18:14:05 +0000405 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
406 AssemblerDialect(~0U) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000407 // Save the old handler.
408 SavedDiagHandler = SrcMgr.getDiagHandler();
409 SavedDiagContext = SrcMgr.getDiagContext();
410 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000411 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000412 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000413
414 // Initialize the generic parser.
415 GenericParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000416
417 // Initialize the platform / file format parser.
418 //
419 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
420 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000421 if (_MAI.hasMicrosoftFastStdCallMangling()) {
422 PlatformParser = createCOFFAsmParser();
423 PlatformParser->Initialize(*this);
424 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000425 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000426 PlatformParser->Initialize(*this);
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000427 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000428 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000429 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000430 }
Chris Lattnerebb89b42009-09-27 21:16:52 +0000431}
432
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000433AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000434 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
435
436 // Destroy any macros.
437 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
438 ie = MacroMap.end(); it != ie; ++it)
439 delete it->getValue();
440
Daniel Dunbare4749702010-07-12 18:12:02 +0000441 delete PlatformParser;
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000442 delete GenericParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000443}
444
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000445void AsmParser::PrintMacroInstantiations() {
446 // Print the active macro instantiation stack.
447 for (std::vector<MacroInstantiation*>::const_reverse_iterator
448 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000449 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
450 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000451}
452
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000453bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000454 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000455 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000456 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000457 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000458 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000459}
460
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000461bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000462 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000463 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000464 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000465 return true;
466}
467
Sean Callananfd0b0282010-01-21 00:19:58 +0000468bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000469 std::string IncludedFile;
470 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000471 if (NewBuf == -1)
472 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000473
Sean Callananfd0b0282010-01-21 00:19:58 +0000474 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000475
Sean Callananfd0b0282010-01-21 00:19:58 +0000476 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000477
Sean Callananfd0b0282010-01-21 00:19:58 +0000478 return false;
479}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000480
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000481/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000482/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000483/// returns true on failure.
484bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
485 std::string IncludedFile;
486 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
487 if (NewBuf == -1)
488 return true;
489
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000490 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000491 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
492 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000493 return false;
494}
495
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000496void AsmParser::JumpToLoc(SMLoc Loc) {
497 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
498 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
499}
500
Sean Callananfd0b0282010-01-21 00:19:58 +0000501const AsmToken &AsmParser::Lex() {
502 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000503
Sean Callananfd0b0282010-01-21 00:19:58 +0000504 if (tok->is(AsmToken::Eof)) {
505 // If this is the end of an included file, pop the parent file off the
506 // include stack.
507 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
508 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000509 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000510 tok = &Lexer.Lex();
511 }
512 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000513
Sean Callananfd0b0282010-01-21 00:19:58 +0000514 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000515 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000516
Sean Callananfd0b0282010-01-21 00:19:58 +0000517 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000518}
519
Chris Lattner79180e22010-04-05 23:15:42 +0000520bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000521 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000522 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000523 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000524
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000525 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000526 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000527
528 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000529 AsmCond StartingCondState = TheCondState;
530
Kevin Enderby613b7572011-11-01 22:27:22 +0000531 // If we are generating dwarf for assembly source files save the initial text
532 // section and generate a .file directive.
533 if (getContext().getGenDwarfForAssembly()) {
534 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000535 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
536 getStreamer().EmitLabel(SectionStartSym);
537 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000538 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
539 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
540 }
541
Chris Lattnerb717fb02009-07-02 21:53:43 +0000542 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000543 while (Lexer.isNot(AsmToken::Eof)) {
Chris Lattnerb717fb02009-07-02 21:53:43 +0000544 if (!ParseStatement()) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000545
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000546 // We had an error, validate that one was emitted and recover by skipping to
547 // the next line.
548 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000549 EatToEndOfStatement();
550 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000551
552 if (TheCondState.TheCond != StartingCondState.TheCond ||
553 TheCondState.Ignore != StartingCondState.Ignore)
554 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000555
556 // Check to see there are no empty DwarfFile slots.
557 const std::vector<MCDwarfFile *> &MCDwarfFiles =
558 getContext().getMCDwarfFiles();
559 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000560 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000561 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000562 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000563
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000564 // Check to see that all assembler local symbols were actually defined.
565 // Targets that don't do subsections via symbols may not want this, though,
566 // so conservatively exclude them. Only do this if we're finalizing, though,
567 // as otherwise we won't necessarilly have seen everything yet.
568 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
569 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
570 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
571 e = Symbols.end();
572 i != e; ++i) {
573 MCSymbol *Sym = i->getValue();
574 // Variable symbols may not be marked as defined, so check those
575 // explicitly. If we know it's a variable, we have a definition for
576 // the purposes of this check.
577 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
578 // FIXME: We would really like to refer back to where the symbol was
579 // first referenced for a source location. We need to add something
580 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000581 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
582 "assembler local symbol '" + Sym->getName() +
583 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000584 }
585 }
586
587
Chris Lattner79180e22010-04-05 23:15:42 +0000588 // Finalize the output stream if there are no errors and if the client wants
589 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000590 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000591 Out.Finish();
592
Chris Lattnerb717fb02009-07-02 21:53:43 +0000593 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000594}
595
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000596void AsmParser::CheckForValidSection() {
597 if (!getStreamer().getCurrentSection()) {
598 TokError("expected section directive before assembly directive");
599 Out.SwitchSection(Ctx.getMachOSection(
600 "__TEXT", "__text",
601 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
602 0, SectionKind::getText()));
603 }
604}
605
Chris Lattner2cf5f142009-06-22 01:29:09 +0000606/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
607void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000608 while (Lexer.isNot(AsmToken::EndOfStatement) &&
609 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000610 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000611
Chris Lattner2cf5f142009-06-22 01:29:09 +0000612 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000613 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000614 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000615}
616
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000617StringRef AsmParser::ParseStringToEndOfStatement() {
618 const char *Start = getTok().getLoc().getPointer();
619
620 while (Lexer.isNot(AsmToken::EndOfStatement) &&
621 Lexer.isNot(AsmToken::Eof))
622 Lex();
623
624 const char *End = getTok().getLoc().getPointer();
625 return StringRef(Start, End - Start);
626}
Chris Lattnerc4193832009-06-22 05:51:26 +0000627
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000628StringRef AsmParser::ParseStringToComma() {
629 const char *Start = getTok().getLoc().getPointer();
630
631 while (Lexer.isNot(AsmToken::EndOfStatement) &&
632 Lexer.isNot(AsmToken::Comma) &&
633 Lexer.isNot(AsmToken::Eof))
634 Lex();
635
636 const char *End = getTok().getLoc().getPointer();
637 return StringRef(Start, End - Start);
638}
639
Chris Lattner74ec1a32009-06-22 06:32:03 +0000640/// ParseParenExpr - Parse a paren expression and return it.
641/// NOTE: This assumes the leading '(' has already been consumed.
642///
643/// parenexpr ::= expr)
644///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000645bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000646 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000647 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000648 return TokError("expected ')' in parentheses expression");
Chris Lattnerb4307b32010-01-15 19:28:38 +0000649 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000650 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000651 return false;
652}
Chris Lattnerc4193832009-06-22 05:51:26 +0000653
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000654/// ParseBracketExpr - Parse a bracket expression and return it.
655/// NOTE: This assumes the leading '[' has already been consumed.
656///
657/// bracketexpr ::= expr]
658///
659bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
660 if (ParseExpression(Res)) return true;
661 if (Lexer.isNot(AsmToken::RBrac))
662 return TokError("expected ']' in brackets expression");
663 EndLoc = Lexer.getLoc();
664 Lex();
665 return false;
666}
667
Chris Lattner74ec1a32009-06-22 06:32:03 +0000668/// ParsePrimaryExpr - Parse a primary expression and return it.
669/// primaryexpr ::= (parenexpr
670/// primaryexpr ::= symbol
671/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000672/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000673/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000674bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000675 switch (Lexer.getKind()) {
676 default:
677 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000678 // If we have an error assume that we've already handled it.
679 case AsmToken::Error:
680 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000681 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000682 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000683 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000684 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000685 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000686 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000687 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000688 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000689 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000690 EndLoc = Lexer.getLoc();
691
692 StringRef Identifier;
693 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000694 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000695
Daniel Dunbarfffff912009-10-16 01:34:54 +0000696 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000697 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000698 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000699
700 // Lookup the symbol variant if used.
701 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000702 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000703 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000704 if (Variant == MCSymbolRefExpr::VK_Invalid) {
705 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000706 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000707 }
708 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000709
Daniel Dunbarfffff912009-10-16 01:34:54 +0000710 // If this is an absolute variable reference, substitute it now to preserve
711 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000712 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000713 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000714 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000715
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000716 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000717 return false;
718 }
719
720 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000721 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000722 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000723 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000724 case AsmToken::Integer: {
725 SMLoc Loc = getTok().getLoc();
726 int64_t IntVal = getTok().getIntVal();
727 Res = MCConstantExpr::Create(IntVal, getContext());
Chris Lattnerb4307b32010-01-15 19:28:38 +0000728 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000729 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000730 // Look for 'b' or 'f' following an Integer as a directional label
731 if (Lexer.getKind() == AsmToken::Identifier) {
732 StringRef IDVal = getTok().getString();
733 if (IDVal == "f" || IDVal == "b"){
734 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
735 IDVal == "f" ? 1 : 0);
736 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
737 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000738 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000739 return Error(Loc, "invalid reference to undefined symbol");
740 EndLoc = Lexer.getLoc();
741 Lex(); // Eat identifier.
742 }
743 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000744 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000745 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000746 case AsmToken::Real: {
747 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000748 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000749 Res = MCConstantExpr::Create(IntVal, getContext());
750 Lex(); // Eat token.
751 return false;
752 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000753 case AsmToken::Dot: {
754 // This is a '.' reference, which references the current PC. Emit a
755 // temporary label to the streamer and refer to it.
756 MCSymbol *Sym = Ctx.CreateTempSymbol();
757 Out.EmitLabel(Sym);
758 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
759 EndLoc = Lexer.getLoc();
760 Lex(); // Eat identifier.
761 return false;
762 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000763 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000764 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000765 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000766 case AsmToken::LBrac:
767 if (!PlatformParser->HasBracketExpressions())
768 return TokError("brackets expression not supported on this target");
769 Lex(); // Eat the '['.
770 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000771 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000772 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000773 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000774 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000775 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000776 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000777 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000778 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000779 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000780 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000781 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000782 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000783 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000784 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000785 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000786 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000787 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000788 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000789 }
790}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000791
Chris Lattnerb4307b32010-01-15 19:28:38 +0000792bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000793 SMLoc EndLoc;
794 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000795}
796
Daniel Dunbarcceba832010-09-17 02:47:07 +0000797const MCExpr *
798AsmParser::ApplyModifierToExpr(const MCExpr *E,
799 MCSymbolRefExpr::VariantKind Variant) {
800 // Recurse over the given expression, rebuilding it to apply the given variant
801 // if there is exactly one symbol.
802 switch (E->getKind()) {
803 case MCExpr::Target:
804 case MCExpr::Constant:
805 return 0;
806
807 case MCExpr::SymbolRef: {
808 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
809
810 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
811 TokError("invalid variant on expression '" +
812 getTok().getIdentifier() + "' (already modified)");
813 return E;
814 }
815
816 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
817 }
818
819 case MCExpr::Unary: {
820 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
821 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
822 if (!Sub)
823 return 0;
824 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
825 }
826
827 case MCExpr::Binary: {
828 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
829 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
830 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
831
832 if (!LHS && !RHS)
833 return 0;
834
835 if (!LHS) LHS = BE->getLHS();
836 if (!RHS) RHS = BE->getRHS();
837
838 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
839 }
840 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000841
Craig Topper85814382012-02-07 05:05:23 +0000842 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000843}
844
Chris Lattner74ec1a32009-06-22 06:32:03 +0000845/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000846///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000847/// expr ::= expr &&,|| expr -> lowest.
848/// expr ::= expr |,^,&,! expr
849/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
850/// expr ::= expr <<,>> expr
851/// expr ::= expr +,- expr
852/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000853/// expr ::= primaryexpr
854///
Chris Lattner54482b42010-01-15 19:39:23 +0000855bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000856 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000857 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000858 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
859 return true;
860
Daniel Dunbarcceba832010-09-17 02:47:07 +0000861 // As a special case, we support 'a op b @ modifier' by rewriting the
862 // expression to include the modifier. This is inefficient, but in general we
863 // expect users to use 'a@modifier op b'.
864 if (Lexer.getKind() == AsmToken::At) {
865 Lex();
866
867 if (Lexer.isNot(AsmToken::Identifier))
868 return TokError("unexpected symbol modifier following '@'");
869
870 MCSymbolRefExpr::VariantKind Variant =
871 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
872 if (Variant == MCSymbolRefExpr::VK_Invalid)
873 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
874
875 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
876 if (!ModifiedRes) {
877 return TokError("invalid modifier '" + getTok().getIdentifier() +
878 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000879 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000880
Daniel Dunbarcceba832010-09-17 02:47:07 +0000881 Res = ModifiedRes;
882 Lex();
883 }
884
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000885 // Try to constant fold it up front, if possible.
886 int64_t Value;
887 if (Res->EvaluateAsAbsolute(Value))
888 Res = MCConstantExpr::Create(Value, getContext());
889
890 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000891}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000892
Chris Lattnerb4307b32010-01-15 19:28:38 +0000893bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000894 Res = 0;
895 return ParseParenExpr(Res, EndLoc) ||
896 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000897}
898
Daniel Dunbar475839e2009-06-29 20:37:27 +0000899bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000900 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000901
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000902 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000903 if (ParseExpression(Expr))
904 return true;
905
Daniel Dunbare00b0112009-10-16 01:57:52 +0000906 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000907 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000908
909 return false;
910}
911
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000912static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000913 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000914 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000915 default:
916 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000917
Jim Grosbachfbe16812011-08-20 16:24:13 +0000918 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000919 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000920 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000921 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000922 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000923 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000924 return 1;
925
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000926
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000927 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +0000928 //
929 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +0000930 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000931 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000932 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000933 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000934 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000935 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000936 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000937 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000938 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000939
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000940 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000941 case AsmToken::EqualEqual:
942 Kind = MCBinaryExpr::EQ;
943 return 3;
944 case AsmToken::ExclaimEqual:
945 case AsmToken::LessGreater:
946 Kind = MCBinaryExpr::NE;
947 return 3;
948 case AsmToken::Less:
949 Kind = MCBinaryExpr::LT;
950 return 3;
951 case AsmToken::LessEqual:
952 Kind = MCBinaryExpr::LTE;
953 return 3;
954 case AsmToken::Greater:
955 Kind = MCBinaryExpr::GT;
956 return 3;
957 case AsmToken::GreaterEqual:
958 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000959 return 3;
960
Jim Grosbachfbe16812011-08-20 16:24:13 +0000961 // Intermediate Precedence: <<, >>
962 case AsmToken::LessLess:
963 Kind = MCBinaryExpr::Shl;
964 return 4;
965 case AsmToken::GreaterGreater:
966 Kind = MCBinaryExpr::Shr;
967 return 4;
968
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000969 // High Intermediate Precedence: +, -
970 case AsmToken::Plus:
971 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000972 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000973 case AsmToken::Minus:
974 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000975 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000976
Jim Grosbachfbe16812011-08-20 16:24:13 +0000977 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +0000978 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000979 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000980 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000981 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000982 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000983 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000984 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000985 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000986 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000987 }
988}
989
990
991/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
992/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000993bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
994 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000995 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000996 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000997 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000998
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000999 // If the next token is lower precedence than we are allowed to eat, return
1000 // successfully with what we ate already.
1001 if (TokPrec < Precedence)
1002 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001003
Sean Callanan79ed1a82010-01-19 20:22:31 +00001004 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001005
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001006 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001007 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001008 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001009
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001010 // If BinOp binds less tightly with RHS than the operator after RHS, let
1011 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001012 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001013 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001014 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001015 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001016 }
1017
Daniel Dunbar475839e2009-06-29 20:37:27 +00001018 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001019 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001020 }
1021}
1022
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001023
1024
1025
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001026/// ParseStatement:
1027/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001028/// ::= Label* Directive ...Operands... EndOfStatement
1029/// ::= Label* Identifier OperandList* EndOfStatement
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001030bool AsmParser::ParseStatement() {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001031 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001032 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001033 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001034 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001035 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001036
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001037 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001038 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001039 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001040 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001041 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001042 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001043 if (Lexer.is(AsmToken::Hash))
1044 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001045
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001046 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001047 if (Lexer.is(AsmToken::Integer)) {
1048 LocalLabelVal = getTok().getIntVal();
1049 if (LocalLabelVal < 0) {
1050 if (!TheCondState.Ignore)
1051 return TokError("unexpected token at start of statement");
1052 IDVal = "";
1053 }
1054 else {
1055 IDVal = getTok().getString();
1056 Lex(); // Consume the integer token to be used as an identifier token.
1057 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001058 if (!TheCondState.Ignore)
1059 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001060 }
1061 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001062
1063 } else if (Lexer.is(AsmToken::Dot)) {
1064 // Treat '.' as a valid identifier in this context.
1065 Lex();
1066 IDVal = ".";
1067
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001068 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001069 if (!TheCondState.Ignore)
1070 return TokError("unexpected token at start of statement");
1071 IDVal = "";
1072 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001073
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001074
Chris Lattner7834fac2010-04-17 18:14:27 +00001075 // Handle conditional assembly here before checking for skipping. We
1076 // have to do this so that .endif isn't skipped in a ".if 0" block for
1077 // example.
1078 if (IDVal == ".if")
1079 return ParseDirectiveIf(IDLoc);
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00001080 if (IDVal == ".ifb")
1081 return ParseDirectiveIfb(IDLoc, true);
1082 if (IDVal == ".ifnb")
1083 return ParseDirectiveIfb(IDLoc, false);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00001084 if (IDVal == ".ifc")
1085 return ParseDirectiveIfc(IDLoc, true);
1086 if (IDVal == ".ifnc")
1087 return ParseDirectiveIfc(IDLoc, false);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00001088 if (IDVal == ".ifdef")
1089 return ParseDirectiveIfdef(IDLoc, true);
1090 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1091 return ParseDirectiveIfdef(IDLoc, false);
Chris Lattner7834fac2010-04-17 18:14:27 +00001092 if (IDVal == ".elseif")
1093 return ParseDirectiveElseIf(IDLoc);
1094 if (IDVal == ".else")
1095 return ParseDirectiveElse(IDLoc);
1096 if (IDVal == ".endif")
1097 return ParseDirectiveEndIf(IDLoc);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001098
Chris Lattner7834fac2010-04-17 18:14:27 +00001099 // If we are in a ".if 0" block, ignore this statement.
1100 if (TheCondState.Ignore) {
1101 EatToEndOfStatement();
1102 return false;
1103 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001104
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001105 // FIXME: Recurse on local labels?
1106
1107 // See what kind of statement we have.
1108 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001109 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001110 CheckForValidSection();
1111
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001112 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001113 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001114
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001115 // Diagnose attempt to use '.' as a label.
1116 if (IDVal == ".")
1117 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1118
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001119 // Diagnose attempt to use a variable as a label.
1120 //
1121 // FIXME: Diagnostics. Note the location of the definition as a label.
1122 // FIXME: This doesn't diagnose assignment to a symbol which has been
1123 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001124 MCSymbol *Sym;
1125 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001126 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001127 else
1128 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001129 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001130 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001131
Daniel Dunbar959fd882009-08-26 22:13:22 +00001132 // Emit the label.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001133 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001134
Kevin Enderby94c2e852011-12-09 18:09:40 +00001135 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001136 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001137 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001138 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1139 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001140
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001141 // Consume any end of statement token, if present, to avoid spurious
1142 // AddBlankLine calls().
1143 if (Lexer.is(AsmToken::EndOfStatement)) {
1144 Lex();
1145 if (Lexer.is(AsmToken::Eof))
1146 return false;
1147 }
1148
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001149 return ParseStatement();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001150 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001151
Daniel Dunbar3f872332009-07-28 16:08:33 +00001152 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001153 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001154 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001155
Nico Weber4c4c7322011-01-28 03:04:41 +00001156 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001157
1158 default: // Normal instruction or directive.
1159 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001160 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001161
1162 // If macros are enabled, check to see if this is a macro instantiation.
1163 if (MacrosEnabled)
1164 if (const Macro *M = MacroMap.lookup(IDVal))
1165 return HandleMacroEntry(IDVal, IDLoc, M);
1166
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001167 // Otherwise, we have a normal instruction or directive.
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001168 if (IDVal[0] == '.' && IDVal != ".") {
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001169 // Assembler features
Roman Divacky50e7a782010-10-28 16:22:58 +00001170 if (IDVal == ".set" || IDVal == ".equ")
Nico Weber4c4c7322011-01-28 03:04:41 +00001171 return ParseDirectiveSet(IDVal, true);
1172 if (IDVal == ".equiv")
1173 return ParseDirectiveSet(IDVal, false);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001174
Daniel Dunbara0d14262009-06-24 23:30:00 +00001175 // Data directives
1176
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001177 if (IDVal == ".ascii")
Rafael Espindola787c3372010-10-28 20:02:27 +00001178 return ParseDirectiveAscii(IDVal, false);
1179 if (IDVal == ".asciz" || IDVal == ".string")
1180 return ParseDirectiveAscii(IDVal, true);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001181
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001182 if (IDVal == ".byte")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001183 return ParseDirectiveValue(1);
Kevin Enderby9c656452009-09-10 20:51:44 +00001184 if (IDVal == ".short")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001185 return ParseDirectiveValue(2);
Rafael Espindolacc3acee2010-11-01 15:29:07 +00001186 if (IDVal == ".value")
1187 return ParseDirectiveValue(2);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001188 if (IDVal == ".2byte")
1189 return ParseDirectiveValue(2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001190 if (IDVal == ".long")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001191 return ParseDirectiveValue(4);
Rafael Espindola435279b2010-11-17 16:24:40 +00001192 if (IDVal == ".int")
1193 return ParseDirectiveValue(4);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001194 if (IDVal == ".4byte")
1195 return ParseDirectiveValue(4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001196 if (IDVal == ".quad")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001197 return ParseDirectiveValue(8);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001198 if (IDVal == ".8byte")
1199 return ParseDirectiveValue(8);
Roman Divacky14e66552011-01-28 14:20:32 +00001200 if (IDVal == ".single" || IDVal == ".float")
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001201 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1202 if (IDVal == ".double")
1203 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001204
Eli Friedman5d68ec22010-07-19 04:17:25 +00001205 if (IDVal == ".align") {
1206 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1207 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1208 }
1209 if (IDVal == ".align32") {
1210 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1211 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1212 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001213 if (IDVal == ".balign")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001214 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001215 if (IDVal == ".balignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001216 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001217 if (IDVal == ".balignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001218 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001219 if (IDVal == ".p2align")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001220 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001221 if (IDVal == ".p2alignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001222 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001223 if (IDVal == ".p2alignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001224 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1225
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001226 if (IDVal == ".org")
Daniel Dunbarc238b582009-06-25 22:44:51 +00001227 return ParseDirectiveOrg();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001228
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001229 if (IDVal == ".fill")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001230 return ParseDirectiveFill();
Rafael Espindolace8463f2011-04-07 20:26:23 +00001231 if (IDVal == ".space" || IDVal == ".skip")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001232 return ParseDirectiveSpace();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001233 if (IDVal == ".zero")
1234 return ParseDirectiveZero();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001235
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001236 // Symbol attribute directives
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001237
Benjamin Kramere14a3c52012-05-12 11:18:59 +00001238 if (IDVal == ".extern") {
1239 EatToEndOfStatement(); // .extern is the default, ignore it.
1240 return false;
1241 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001242 if (IDVal == ".globl" || IDVal == ".global")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001243 return ParseDirectiveSymbolAttribute(MCSA_Global);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001244 if (IDVal == ".indirect_symbol")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001245 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001246 if (IDVal == ".lazy_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001247 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001248 if (IDVal == ".no_dead_strip")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001249 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Kevin Enderbye8e98d72010-11-19 18:39:33 +00001250 if (IDVal == ".symbol_resolver")
1251 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001252 if (IDVal == ".private_extern")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001253 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001254 if (IDVal == ".reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001255 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001256 if (IDVal == ".weak_definition")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001257 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001258 if (IDVal == ".weak_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001259 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Kevin Enderbyf59cac52010-07-08 17:22:42 +00001260 if (IDVal == ".weak_def_can_be_hidden")
1261 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001262
Hans Wennborg5cc64912011-06-18 13:51:54 +00001263 if (IDVal == ".comm" || IDVal == ".common")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001264 return ParseDirectiveComm(/*IsLocal=*/false);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001265 if (IDVal == ".lcomm")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001266 return ParseDirectiveComm(/*IsLocal=*/true);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001267
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001268 if (IDVal == ".abort")
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001269 return ParseDirectiveAbort();
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001270 if (IDVal == ".include")
Kevin Enderby1f049b22009-07-14 23:21:55 +00001271 return ParseDirectiveInclude();
Kevin Enderbyc55acca2011-12-14 21:47:48 +00001272 if (IDVal == ".incbin")
1273 return ParseDirectiveIncbin();
Kevin Enderbya5c78322009-07-13 21:03:15 +00001274
Benjamin Kramer5cdf0ad2012-05-12 11:19:04 +00001275 if (IDVal == ".code16" || IDVal == ".code16gcc")
Roman Divackyf6fbd842011-01-31 20:56:49 +00001276 return TokError(Twine(IDVal) + " not supported yet");
Roman Divackycb727802011-01-28 19:29:48 +00001277
Rafael Espindola761cb062012-06-03 23:57:14 +00001278 // Macro-like directives
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001279 if (IDVal == ".rept")
1280 return ParseDirectiveRept(IDLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001281 if (IDVal == ".irp")
1282 return ParseDirectiveIrp(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001283 if (IDVal == ".endr")
Rafael Espindola761cb062012-06-03 23:57:14 +00001284 return ParseDirectiveEndr(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001285
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001286 // Look up the handler in the handler table.
1287 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1288 DirectiveMap.lookup(IDVal);
1289 if (Handler.first)
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +00001290 return (*Handler.second)(Handler.first, IDVal, IDLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001291
Kevin Enderby9c656452009-09-10 20:51:44 +00001292 // Target hook for parsing target specific directives.
1293 if (!getTargetParser().ParseDirective(ID))
1294 return false;
1295
Jim Grosbach686c0182012-05-01 18:38:27 +00001296 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001297 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001298
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001299 CheckForValidSection();
1300
Chris Lattnera7f13542010-05-19 23:34:33 +00001301 // Canonicalize the opcode to lower case.
1302 SmallString<128> Opcode;
1303 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1304 Opcode.push_back(tolower(IDVal[i]));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001305
Chris Lattner98986712010-01-14 22:21:20 +00001306 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
Chris Lattnera7f13542010-05-19 23:34:33 +00001307 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001308 ParsedOperands);
Chris Lattner2cf5f142009-06-22 01:29:09 +00001309
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001310 // Dump the parsed representation, if requested.
1311 if (getShowParsedOperands()) {
1312 SmallString<256> Str;
1313 raw_svector_ostream OS(Str);
1314 OS << "parsed instruction: [";
1315 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1316 if (i != 0)
1317 OS << ", ";
Jim Grosbachb7f689b2011-07-13 15:34:57 +00001318 ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001319 }
1320 OS << "]";
1321
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001322 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001323 }
1324
Kevin Enderby613b7572011-11-01 22:27:22 +00001325 // If we are generating dwarf for assembly source files and the current
1326 // section is the initial text section then generate a .loc directive for
1327 // the instruction.
1328 if (!HadError && getContext().getGenDwarfForAssembly() &&
1329 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1330 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1331 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1332 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001333 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001334 StringRef());
1335 }
1336
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001337 // If parsing succeeded, match the instruction.
Chris Lattner7036f8b2010-09-29 01:42:58 +00001338 if (!HadError)
1339 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1340 Out);
Chris Lattner98986712010-01-14 22:21:20 +00001341
Chris Lattner98986712010-01-14 22:21:20 +00001342 // Free any parsed operands.
1343 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1344 delete ParsedOperands[i];
1345
Chris Lattnercbf8a982010-09-11 16:18:25 +00001346 // Don't skip the rest of the line, the instruction parser is responsible for
1347 // that.
1348 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001349}
Chris Lattner9a023f72009-06-24 04:43:34 +00001350
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001351/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1352/// since they may not be able to be tokenized to get to the end of line token.
1353void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001354 if (!Lexer.is(AsmToken::EndOfStatement))
1355 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001356 // Eat EOL.
1357 Lex();
1358}
1359
1360/// ParseCppHashLineFilenameComment as this:
1361/// ::= # number "filename"
1362/// or just as a full line comment if it doesn't have a number and a string.
1363bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1364 Lex(); // Eat the hash token.
1365
1366 if (getLexer().isNot(AsmToken::Integer)) {
1367 // Consume the line since in cases it is not a well-formed line directive,
1368 // as if were simply a full line comment.
1369 EatToEndOfLine();
1370 return false;
1371 }
1372
1373 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001374 Lex();
1375
1376 if (getLexer().isNot(AsmToken::String)) {
1377 EatToEndOfLine();
1378 return false;
1379 }
1380
1381 StringRef Filename = getTok().getString();
1382 // Get rid of the enclosing quotes.
1383 Filename = Filename.substr(1, Filename.size()-2);
1384
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001385 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1386 CppHashLoc = L;
1387 CppHashFilename = Filename;
1388 CppHashLineNumber = LineNumber;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001389
1390 // Ignore any trailing characters, they're just comment.
1391 EatToEndOfLine();
1392 return false;
1393}
1394
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001395/// DiagHandler - will use the the last parsed cpp hash line filename comment
1396/// for the Filename and LineNo if any in the diagnostic.
1397void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1398 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1399 raw_ostream &OS = errs();
1400
1401 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1402 const SMLoc &DiagLoc = Diag.getLoc();
1403 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1404 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1405
1406 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1407 // before printing the message.
1408 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001409 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001410 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1411 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1412 }
1413
1414 // If we have not parsed a cpp hash line filename comment or the source
1415 // manager changed or buffer changed (like in a nested include) then just
1416 // print the normal diagnostic using its Filename and LineNo.
1417 if (!Parser->CppHashLineNumber ||
1418 &DiagSrcMgr != &Parser->SrcMgr ||
1419 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001420 if (Parser->SavedDiagHandler)
1421 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1422 else
1423 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001424 return;
1425 }
1426
1427 // Use the CppHashFilename and calculate a line number based on the
1428 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1429 // the diagnostic.
1430 const std::string Filename = Parser->CppHashFilename;
1431
1432 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1433 int CppHashLocLineNo =
1434 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1435 int LineNo = Parser->CppHashLineNumber - 1 +
1436 (DiagLocLineNo - CppHashLocLineNo);
1437
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001438 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1439 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001440 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001441 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001442
Benjamin Kramer04a04262011-10-16 10:48:29 +00001443 if (Parser->SavedDiagHandler)
1444 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1445 else
1446 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001447}
1448
Rafael Espindola761cb062012-06-03 23:57:14 +00001449bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola65366442011-06-05 02:43:45 +00001450 const std::vector<StringRef> &Parameters,
Rafael Espindola28c1f6662012-06-03 22:41:23 +00001451 const std::vector<MacroArgument> &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001452 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001453 unsigned NParameters = Parameters.size();
1454 if (NParameters != 0 && NParameters != A.size())
1455 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001456
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001457 while (!Body.empty()) {
1458 // Scan for the next substitution.
1459 std::size_t End = Body.size(), Pos = 0;
1460 for (; Pos != End; ++Pos) {
1461 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001462 if (!NParameters) {
1463 // This macro has no parameters, look for $0, $1, etc.
1464 if (Body[Pos] != '$' || Pos + 1 == End)
1465 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001466
Rafael Espindola65366442011-06-05 02:43:45 +00001467 char Next = Body[Pos + 1];
1468 if (Next == '$' || Next == 'n' || isdigit(Next))
1469 break;
1470 } else {
1471 // This macro has parameters, look for \foo, \bar, etc.
1472 if (Body[Pos] == '\\' && Pos + 1 != End)
1473 break;
1474 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001475 }
1476
1477 // Add the prefix.
1478 OS << Body.slice(0, Pos);
1479
1480 // Check if we reached the end.
1481 if (Pos == End)
1482 break;
1483
Rafael Espindola65366442011-06-05 02:43:45 +00001484 if (!NParameters) {
1485 switch (Body[Pos+1]) {
1486 // $$ => $
1487 case '$':
1488 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001489 break;
1490
Rafael Espindola65366442011-06-05 02:43:45 +00001491 // $n => number of arguments
1492 case 'n':
1493 OS << A.size();
1494 break;
1495
1496 // $[0-9] => argument
1497 default: {
1498 // Missing arguments are ignored.
1499 unsigned Index = Body[Pos+1] - '0';
1500 if (Index >= A.size())
1501 break;
1502
1503 // Otherwise substitute with the token values, with spaces eliminated.
Rafael Espindola28c1f6662012-06-03 22:41:23 +00001504 for (MacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001505 ie = A[Index].end(); it != ie; ++it)
1506 OS << it->getString();
1507 break;
1508 }
1509 }
1510 Pos += 2;
1511 } else {
1512 unsigned I = Pos + 1;
1513 while (isalnum(Body[I]) && I + 1 != End)
1514 ++I;
1515
1516 const char *Begin = Body.data() + Pos +1;
1517 StringRef Argument(Begin, I - (Pos +1));
1518 unsigned Index = 0;
1519 for (; Index < NParameters; ++Index)
1520 if (Parameters[Index] == Argument)
1521 break;
1522
1523 // FIXME: We should error at the macro definition.
1524 if (Index == NParameters)
1525 return Error(L, "Parameter not found");
1526
Rafael Espindola28c1f6662012-06-03 22:41:23 +00001527 for (MacroArgument::const_iterator it = A[Index].begin(),
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001528 ie = A[Index].end(); it != ie; ++it)
1529 OS << it->getString();
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001530
Rafael Espindola65366442011-06-05 02:43:45 +00001531 Pos += 1 + Argument.size();
1532 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001533 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001534 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001535 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001536
Rafael Espindola65366442011-06-05 02:43:45 +00001537 return false;
1538}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001539
Rafael Espindola65366442011-06-05 02:43:45 +00001540MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1541 MemoryBuffer *I)
1542 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1543{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001544}
1545
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001546/// ParseMacroArgument - Extract AsmTokens for a macro argument.
1547/// This is used for both default macro parameter values and the
1548/// arguments in macro invocations
1549bool AsmParser::ParseMacroArgument(MacroArgument &MA) {
1550 unsigned ParenLevel = 0;
1551
1552 for (;;) {
1553 SMLoc LastTokenLoc;
1554
1555 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
1556 return TokError("unexpected token in macro instantiation");
1557
1558 // HandleMacroEntry relies on not advancing the lexer here
1559 // to be able to fill in the remaining default parameter values
1560 if (Lexer.is(AsmToken::EndOfStatement))
1561 break;
1562 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
1563 break;
1564
1565 // Adjust the current parentheses level.
1566 if (Lexer.is(AsmToken::LParen))
1567 ++ParenLevel;
1568 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1569 --ParenLevel;
1570
1571 // Append the token to the current argument list.
1572 MA.push_back(getTok());
1573 Lex();
1574 }
1575 if (ParenLevel != 0)
1576 return TokError("unbalanced parenthesises in macro argument");
1577 return false;
1578}
1579
1580// Parse the macro instantiation arguments.
1581bool AsmParser::ParseMacroArguments(const Macro *M,
1582 std::vector<MacroArgument> &A) {
1583 const unsigned NParameters = M ? M->Parameters.size() : 0;
1584
1585 // Parse two kinds of macro invocations:
1586 // - macros defined without any parameters accept an arbitrary number of them
1587 // - macros defined with parameters accept at most that many of them
1588 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1589 ++Parameter) {
1590 MacroArgument MA;
1591
1592 if (ParseMacroArgument(MA))
1593 return true;
1594
1595 if (!MA.empty())
1596 A.push_back(MA);
1597 if (Lexer.is(AsmToken::EndOfStatement))
1598 return false;
1599
1600 if (Lexer.is(AsmToken::Comma))
1601 Lex();
1602 }
1603 return TokError("Too many arguments");
1604}
1605
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001606bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1607 const Macro *M) {
1608 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1609 // this, although we should protect against infinite loops.
1610 if (ActiveMacros.size() == 20)
1611 return TokError("macros cannot be nested more than 20 levels deep");
1612
Rafael Espindola28c1f6662012-06-03 22:41:23 +00001613 std::vector<MacroArgument> MacroArguments;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001614 if (ParseMacroArguments(M, MacroArguments))
1615 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001616
Rafael Espindola65366442011-06-05 02:43:45 +00001617 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1618 // to hold the macro body with substitutions.
1619 SmallString<256> Buf;
1620 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001621 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001622
Rafael Espindola761cb062012-06-03 23:57:14 +00001623 if (expandMacro(OS, Body, M->Parameters, MacroArguments, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001624 return true;
1625
Rafael Espindola761cb062012-06-03 23:57:14 +00001626 // We include the .endmacro in the buffer as our queue to exit the macro
1627 // instantiation.
1628 OS << ".endmacro\n";
1629
Rafael Espindola65366442011-06-05 02:43:45 +00001630 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001631 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001632
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001633 // Create the macro instantiation object and add to the current macro
1634 // instantiation stack.
1635 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001636 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001637 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001638 ActiveMacros.push_back(MI);
1639
1640 // Jump to the macro instantiation and prime the lexer.
1641 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1642 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1643 Lex();
1644
1645 return false;
1646}
1647
1648void AsmParser::HandleMacroExit() {
1649 // Jump to the EndOfStatement we should return to, and consume it.
1650 JumpToLoc(ActiveMacros.back()->ExitLoc);
1651 Lex();
1652
1653 // Pop the instantiation entry.
1654 delete ActiveMacros.back();
1655 ActiveMacros.pop_back();
1656}
1657
Rafael Espindolae71cc862012-01-28 05:57:00 +00001658static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001659 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001660 case MCExpr::Binary: {
1661 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1662 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001663 break;
1664 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001665 case MCExpr::Target:
1666 case MCExpr::Constant:
1667 return false;
1668 case MCExpr::SymbolRef: {
1669 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001670 if (S.isVariable())
1671 return IsUsedIn(Sym, S.getVariableValue());
1672 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001673 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001674 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001675 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001676 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001677
1678 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001679}
1680
Nico Weber4c4c7322011-01-28 03:04:41 +00001681bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001682 // FIXME: Use better location, we should use proper tokens.
1683 SMLoc EqualLoc = Lexer.getLoc();
1684
Daniel Dunbar821e3332009-08-31 08:09:28 +00001685 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001686 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001687 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001688
Rafael Espindolae71cc862012-01-28 05:57:00 +00001689 // Note: we don't count b as used in "a = b". This is to allow
1690 // a = b
1691 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001692
Daniel Dunbar3f872332009-07-28 16:08:33 +00001693 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001694 return TokError("unexpected token in assignment");
1695
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001696 // Error on assignment to '.'.
1697 if (Name == ".") {
1698 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1699 "(use '.space' or '.org').)"));
1700 }
1701
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001702 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001703 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001704
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001705 // Validate that the LHS is allowed to be a variable (either it has not been
1706 // used as a symbol, or it is an absolute symbol).
1707 MCSymbol *Sym = getContext().LookupSymbol(Name);
1708 if (Sym) {
1709 // Diagnose assignment to a label.
1710 //
1711 // FIXME: Diagnostics. Note the location of the definition as a label.
1712 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00001713 if (IsUsedIn(Sym, Value))
1714 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1715 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001716 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00001717 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1718 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00001719 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001720 return Error(EqualLoc, "redefinition of '" + Name + "'");
1721 else if (!Sym->isVariable())
1722 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00001723 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001724 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1725 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001726
1727 // Don't count these checks as uses.
1728 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001729 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001730 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001731
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001732 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001733
1734 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00001735 Out.EmitAssignment(Sym, Value);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001736
1737 return false;
1738}
1739
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001740/// ParseIdentifier:
1741/// ::= identifier
1742/// ::= string
1743bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00001744 // The assembler has relaxed rules for accepting identifiers, in particular we
1745 // allow things like '.globl $foo', which would normally be separate
1746 // tokens. At this level, we have already lexed so we cannot (currently)
1747 // handle this as a context dependent token, instead we detect adjacent tokens
1748 // and return the combined identifier.
1749 if (Lexer.is(AsmToken::Dollar)) {
1750 SMLoc DollarLoc = getLexer().getLoc();
1751
1752 // Consume the dollar sign, and check for a following identifier.
1753 Lex();
1754 if (Lexer.isNot(AsmToken::Identifier))
1755 return true;
1756
1757 // We have a '$' followed by an identifier, make sure they are adjacent.
1758 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1759 return true;
1760
1761 // Construct the joined identifier and consume the token.
1762 Res = StringRef(DollarLoc.getPointer(),
1763 getTok().getIdentifier().size() + 1);
1764 Lex();
1765 return false;
1766 }
1767
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001768 if (Lexer.isNot(AsmToken::Identifier) &&
1769 Lexer.isNot(AsmToken::String))
1770 return true;
1771
Sean Callanan18b83232010-01-19 21:44:56 +00001772 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001773
Sean Callanan79ed1a82010-01-19 20:22:31 +00001774 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001775
1776 return false;
1777}
1778
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001779/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00001780/// ::= .equ identifier ',' expression
1781/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001782/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00001783bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001784 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001785
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001786 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00001787 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001788
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001789 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00001790 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001791 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001792
Nico Weber4c4c7322011-01-28 03:04:41 +00001793 return ParseAssignment(Name, allow_redef);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001794}
1795
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001796bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001797 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001798
1799 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00001800 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001801 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1802 if (Str[i] != '\\') {
1803 Data += Str[i];
1804 continue;
1805 }
1806
1807 // Recognize escaped characters. Note that this escape semantics currently
1808 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1809 ++i;
1810 if (i == e)
1811 return TokError("unexpected backslash at end of string");
1812
1813 // Recognize octal sequences.
1814 if ((unsigned) (Str[i] - '0') <= 7) {
1815 // Consume up to three octal characters.
1816 unsigned Value = Str[i] - '0';
1817
1818 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1819 ++i;
1820 Value = Value * 8 + (Str[i] - '0');
1821
1822 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1823 ++i;
1824 Value = Value * 8 + (Str[i] - '0');
1825 }
1826 }
1827
1828 if (Value > 255)
1829 return TokError("invalid octal escape sequence (out of range)");
1830
1831 Data += (unsigned char) Value;
1832 continue;
1833 }
1834
1835 // Otherwise recognize individual escapes.
1836 switch (Str[i]) {
1837 default:
1838 // Just reject invalid escape sequences for now.
1839 return TokError("invalid escape sequence (unrecognized character)");
1840
1841 case 'b': Data += '\b'; break;
1842 case 'f': Data += '\f'; break;
1843 case 'n': Data += '\n'; break;
1844 case 'r': Data += '\r'; break;
1845 case 't': Data += '\t'; break;
1846 case '"': Data += '"'; break;
1847 case '\\': Data += '\\'; break;
1848 }
1849 }
1850
1851 return false;
1852}
1853
Daniel Dunbara0d14262009-06-24 23:30:00 +00001854/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00001855/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1856bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001857 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001858 CheckForValidSection();
1859
Daniel Dunbara0d14262009-06-24 23:30:00 +00001860 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001861 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00001862 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001863
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001864 std::string Data;
1865 if (ParseEscapedString(Data))
1866 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001867
1868 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001869 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001870 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1871
Sean Callanan79ed1a82010-01-19 20:22:31 +00001872 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001873
1874 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001875 break;
1876
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001877 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00001878 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001879 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001880 }
1881 }
1882
Sean Callanan79ed1a82010-01-19 20:22:31 +00001883 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001884 return false;
1885}
1886
1887/// ParseDirectiveValue
1888/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1889bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001890 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001891 CheckForValidSection();
1892
Daniel Dunbara0d14262009-06-24 23:30:00 +00001893 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00001894 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00001895 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00001896 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001897 return true;
1898
Daniel Dunbar414c0c42010-05-23 18:36:38 +00001899 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00001900 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1901 assert(Size <= 8 && "Invalid size");
1902 uint64_t IntValue = MCE->getValue();
1903 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1904 return Error(ExprLoc, "literal value out of range for directive");
1905 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1906 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001907 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001908
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001909 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001910 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001911
Daniel Dunbara0d14262009-06-24 23:30:00 +00001912 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001913 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001914 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001915 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001916 }
1917 }
1918
Sean Callanan79ed1a82010-01-19 20:22:31 +00001919 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001920 return false;
1921}
1922
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001923/// ParseDirectiveRealValue
1924/// ::= (.single | .double) [ expression (, expression)* ]
1925bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1926 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1927 CheckForValidSection();
1928
1929 for (;;) {
1930 // We don't truly support arithmetic on floating point expressions, so we
1931 // have to manually parse unary prefixes.
1932 bool IsNeg = false;
1933 if (getLexer().is(AsmToken::Minus)) {
1934 Lex();
1935 IsNeg = true;
1936 } else if (getLexer().is(AsmToken::Plus))
1937 Lex();
1938
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001939 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00001940 getLexer().isNot(AsmToken::Real) &&
1941 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001942 return TokError("unexpected token in directive");
1943
1944 // Convert to an APFloat.
1945 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00001946 StringRef IDVal = getTok().getString();
1947 if (getLexer().is(AsmToken::Identifier)) {
1948 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1949 Value = APFloat::getInf(Semantics);
1950 else if (!IDVal.compare_lower("nan"))
1951 Value = APFloat::getNaN(Semantics, false, ~0);
1952 else
1953 return TokError("invalid floating point literal");
1954 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001955 APFloat::opInvalidOp)
1956 return TokError("invalid floating point literal");
1957 if (IsNeg)
1958 Value.changeSign();
1959
1960 // Consume the numeric token.
1961 Lex();
1962
1963 // Emit the value as an integer.
1964 APInt AsInt = Value.bitcastToAPInt();
1965 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1966 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1967
1968 if (getLexer().is(AsmToken::EndOfStatement))
1969 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001970
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001971 if (getLexer().isNot(AsmToken::Comma))
1972 return TokError("unexpected token in directive");
1973 Lex();
1974 }
1975 }
1976
1977 Lex();
1978 return false;
1979}
1980
Daniel Dunbara0d14262009-06-24 23:30:00 +00001981/// ParseDirectiveSpace
1982/// ::= .space expression [ , expression ]
1983bool AsmParser::ParseDirectiveSpace() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001984 CheckForValidSection();
1985
Daniel Dunbara0d14262009-06-24 23:30:00 +00001986 int64_t NumBytes;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001987 if (ParseAbsoluteExpression(NumBytes))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001988 return true;
1989
1990 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001991 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1992 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001993 return TokError("unexpected token in '.space' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001994 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001995
Daniel Dunbar475839e2009-06-29 20:37:27 +00001996 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001997 return true;
1998
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001999 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002000 return TokError("unexpected token in '.space' directive");
2001 }
2002
Sean Callanan79ed1a82010-01-19 20:22:31 +00002003 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002004
2005 if (NumBytes <= 0)
2006 return TokError("invalid number of bytes in '.space' directive");
2007
2008 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002009 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002010
2011 return false;
2012}
2013
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002014/// ParseDirectiveZero
2015/// ::= .zero expression
2016bool AsmParser::ParseDirectiveZero() {
2017 CheckForValidSection();
2018
2019 int64_t NumBytes;
2020 if (ParseAbsoluteExpression(NumBytes))
2021 return true;
2022
Rafael Espindolae452b172010-10-05 19:42:57 +00002023 int64_t Val = 0;
2024 if (getLexer().is(AsmToken::Comma)) {
2025 Lex();
2026 if (ParseAbsoluteExpression(Val))
2027 return true;
2028 }
2029
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002030 if (getLexer().isNot(AsmToken::EndOfStatement))
2031 return TokError("unexpected token in '.zero' directive");
2032
2033 Lex();
2034
Rafael Espindolae452b172010-10-05 19:42:57 +00002035 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002036
2037 return false;
2038}
2039
Daniel Dunbara0d14262009-06-24 23:30:00 +00002040/// ParseDirectiveFill
2041/// ::= .fill expression , expression , expression
2042bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002043 CheckForValidSection();
2044
Daniel Dunbara0d14262009-06-24 23:30:00 +00002045 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002046 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002047 return true;
2048
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002049 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002050 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002051 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002052
Daniel Dunbara0d14262009-06-24 23:30:00 +00002053 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002054 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002055 return true;
2056
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002057 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002058 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002059 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002060
Daniel Dunbara0d14262009-06-24 23:30:00 +00002061 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002062 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002063 return true;
2064
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002065 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002066 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002067
Sean Callanan79ed1a82010-01-19 20:22:31 +00002068 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002069
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002070 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2071 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002072
2073 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002074 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002075
2076 return false;
2077}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002078
2079/// ParseDirectiveOrg
2080/// ::= .org expression [ , expression ]
2081bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002082 CheckForValidSection();
2083
Daniel Dunbar821e3332009-08-31 08:09:28 +00002084 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002085 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002086 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002087 return true;
2088
2089 // Parse optional fill expression.
2090 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002091 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2092 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002093 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002094 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002095
Daniel Dunbar475839e2009-06-29 20:37:27 +00002096 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002097 return true;
2098
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002099 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002100 return TokError("unexpected token in '.org' directive");
2101 }
2102
Sean Callanan79ed1a82010-01-19 20:22:31 +00002103 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002104
Jim Grosbachebd4c052012-01-27 00:37:08 +00002105 // Only limited forms of relocatable expressions are accepted here, it
2106 // has to be relative to the current section. The streamer will return
2107 // 'true' if the expression wasn't evaluatable.
2108 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2109 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002110
2111 return false;
2112}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002113
2114/// ParseDirectiveAlign
2115/// ::= {.align, ...} expression [ , expression [ , expression ]]
2116bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002117 CheckForValidSection();
2118
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002119 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002120 int64_t Alignment;
2121 if (ParseAbsoluteExpression(Alignment))
2122 return true;
2123
2124 SMLoc MaxBytesLoc;
2125 bool HasFillExpr = false;
2126 int64_t FillExpr = 0;
2127 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002128 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2129 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002130 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002131 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002132
2133 // The fill expression can be omitted while specifying a maximum number of
2134 // alignment bytes, e.g:
2135 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002136 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002137 HasFillExpr = true;
2138 if (ParseAbsoluteExpression(FillExpr))
2139 return true;
2140 }
2141
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002142 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2143 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002144 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002145 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002146
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002147 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002148 if (ParseAbsoluteExpression(MaxBytesToFill))
2149 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002150
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002151 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002152 return TokError("unexpected token in directive");
2153 }
2154 }
2155
Sean Callanan79ed1a82010-01-19 20:22:31 +00002156 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002157
Daniel Dunbar648ac512010-05-17 21:54:30 +00002158 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002159 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002160
2161 // Compute alignment in bytes.
2162 if (IsPow2) {
2163 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002164 if (Alignment >= 32) {
2165 Error(AlignmentLoc, "invalid alignment value");
2166 Alignment = 31;
2167 }
2168
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002169 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002170 }
2171
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002172 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002173 if (MaxBytesLoc.isValid()) {
2174 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002175 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2176 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002177 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002178 }
2179
2180 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002181 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2182 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002183 MaxBytesToFill = 0;
2184 }
2185 }
2186
Daniel Dunbar648ac512010-05-17 21:54:30 +00002187 // Check whether we should use optimal code alignment for this .align
2188 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002189 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002190 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2191 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002192 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002193 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002194 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002195 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2196 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002197 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002198
2199 return false;
2200}
2201
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002202/// ParseDirectiveSymbolAttribute
2203/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00002204bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002205 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002206 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002207 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00002208 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002209
2210 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00002211 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002212
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002213 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002214
Jim Grosbach10ec6502011-09-15 17:56:49 +00002215 // Assembler local symbols don't make any sense here. Complain loudly.
2216 if (Sym->isTemporary())
2217 return Error(Loc, "non-local symbol required in directive");
2218
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002219 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002220
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002221 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002222 break;
2223
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002224 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002225 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002226 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002227 }
2228 }
2229
Sean Callanan79ed1a82010-01-19 20:22:31 +00002230 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00002231 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002232}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002233
2234/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00002235/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2236bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002237 CheckForValidSection();
2238
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002239 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002240 StringRef Name;
2241 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002242 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002243
Daniel Dunbar76c4d762009-07-31 21:55:09 +00002244 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002245 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002246
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002247 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002248 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002249 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002250
2251 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002252 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002253 if (ParseAbsoluteExpression(Size))
2254 return true;
2255
2256 int64_t Pow2Alignment = 0;
2257 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002258 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00002259 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002260 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002261 if (ParseAbsoluteExpression(Pow2Alignment))
2262 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002263
Chris Lattner258281d2010-01-19 06:22:22 +00002264 // If this target takes alignments in bytes (not log) validate and convert.
2265 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2266 if (!isPowerOf2_64(Pow2Alignment))
2267 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2268 Pow2Alignment = Log2_64(Pow2Alignment);
2269 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002270 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002271
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002272 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00002273 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002274
Sean Callanan79ed1a82010-01-19 20:22:31 +00002275 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002276
Chris Lattner1fc3d752009-07-09 17:25:12 +00002277 // NOTE: a size of zero for a .comm should create a undefined symbol
2278 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002279 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002280 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2281 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002282
Eric Christopherc260a3e2010-05-14 01:38:54 +00002283 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002284 // may internally end up wanting an alignment in bytes.
2285 // FIXME: Diagnose overflow.
2286 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002287 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2288 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002289
Daniel Dunbar8906ff12009-08-22 07:22:36 +00002290 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002291 return Error(IDLoc, "invalid symbol redefinition");
2292
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002293 // '.lcomm' is equivalent to '.zerofill'.
Chris Lattner1fc3d752009-07-09 17:25:12 +00002294 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002295 if (IsLocal) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002296 getStreamer().EmitZerofill(Ctx.getMachOSection(
2297 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2298 0, SectionKind::getBSS()),
2299 Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002300 return false;
2301 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002302
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002303 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002304 return false;
2305}
Chris Lattner9be3fee2009-07-10 22:20:30 +00002306
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002307/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002308/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002309bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002310 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002311 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002312
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002313 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002314 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002315 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002316
Sean Callanan79ed1a82010-01-19 20:22:31 +00002317 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002318
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002319 if (Str.empty())
2320 Error(Loc, ".abort detected. Assembly stopping.");
2321 else
2322 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002323 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002324
2325 return false;
2326}
Kevin Enderby71148242009-07-14 21:35:03 +00002327
Kevin Enderby1f049b22009-07-14 23:21:55 +00002328/// ParseDirectiveInclude
2329/// ::= .include "filename"
2330bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002331 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002332 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002333
Sean Callanan18b83232010-01-19 21:44:56 +00002334 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002335 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002336 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00002337
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002338 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002339 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002340
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002341 // Strip the quotes.
2342 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002343
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002344 // Attempt to switch the lexer to the included file before consuming the end
2345 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00002346 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00002347 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002348 return true;
2349 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00002350
2351 return false;
2352}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00002353
Kevin Enderbyc55acca2011-12-14 21:47:48 +00002354/// ParseDirectiveIncbin
2355/// ::= .incbin "filename"
2356bool AsmParser::ParseDirectiveIncbin() {
2357 if (getLexer().isNot(AsmToken::String))
2358 return TokError("expected string in '.incbin' directive");
2359
2360 std::string Filename = getTok().getString();
2361 SMLoc IncbinLoc = getLexer().getLoc();
2362 Lex();
2363
2364 if (getLexer().isNot(AsmToken::EndOfStatement))
2365 return TokError("unexpected token in '.incbin' directive");
2366
2367 // Strip the quotes.
2368 Filename = Filename.substr(1, Filename.size()-2);
2369
2370 // Attempt to process the included file.
2371 if (ProcessIncbinFile(Filename)) {
2372 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2373 return true;
2374 }
2375
2376 return false;
2377}
2378
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002379/// ParseDirectiveIf
2380/// ::= .if expression
2381bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002382 TheCondStack.push_back(TheCondState);
2383 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00002384 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002385 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00002386 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002387 int64_t ExprValue;
2388 if (ParseAbsoluteExpression(ExprValue))
2389 return true;
2390
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002391 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002392 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002393
Sean Callanan79ed1a82010-01-19 20:22:31 +00002394 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002395
2396 TheCondState.CondMet = ExprValue;
2397 TheCondState.Ignore = !TheCondState.CondMet;
2398 }
2399
2400 return false;
2401}
2402
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002403/// ParseDirectiveIfb
2404/// ::= .ifb string
2405bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2406 TheCondStack.push_back(TheCondState);
2407 TheCondState.TheCond = AsmCond::IfCond;
2408
Benjamin Kramer29739e72012-05-12 16:52:21 +00002409 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002410 EatToEndOfStatement();
2411 } else {
2412 StringRef Str = ParseStringToEndOfStatement();
2413
2414 if (getLexer().isNot(AsmToken::EndOfStatement))
2415 return TokError("unexpected token in '.ifb' directive");
2416
2417 Lex();
2418
2419 TheCondState.CondMet = ExpectBlank == Str.empty();
2420 TheCondState.Ignore = !TheCondState.CondMet;
2421 }
2422
2423 return false;
2424}
2425
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002426/// ParseDirectiveIfc
2427/// ::= .ifc string1, string2
2428bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2429 TheCondStack.push_back(TheCondState);
2430 TheCondState.TheCond = AsmCond::IfCond;
2431
Benjamin Kramer29739e72012-05-12 16:52:21 +00002432 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002433 EatToEndOfStatement();
2434 } else {
2435 StringRef Str1 = ParseStringToComma();
2436
2437 if (getLexer().isNot(AsmToken::Comma))
2438 return TokError("unexpected token in '.ifc' directive");
2439
2440 Lex();
2441
2442 StringRef Str2 = ParseStringToEndOfStatement();
2443
2444 if (getLexer().isNot(AsmToken::EndOfStatement))
2445 return TokError("unexpected token in '.ifc' directive");
2446
2447 Lex();
2448
2449 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2450 TheCondState.Ignore = !TheCondState.CondMet;
2451 }
2452
2453 return false;
2454}
2455
2456/// ParseDirectiveIfdef
2457/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00002458bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2459 StringRef Name;
2460 TheCondStack.push_back(TheCondState);
2461 TheCondState.TheCond = AsmCond::IfCond;
2462
2463 if (TheCondState.Ignore) {
2464 EatToEndOfStatement();
2465 } else {
2466 if (ParseIdentifier(Name))
2467 return TokError("expected identifier after '.ifdef'");
2468
2469 Lex();
2470
2471 MCSymbol *Sym = getContext().LookupSymbol(Name);
2472
2473 if (expect_defined)
2474 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2475 else
2476 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2477 TheCondState.Ignore = !TheCondState.CondMet;
2478 }
2479
2480 return false;
2481}
2482
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002483/// ParseDirectiveElseIf
2484/// ::= .elseif expression
2485bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2486 if (TheCondState.TheCond != AsmCond::IfCond &&
2487 TheCondState.TheCond != AsmCond::ElseIfCond)
2488 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2489 " an .elseif");
2490 TheCondState.TheCond = AsmCond::ElseIfCond;
2491
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002492 bool LastIgnoreState = false;
2493 if (!TheCondStack.empty())
2494 LastIgnoreState = TheCondStack.back().Ignore;
2495 if (LastIgnoreState || TheCondState.CondMet) {
2496 TheCondState.Ignore = true;
2497 EatToEndOfStatement();
2498 }
2499 else {
2500 int64_t ExprValue;
2501 if (ParseAbsoluteExpression(ExprValue))
2502 return true;
2503
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002504 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002505 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002506
Sean Callanan79ed1a82010-01-19 20:22:31 +00002507 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002508 TheCondState.CondMet = ExprValue;
2509 TheCondState.Ignore = !TheCondState.CondMet;
2510 }
2511
2512 return false;
2513}
2514
2515/// ParseDirectiveElse
2516/// ::= .else
2517bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002518 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002519 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002520
Sean Callanan79ed1a82010-01-19 20:22:31 +00002521 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002522
2523 if (TheCondState.TheCond != AsmCond::IfCond &&
2524 TheCondState.TheCond != AsmCond::ElseIfCond)
2525 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2526 ".elseif");
2527 TheCondState.TheCond = AsmCond::ElseCond;
2528 bool LastIgnoreState = false;
2529 if (!TheCondStack.empty())
2530 LastIgnoreState = TheCondStack.back().Ignore;
2531 if (LastIgnoreState || TheCondState.CondMet)
2532 TheCondState.Ignore = true;
2533 else
2534 TheCondState.Ignore = false;
2535
2536 return false;
2537}
2538
2539/// ParseDirectiveEndIf
2540/// ::= .endif
2541bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002542 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002543 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002544
Sean Callanan79ed1a82010-01-19 20:22:31 +00002545 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002546
2547 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2548 TheCondStack.empty())
2549 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2550 ".else");
2551 if (!TheCondStack.empty()) {
2552 TheCondState = TheCondStack.back();
2553 TheCondStack.pop_back();
2554 }
2555
2556 return false;
2557}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002558
2559/// ParseDirectiveFile
Nick Lewycky44d798d2011-10-17 23:05:28 +00002560/// ::= .file [number] filename
2561/// ::= .file number directory filename
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002562bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002563 // FIXME: I'm not sure what this is.
2564 int64_t FileNumber = -1;
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002565 SMLoc FileNumberLoc = getLexer().getLoc();
Daniel Dunbareceec052010-07-12 17:45:27 +00002566 if (getLexer().is(AsmToken::Integer)) {
Sean Callanan18b83232010-01-19 21:44:56 +00002567 FileNumber = getTok().getIntVal();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002568 Lex();
Daniel Dunbareceec052010-07-12 17:45:27 +00002569
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002570 if (FileNumber < 1)
2571 return TokError("file number less than one");
2572 }
2573
Daniel Dunbareceec052010-07-12 17:45:27 +00002574 if (getLexer().isNot(AsmToken::String))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002575 return TokError("unexpected token in '.file' directive");
Daniel Dunbareceec052010-07-12 17:45:27 +00002576
Nick Lewycky44d798d2011-10-17 23:05:28 +00002577 // Usually the directory and filename together, otherwise just the directory.
2578 StringRef Path = getTok().getString();
2579 Path = Path.substr(1, Path.size()-2);
Sean Callanan79ed1a82010-01-19 20:22:31 +00002580 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002581
Nick Lewycky44d798d2011-10-17 23:05:28 +00002582 StringRef Directory;
2583 StringRef Filename;
2584 if (getLexer().is(AsmToken::String)) {
2585 if (FileNumber == -1)
2586 return TokError("explicit path specified, but no file number");
2587 Filename = getTok().getString();
2588 Filename = Filename.substr(1, Filename.size()-2);
2589 Directory = Path;
2590 Lex();
2591 } else {
2592 Filename = Path;
2593 }
2594
Daniel Dunbareceec052010-07-12 17:45:27 +00002595 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002596 return TokError("unexpected token in '.file' directive");
2597
Chris Lattnerd32e8032010-01-25 19:02:58 +00002598 if (FileNumber == -1)
Daniel Dunbareceec052010-07-12 17:45:27 +00002599 getStreamer().EmitFileDirective(Filename);
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002600 else {
Kevin Enderby8704b782012-01-11 18:04:47 +00002601 if (getContext().getGenDwarfForAssembly() == true)
2602 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2603 "used to generate dwarf debug info for assembly code");
2604
Nick Lewycky44d798d2011-10-17 23:05:28 +00002605 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002606 Error(FileNumberLoc, "file number already allocated");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002607 }
Daniel Dunbareceec052010-07-12 17:45:27 +00002608
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002609 return false;
2610}
2611
2612/// ParseDirectiveLine
2613/// ::= .line [number]
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002614bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbareceec052010-07-12 17:45:27 +00002615 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2616 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002617 return TokError("unexpected token in '.line' directive");
2618
Sean Callanan18b83232010-01-19 21:44:56 +00002619 int64_t LineNumber = getTok().getIntVal();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002620 (void) LineNumber;
Sean Callanan79ed1a82010-01-19 20:22:31 +00002621 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002622
2623 // FIXME: Do something with the .line.
2624 }
2625
Daniel Dunbareceec052010-07-12 17:45:27 +00002626 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar839348a2010-07-01 20:20:01 +00002627 return TokError("unexpected token in '.line' directive");
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002628
2629 return false;
2630}
2631
2632
2633/// ParseDirectiveLoc
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002634/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002635/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2636/// The first number is a file number, must have been previously assigned with
2637/// a .file directive, the second number is the line number and optionally the
2638/// third number is a column position (zero if not specified). The remaining
2639/// optional items are .loc sub-directives.
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002640bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002641
Daniel Dunbareceec052010-07-12 17:45:27 +00002642 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002643 return TokError("unexpected token in '.loc' directive");
Sean Callanan18b83232010-01-19 21:44:56 +00002644 int64_t FileNumber = getTok().getIntVal();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002645 if (FileNumber < 1)
2646 return TokError("file number less than one in '.loc' directive");
Kevin Enderby3f55c242010-10-04 20:17:24 +00002647 if (!getContext().isValidDwarfFileNumber(FileNumber))
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002648 return TokError("unassigned file number in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002649 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002650
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002651 int64_t LineNumber = 0;
2652 if (getLexer().is(AsmToken::Integer)) {
2653 LineNumber = getTok().getIntVal();
2654 if (LineNumber < 1)
2655 return TokError("line number less than one in '.loc' directive");
2656 Lex();
2657 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002658
2659 int64_t ColumnPos = 0;
2660 if (getLexer().is(AsmToken::Integer)) {
2661 ColumnPos = getTok().getIntVal();
2662 if (ColumnPos < 0)
2663 return TokError("column position less than zero in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002664 Lex();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002665 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002666
Kevin Enderbyc0957932010-09-30 16:52:03 +00002667 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002668 unsigned Isa = 0;
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002669 int64_t Discriminator = 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002670 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2671 for (;;) {
2672 if (getLexer().is(AsmToken::EndOfStatement))
2673 break;
2674
2675 StringRef Name;
2676 SMLoc Loc = getTok().getLoc();
2677 if (getParser().ParseIdentifier(Name))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002678 return TokError("unexpected token in '.loc' directive");
2679
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002680 if (Name == "basic_block")
2681 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2682 else if (Name == "prologue_end")
2683 Flags |= DWARF2_FLAG_PROLOGUE_END;
2684 else if (Name == "epilogue_begin")
2685 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2686 else if (Name == "is_stmt") {
2687 SMLoc Loc = getTok().getLoc();
2688 const MCExpr *Value;
2689 if (getParser().ParseExpression(Value))
2690 return true;
2691 // The expression must be the constant 0 or 1.
2692 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2693 int Value = MCE->getValue();
2694 if (Value == 0)
2695 Flags &= ~DWARF2_FLAG_IS_STMT;
2696 else if (Value == 1)
2697 Flags |= DWARF2_FLAG_IS_STMT;
2698 else
2699 return Error(Loc, "is_stmt value not 0 or 1");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002700 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002701 else {
2702 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2703 }
2704 }
2705 else if (Name == "isa") {
2706 SMLoc Loc = getTok().getLoc();
2707 const MCExpr *Value;
2708 if (getParser().ParseExpression(Value))
2709 return true;
2710 // The expression must be a constant greater or equal to 0.
2711 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2712 int Value = MCE->getValue();
2713 if (Value < 0)
2714 return Error(Loc, "isa number less than zero");
2715 Isa = Value;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002716 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002717 else {
2718 return Error(Loc, "isa number not a constant value");
2719 }
2720 }
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002721 else if (Name == "discriminator") {
2722 if (getParser().ParseAbsoluteExpression(Discriminator))
2723 return true;
2724 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002725 else {
2726 return Error(Loc, "unknown sub-directive in '.loc' directive");
2727 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002728
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002729 if (getLexer().is(AsmToken::EndOfStatement))
2730 break;
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002731 }
2732 }
2733
Rafael Espindolaaf6b58082010-11-16 21:20:32 +00002734 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
Devang Patel3f3bf932011-04-18 20:26:49 +00002735 Isa, Discriminator, StringRef());
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002736
2737 return false;
2738}
2739
Daniel Dunbar138abae2010-10-16 04:56:42 +00002740/// ParseDirectiveStabs
2741/// ::= .stabs string, number, number, number
2742bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2743 SMLoc DirectiveLoc) {
2744 return TokError("unsupported directive '" + Directive + "'");
2745}
2746
Rafael Espindolaf9efd832011-05-10 01:10:18 +00002747/// ParseDirectiveCFISections
2748/// ::= .cfi_sections section [, section]
2749bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2750 SMLoc DirectiveLoc) {
2751 StringRef Name;
2752 bool EH = false;
2753 bool Debug = false;
2754
2755 if (getParser().ParseIdentifier(Name))
2756 return TokError("Expected an identifier");
2757
2758 if (Name == ".eh_frame")
2759 EH = true;
2760 else if (Name == ".debug_frame")
2761 Debug = true;
2762
2763 if (getLexer().is(AsmToken::Comma)) {
2764 Lex();
2765
2766 if (getParser().ParseIdentifier(Name))
2767 return TokError("Expected an identifier");
2768
2769 if (Name == ".eh_frame")
2770 EH = true;
2771 else if (Name == ".debug_frame")
2772 Debug = true;
2773 }
2774
2775 getStreamer().EmitCFISections(EH, Debug);
2776
2777 return false;
2778}
2779
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002780/// ParseDirectiveCFIStartProc
2781/// ::= .cfi_startproc
2782bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2783 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002784 getStreamer().EmitCFIStartProc();
2785 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002786}
2787
2788/// ParseDirectiveCFIEndProc
2789/// ::= .cfi_endproc
2790bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002791 getStreamer().EmitCFIEndProc();
2792 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002793}
2794
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002795/// ParseRegisterOrRegisterNumber - parse register name or number.
2796bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2797 SMLoc DirectiveLoc) {
2798 unsigned RegNo;
2799
Jim Grosbach6f888a82011-06-02 17:14:04 +00002800 if (getLexer().isNot(AsmToken::Integer)) {
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002801 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2802 DirectiveLoc))
2803 return true;
Evan Cheng0e6a0522011-07-18 20:57:22 +00002804 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002805 } else
2806 return getParser().ParseAbsoluteExpression(Register);
Jim Grosbachde2f5f42011-02-11 19:05:56 +00002807
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002808 return false;
2809}
2810
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002811/// ParseDirectiveCFIDefCfa
2812/// ::= .cfi_def_cfa register, offset
2813bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2814 SMLoc DirectiveLoc) {
2815 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002816 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002817 return true;
2818
2819 if (getLexer().isNot(AsmToken::Comma))
2820 return TokError("unexpected token in directive");
2821 Lex();
2822
2823 int64_t Offset = 0;
2824 if (getParser().ParseAbsoluteExpression(Offset))
2825 return true;
2826
Rafael Espindola066c2f42011-04-12 23:59:07 +00002827 getStreamer().EmitCFIDefCfa(Register, Offset);
2828 return false;
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002829}
2830
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002831/// ParseDirectiveCFIDefCfaOffset
2832/// ::= .cfi_def_cfa_offset offset
2833bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2834 SMLoc DirectiveLoc) {
2835 int64_t Offset = 0;
2836 if (getParser().ParseAbsoluteExpression(Offset))
2837 return true;
2838
Rafael Espindola066c2f42011-04-12 23:59:07 +00002839 getStreamer().EmitCFIDefCfaOffset(Offset);
2840 return false;
Rafael Espindola53abbe52011-04-11 20:29:16 +00002841}
2842
2843/// ParseDirectiveCFIAdjustCfaOffset
2844/// ::= .cfi_adjust_cfa_offset adjustment
2845bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2846 SMLoc DirectiveLoc) {
2847 int64_t Adjustment = 0;
2848 if (getParser().ParseAbsoluteExpression(Adjustment))
2849 return true;
2850
Rafael Espindola5d7dcd32011-04-12 18:53:30 +00002851 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2852 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002853}
2854
2855/// ParseDirectiveCFIDefCfaRegister
2856/// ::= .cfi_def_cfa_register register
2857bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2858 SMLoc DirectiveLoc) {
2859 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002860 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002861 return true;
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002862
Rafael Espindola066c2f42011-04-12 23:59:07 +00002863 getStreamer().EmitCFIDefCfaRegister(Register);
2864 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002865}
2866
2867/// ParseDirectiveCFIOffset
Rafael Espindolaa61842b2011-04-11 21:49:50 +00002868/// ::= .cfi_offset register, offset
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002869bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2870 int64_t Register = 0;
2871 int64_t Offset = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002872
2873 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002874 return true;
2875
2876 if (getLexer().isNot(AsmToken::Comma))
2877 return TokError("unexpected token in directive");
2878 Lex();
2879
2880 if (getParser().ParseAbsoluteExpression(Offset))
2881 return true;
2882
Rafael Espindola066c2f42011-04-12 23:59:07 +00002883 getStreamer().EmitCFIOffset(Register, Offset);
2884 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002885}
2886
Rafael Espindolaa61842b2011-04-11 21:49:50 +00002887/// ParseDirectiveCFIRelOffset
2888/// ::= .cfi_rel_offset register, offset
2889bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2890 SMLoc DirectiveLoc) {
2891 int64_t Register = 0;
2892
2893 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2894 return true;
2895
2896 if (getLexer().isNot(AsmToken::Comma))
2897 return TokError("unexpected token in directive");
2898 Lex();
2899
2900 int64_t Offset = 0;
2901 if (getParser().ParseAbsoluteExpression(Offset))
2902 return true;
2903
Rafael Espindola25f492e2011-04-12 16:12:03 +00002904 getStreamer().EmitCFIRelOffset(Register, Offset);
2905 return false;
Rafael Espindolaa61842b2011-04-11 21:49:50 +00002906}
2907
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002908static bool isValidEncoding(int64_t Encoding) {
2909 if (Encoding & ~0xff)
2910 return false;
2911
2912 if (Encoding == dwarf::DW_EH_PE_omit)
2913 return true;
2914
2915 const unsigned Format = Encoding & 0xf;
2916 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2917 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2918 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2919 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2920 return false;
2921
Rafael Espindolacaf11582010-12-29 04:31:26 +00002922 const unsigned Application = Encoding & 0x70;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002923 if (Application != dwarf::DW_EH_PE_absptr &&
Rafael Espindolacaf11582010-12-29 04:31:26 +00002924 Application != dwarf::DW_EH_PE_pcrel)
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002925 return false;
2926
2927 return true;
2928}
2929
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002930/// ParseDirectiveCFIPersonalityOrLsda
2931/// ::= .cfi_personality encoding, [symbol_name]
2932/// ::= .cfi_lsda encoding, [symbol_name]
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002933bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002934 SMLoc DirectiveLoc) {
2935 int64_t Encoding = 0;
2936 if (getParser().ParseAbsoluteExpression(Encoding))
2937 return true;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002938 if (Encoding == dwarf::DW_EH_PE_omit)
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002939 return false;
2940
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002941 if (!isValidEncoding(Encoding))
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002942 return TokError("unsupported encoding.");
2943
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002944 if (getLexer().isNot(AsmToken::Comma))
2945 return TokError("unexpected token in directive");
2946 Lex();
2947
2948 StringRef Name;
2949 if (getParser().ParseIdentifier(Name))
2950 return TokError("expected identifier in directive");
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002951
2952 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2953
2954 if (IDVal == ".cfi_personality")
Rafael Espindola066c2f42011-04-12 23:59:07 +00002955 getStreamer().EmitCFIPersonality(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002956 else {
2957 assert(IDVal == ".cfi_lsda");
Rafael Espindola066c2f42011-04-12 23:59:07 +00002958 getStreamer().EmitCFILsda(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002959 }
Rafael Espindola066c2f42011-04-12 23:59:07 +00002960 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002961}
2962
Rafael Espindolafe024d02010-12-28 18:36:23 +00002963/// ParseDirectiveCFIRememberState
2964/// ::= .cfi_remember_state
2965bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2966 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002967 getStreamer().EmitCFIRememberState();
2968 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00002969}
2970
2971/// ParseDirectiveCFIRestoreState
2972/// ::= .cfi_remember_state
2973bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2974 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002975 getStreamer().EmitCFIRestoreState();
2976 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00002977}
2978
Rafael Espindolac5754392011-04-12 15:31:05 +00002979/// ParseDirectiveCFISameValue
2980/// ::= .cfi_same_value register
2981bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2982 SMLoc DirectiveLoc) {
2983 int64_t Register = 0;
2984
2985 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2986 return true;
2987
2988 getStreamer().EmitCFISameValue(Register);
2989
2990 return false;
2991}
2992
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00002993/// ParseDirectiveCFIRestore
2994/// ::= .cfi_restore register
2995bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
2996 SMLoc DirectiveLoc) {
2997 int64_t Register = 0;
2998 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2999 return true;
3000
3001 getStreamer().EmitCFIRestore(Register);
3002
3003 return false;
3004}
3005
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003006/// ParseDirectiveCFIEscape
3007/// ::= .cfi_escape expression[,...]
3008bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
3009 SMLoc DirectiveLoc) {
3010 std::string Values;
3011 int64_t CurrValue;
3012 if (getParser().ParseAbsoluteExpression(CurrValue))
3013 return true;
3014
3015 Values.push_back((uint8_t)CurrValue);
3016
3017 while (getLexer().is(AsmToken::Comma)) {
3018 Lex();
3019
3020 if (getParser().ParseAbsoluteExpression(CurrValue))
3021 return true;
3022
3023 Values.push_back((uint8_t)CurrValue);
3024 }
3025
3026 getStreamer().EmitCFIEscape(Values);
3027 return false;
3028}
3029
Rafael Espindola16d7d432012-01-23 21:51:52 +00003030/// ParseDirectiveCFISignalFrame
3031/// ::= .cfi_signal_frame
3032bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3033 SMLoc DirectiveLoc) {
3034 if (getLexer().isNot(AsmToken::EndOfStatement))
3035 return Error(getLexer().getLoc(),
3036 "unexpected token in '" + Directive + "' directive");
3037
3038 getStreamer().EmitCFISignalFrame();
3039
3040 return false;
3041}
3042
Daniel Dunbar3c802de2010-07-18 18:38:02 +00003043/// ParseDirectiveMacrosOnOff
3044/// ::= .macros_on
3045/// ::= .macros_off
3046bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3047 SMLoc DirectiveLoc) {
3048 if (getLexer().isNot(AsmToken::EndOfStatement))
3049 return Error(getLexer().getLoc(),
3050 "unexpected token in '" + Directive + "' directive");
3051
3052 getParser().MacrosEnabled = Directive == ".macros_on";
3053
3054 return false;
3055}
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003056
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003057/// ParseDirectiveMacro
Rafael Espindola65366442011-06-05 02:43:45 +00003058/// ::= .macro name [parameters]
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003059bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3060 SMLoc DirectiveLoc) {
3061 StringRef Name;
3062 if (getParser().ParseIdentifier(Name))
3063 return TokError("expected identifier in directive");
3064
Rafael Espindola65366442011-06-05 02:43:45 +00003065 std::vector<StringRef> Parameters;
3066 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3067 for(;;) {
3068 StringRef Parameter;
3069 if (getParser().ParseIdentifier(Parameter))
3070 return TokError("expected identifier in directive");
3071 Parameters.push_back(Parameter);
3072
3073 if (getLexer().isNot(AsmToken::Comma))
3074 break;
3075 Lex();
3076 }
3077 }
3078
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003079 if (getLexer().isNot(AsmToken::EndOfStatement))
3080 return TokError("unexpected token in '.macro' directive");
3081
3082 // Eat the end of statement.
3083 Lex();
3084
3085 AsmToken EndToken, StartToken = getTok();
3086
3087 // Lex the macro definition.
3088 for (;;) {
3089 // Check whether we have reached the end of the file.
3090 if (getLexer().is(AsmToken::Eof))
3091 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3092
3093 // Otherwise, check whether we have reach the .endmacro.
3094 if (getLexer().is(AsmToken::Identifier) &&
3095 (getTok().getIdentifier() == ".endm" ||
3096 getTok().getIdentifier() == ".endmacro")) {
3097 EndToken = getTok();
3098 Lex();
3099 if (getLexer().isNot(AsmToken::EndOfStatement))
3100 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3101 "' directive");
3102 break;
3103 }
3104
3105 // Otherwise, scan til the end of the statement.
3106 getParser().EatToEndOfStatement();
3107 }
3108
3109 if (getParser().MacroMap.lookup(Name)) {
3110 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3111 }
3112
3113 const char *BodyStart = StartToken.getLoc().getPointer();
3114 const char *BodyEnd = EndToken.getLoc().getPointer();
3115 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Rafael Espindola65366442011-06-05 02:43:45 +00003116 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003117 return false;
3118}
3119
3120/// ParseDirectiveEndMacro
3121/// ::= .endm
3122/// ::= .endmacro
3123bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
3124 SMLoc DirectiveLoc) {
3125 if (getLexer().isNot(AsmToken::EndOfStatement))
3126 return TokError("unexpected token in '" + Directive + "' directive");
3127
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00003128 // If we are inside a macro instantiation, terminate the current
3129 // instantiation.
3130 if (!getParser().ActiveMacros.empty()) {
3131 getParser().HandleMacroExit();
3132 return false;
3133 }
3134
3135 // Otherwise, this .endmacro is a stray entry in the file; well formed
3136 // .endmacro directives are handled during the macro definition parsing.
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003137 return TokError("unexpected '" + Directive + "' in file, "
3138 "no current macro definition");
3139}
3140
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +00003141/// ParseDirectivePurgeMacro
3142/// ::= .purgem
3143bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3144 SMLoc DirectiveLoc) {
3145 StringRef Name;
3146 if (getParser().ParseIdentifier(Name))
3147 return TokError("expected identifier in '.purgem' directive");
3148
3149 if (getLexer().isNot(AsmToken::EndOfStatement))
3150 return TokError("unexpected token in '.purgem' directive");
3151
3152 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3153 if (I == getParser().MacroMap.end())
3154 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3155
3156 // Undefine the macro.
3157 delete I->getValue();
3158 getParser().MacroMap.erase(I);
3159 return false;
3160}
3161
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003162bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
Rafael Espindola3ff57092010-11-02 17:22:24 +00003163 getParser().CheckForValidSection();
3164
3165 const MCExpr *Value;
3166
3167 if (getParser().ParseExpression(Value))
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003168 return true;
3169
3170 if (getLexer().isNot(AsmToken::EndOfStatement))
3171 return TokError("unexpected token in directive");
3172
3173 if (DirName[1] == 's')
Rafael Espindola3ff57092010-11-02 17:22:24 +00003174 getStreamer().EmitSLEB128Value(Value);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003175 else
Rafael Espindola3ff57092010-11-02 17:22:24 +00003176 getStreamer().EmitULEB128Value(Value);
3177
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003178 return false;
3179}
3180
Rafael Espindola761cb062012-06-03 23:57:14 +00003181Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003182 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003183
Rafael Espindola761cb062012-06-03 23:57:14 +00003184 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003185 for (;;) {
3186 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003187 if (getLexer().is(AsmToken::Eof)) {
3188 Error(DirectiveLoc, "no matching '.endr' in definition");
3189 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003190 }
3191
Rafael Espindola761cb062012-06-03 23:57:14 +00003192 if (Lexer.is(AsmToken::Identifier) &&
3193 (getTok().getIdentifier() == ".rept")) {
3194 ++NestLevel;
3195 }
3196
3197 // Otherwise, check whether we have reached the .endr.
3198 if (Lexer.is(AsmToken::Identifier) &&
3199 getTok().getIdentifier() == ".endr") {
3200 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003201 EndToken = getTok();
3202 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003203 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3204 TokError("unexpected token in '.endr' directive");
3205 return 0;
3206 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003207 break;
3208 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003209 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003210 }
3211
Rafael Espindola761cb062012-06-03 23:57:14 +00003212 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003213 EatToEndOfStatement();
3214 }
3215
3216 const char *BodyStart = StartToken.getLoc().getPointer();
3217 const char *BodyEnd = EndToken.getLoc().getPointer();
3218 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3219
Rafael Espindola761cb062012-06-03 23:57:14 +00003220 // We Are Anonymous.
3221 StringRef Name;
3222 std::vector<StringRef> Parameters;
3223 return new Macro(Name, Body, Parameters);
3224}
3225
3226void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3227 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003228 OS << ".endr\n";
3229
3230 MemoryBuffer *Instantiation =
3231 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3232
Rafael Espindola761cb062012-06-03 23:57:14 +00003233 // Create the macro instantiation object and add to the current macro
3234 // instantiation stack.
3235 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
3236 getTok().getLoc(),
3237 Instantiation);
3238 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003239
Rafael Espindola761cb062012-06-03 23:57:14 +00003240 // Jump to the macro instantiation and prime the lexer.
3241 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3242 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3243 Lex();
3244}
3245
3246bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3247 int64_t Count;
3248 if (ParseAbsoluteExpression(Count))
3249 return TokError("unexpected token in '.rept' directive");
3250
3251 if (Count < 0)
3252 return TokError("Count is negative");
3253
3254 if (Lexer.isNot(AsmToken::EndOfStatement))
3255 return TokError("unexpected token in '.rept' directive");
3256
3257 // Eat the end of statement.
3258 Lex();
3259
3260 // Lex the rept definition.
3261 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3262 if (!M)
3263 return true;
3264
3265 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3266 // to hold the macro body with substitutions.
3267 SmallString<256> Buf;
3268 std::vector<StringRef> Parameters;
3269 const std::vector<MacroArgument> A;
3270 raw_svector_ostream OS(Buf);
3271 while (Count--) {
3272 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3273 return true;
3274 }
3275 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003276
3277 return false;
3278}
3279
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003280/// ParseDirectiveIrp
3281/// ::= .irp symbol,values
3282bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
3283 std::vector<StringRef> Parameters;
3284 StringRef Parameter;
3285
3286 if (ParseIdentifier(Parameter))
3287 return TokError("expected identifier in '.irp' directive");
3288
3289 Parameters.push_back(Parameter);
3290
3291 if (Lexer.isNot(AsmToken::Comma))
3292 return TokError("expected comma in '.irp' directive");
3293
3294 Lex();
3295
3296 std::vector<MacroArgument> A;
3297 if (ParseMacroArguments(0, A))
3298 return true;
3299
3300 // Eat the end of statement.
3301 Lex();
3302
3303 // Lex the irp definition.
3304 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3305 if (!M)
3306 return true;
3307
3308 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3309 // to hold the macro body with substitutions.
3310 SmallString<256> Buf;
3311 raw_svector_ostream OS(Buf);
3312
3313 for (std::vector<MacroArgument>::iterator i = A.begin(), e = A.end(); i != e;
3314 ++i) {
3315 std::vector<MacroArgument> Args;
3316 Args.push_back(*i);
3317
3318 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3319 return true;
3320 }
3321
3322 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3323
3324 return false;
3325}
3326
Rafael Espindola761cb062012-06-03 23:57:14 +00003327bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3328 if (ActiveMacros.empty())
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003329 return TokError("unexpected '.endr' directive, no current .rept");
3330
3331 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003332 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003333 assert(getLexer().is(AsmToken::EndOfStatement));
3334
Rafael Espindola761cb062012-06-03 23:57:14 +00003335 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003336 return false;
3337}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003338
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003339/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003340MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003341 MCContext &C, MCStreamer &Out,
3342 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003343 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003344}