blob: 93492377ff0637815566d813cb062f0e7dbe4a82 [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"
Matt Fleming924c5e52010-05-21 11:36:59 +000017#include "llvm/ADT/StringSwitch.h"
Daniel Dunbarf9507ff2009-07-27 23:20:52 +000018#include "llvm/ADT/Twine.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000019#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000020#include "llvm/MC/MCContext.h"
Evan Cheng94b95502011-07-26 00:24:13 +000021#include "llvm/MC/MCDwarf.h"
Daniel Dunbar28c251b2009-08-31 08:06:59 +000022#include "llvm/MC/MCExpr.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000023#include "llvm/MC/MCParser/AsmCond.h"
24#include "llvm/MC/MCParser/AsmLexer.h"
25#include "llvm/MC/MCParser/MCAsmParser.h"
26#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Evan Chenge76a33b2011-07-20 05:58:47 +000027#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000028#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000029#include "llvm/MC/MCStreamer.h"
Daniel Dunbardce0f3c2009-06-29 23:43:14 +000030#include "llvm/MC/MCSymbol.h"
Evan Cheng94b95502011-07-26 00:24:13 +000031#include "llvm/MC/MCTargetAsmParser.h"
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000032#include "llvm/Support/CommandLine.h"
Jim Grosbach254cf032011-06-29 16:05:14 +000033#include "llvm/Support/MathExtras.h"
Kevin Enderbyf187ac52010-06-28 21:45:58 +000034#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000035#include "llvm/Support/SourceMgr.h"
Chris Lattnerb0789ed2009-06-21 20:54:55 +000036#include "llvm/Support/raw_ostream.h"
Nick Lewycky476b2422010-12-19 20:43:38 +000037#include <cctype>
Daniel Dunbaraef87e32010-07-18 18:31:38 +000038#include <vector>
Chris Lattner27aa7d22009-06-21 20:16:42 +000039using namespace llvm;
40
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000041static cl::opt<bool>
42FatalAssemblerWarnings("fatal-assembler-warnings",
43 cl::desc("Consider warnings as error"));
44
Daniel Dunbar81ea00f2010-07-12 17:54:38 +000045namespace {
46
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000047/// \brief Helper class for tracking macro definitions.
48struct Macro {
49 StringRef Name;
50 StringRef Body;
Rafael Espindola65366442011-06-05 02:43:45 +000051 std::vector<StringRef> Parameters;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000052
53public:
Rafael Espindola65366442011-06-05 02:43:45 +000054 Macro(StringRef N, StringRef B, const std::vector<StringRef> &P) :
55 Name(N), Body(B), Parameters(P) {}
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000056};
57
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000058/// \brief Helper class for storing information about an active macro
59/// instantiation.
60struct MacroInstantiation {
61 /// The macro being instantiated.
62 const Macro *TheMacro;
63
64 /// The macro instantiation with substitutions.
65 MemoryBuffer *Instantiation;
66
67 /// The location of the instantiation.
68 SMLoc InstantiationLoc;
69
70 /// The location where parsing should resume upon instantiation completion.
71 SMLoc ExitLoc;
72
73public:
Daniel Dunbar7a570d02010-07-18 19:00:10 +000074 MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000075 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000076};
77
Daniel Dunbaraef87e32010-07-18 18:31:38 +000078/// \brief The concrete assembly parser instance.
79class AsmParser : public MCAsmParser {
Daniel Dunbar3c802de2010-07-18 18:38:02 +000080 friend class GenericAsmParser;
81
Daniel Dunbaraef87e32010-07-18 18:31:38 +000082 AsmParser(const AsmParser &); // DO NOT IMPLEMENT
83 void operator=(const AsmParser &); // DO NOT IMPLEMENT
84private:
85 AsmLexer Lexer;
86 MCContext &Ctx;
87 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +000088 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +000089 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +000090 SourceMgr::DiagHandlerTy SavedDiagHandler;
91 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +000092 MCAsmParserExtension *GenericParser;
93 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +000094
Daniel Dunbaraef87e32010-07-18 18:31:38 +000095 /// This is the current buffer index we're lexing from as managed by the
96 /// SourceMgr object.
97 int CurBuffer;
98
99 AsmCond TheCondState;
100 std::vector<AsmCond> TheCondStack;
101
102 /// DirectiveMap - This is a table handlers for directives. Each handler is
103 /// invoked after the directive identifier is read and is responsible for
104 /// parsing and validating the rest of the directive. The handler is passed
105 /// in the directive name and the location of the directive keyword.
106 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000107
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000108 /// MacroMap - Map of currently defined macros.
109 StringMap<Macro*> MacroMap;
110
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000111 /// ActiveMacros - Stack of active macro instantiations.
112 std::vector<MacroInstantiation*> ActiveMacros;
113
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000114 /// Boolean tracking whether macro substitution is enabled.
115 unsigned MacrosEnabled : 1;
116
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000117 /// Flag tracking whether any errors have been encountered.
118 unsigned HadError : 1;
119
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000120 /// The values from the last parsed cpp hash file line comment if any.
121 StringRef CppHashFilename;
122 int64_t CppHashLineNumber;
123 SMLoc CppHashLoc;
124
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000125public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000126 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000127 const MCAsmInfo &MAI);
128 ~AsmParser();
129
130 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
131
132 void AddDirectiveHandler(MCAsmParserExtension *Object,
133 StringRef Directive,
134 DirectiveHandler Handler) {
135 DirectiveMap[Directive] = std::make_pair(Object, Handler);
136 }
137
138public:
139 /// @name MCAsmParser Interface
140 /// {
141
142 virtual SourceMgr &getSourceManager() { return SrcMgr; }
143 virtual MCAsmLexer &getLexer() { return Lexer; }
144 virtual MCContext &getContext() { return Ctx; }
145 virtual MCStreamer &getStreamer() { return Out; }
146
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000147 virtual bool Warning(SMLoc L, const Twine &Msg,
148 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
149 virtual bool Error(SMLoc L, const Twine &Msg,
150 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000151
152 const AsmToken &Lex();
153
154 bool ParseExpression(const MCExpr *&Res);
155 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
156 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
157 virtual bool ParseAbsoluteExpression(int64_t &Res);
158
159 /// }
160
161private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000162 void CheckForValidSection();
163
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000164 bool ParseStatement();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000165 void EatToEndOfLine();
166 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000167
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000168 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
Rafael Espindola65366442011-06-05 02:43:45 +0000169 bool expandMacro(SmallString<256> &Buf, StringRef Body,
170 const std::vector<StringRef> &Parameters,
171 const std::vector<std::vector<AsmToken> > &A,
172 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000173 void HandleMacroExit();
174
175 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000176 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000177 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
178 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000179 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000180 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000181
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000182 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
183 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000184 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
185 /// This returns true on failure.
186 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000187
188 /// \brief Reset the current lexer position to that given by \arg Loc. The
189 /// current token is not set; clients should ensure Lex() is called
190 /// subsequently.
191 void JumpToLoc(SMLoc Loc);
192
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000193 void EatToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000194
195 /// \brief Parse up to the end of statement and a return the contents from the
196 /// current token until the end of the statement; the current token on exit
197 /// will be either the EndOfStatement or EOF.
198 StringRef ParseStringToEndOfStatement();
199
Nico Weber4c4c7322011-01-28 03:04:41 +0000200 bool ParseAssignment(StringRef Name, bool allow_redef);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000201
202 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
203 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
204 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000205 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000206
207 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
208 /// and set \arg Res to the identifier contents.
209 bool ParseIdentifier(StringRef &Res);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000210
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000211 // Directive Parsing.
Rafael Espindola787c3372010-10-28 20:02:27 +0000212
213 // ".ascii", ".asciiz", ".string"
214 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000215 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000216 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000217 bool ParseDirectiveFill(); // ".fill"
218 bool ParseDirectiveSpace(); // ".space"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000219 bool ParseDirectiveZero(); // ".zero"
Nico Weber4c4c7322011-01-28 03:04:41 +0000220 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef); // ".set", ".equ", ".equiv"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000221 bool ParseDirectiveOrg(); // ".org"
222 // ".align{,32}", ".p2align{,w,l}"
223 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
224
225 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
226 /// accepts a single symbol (which should be a label or an external).
227 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000228
229 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
230
231 bool ParseDirectiveAbort(); // ".abort"
232 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000233 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000234
235 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000236 // ".ifdef" or ".ifndef", depending on expect_defined
237 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000238 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
239 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
240 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
241
242 /// ParseEscapedString - Parse the current token as a string which may include
243 /// escaped characters and return the string contents.
244 bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000245
246 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
247 MCSymbolRefExpr::VariantKind Variant);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000248};
249
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000250/// \brief Generic implementations of directive handling, etc. which is shared
251/// (or the default, at least) for all assembler parser.
252class GenericAsmParser : public MCAsmParserExtension {
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000253 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
254 void AddDirectiveHandler(StringRef Directive) {
255 getParser().AddDirectiveHandler(this, Directive,
256 HandleDirective<GenericAsmParser, Handler>);
257 }
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000258public:
259 GenericAsmParser() {}
260
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000261 AsmParser &getParser() {
262 return (AsmParser&) this->MCAsmParserExtension::getParser();
263 }
264
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000265 virtual void Initialize(MCAsmParser &Parser) {
266 // Call the base implementation.
267 this->MCAsmParserExtension::Initialize(Parser);
268
269 // Debugging directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000270 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
271 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
272 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
Daniel Dunbar138abae2010-10-16 04:56:42 +0000273 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000274
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000275 // CFI directives.
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000276 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
277 ".cfi_sections");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000278 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
279 ".cfi_startproc");
280 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
281 ".cfi_endproc");
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000282 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
283 ".cfi_def_cfa");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000284 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
285 ".cfi_def_cfa_offset");
Rafael Espindola53abbe52011-04-11 20:29:16 +0000286 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
287 ".cfi_adjust_cfa_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000288 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
289 ".cfi_def_cfa_register");
290 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
291 ".cfi_offset");
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000292 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
293 ".cfi_rel_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000294 AddDirectiveHandler<
295 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
296 AddDirectiveHandler<
297 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
Rafael Espindolafe024d02010-12-28 18:36:23 +0000298 AddDirectiveHandler<
299 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
300 AddDirectiveHandler<
301 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
Rafael Espindolac5754392011-04-12 15:31:05 +0000302 AddDirectiveHandler<
303 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000304
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000305 // Macro directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000306 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
307 ".macros_on");
308 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
309 ".macros_off");
310 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
311 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
312 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000313
314 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
315 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000316 }
317
Roman Divacky54b0f4f2011-01-27 17:16:37 +0000318 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
319
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000320 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
321 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
322 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar138abae2010-10-16 04:56:42 +0000323 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000324 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000325 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
326 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000327 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000328 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola53abbe52011-04-11 20:29:16 +0000329 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000330 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
331 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000332 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000333 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
Rafael Espindolafe024d02010-12-28 18:36:23 +0000334 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
335 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac5754392011-04-12 15:31:05 +0000336 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000337
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000338 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000339 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
340 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000341
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000342 bool ParseDirectiveLEB128(StringRef, SMLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000343};
344
345}
346
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000347namespace llvm {
348
349extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000350extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000351extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000352
353}
354
Chris Lattneraaec2052010-01-19 19:46:13 +0000355enum { DEFAULT_ADDRSPACE = 0 };
356
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000357AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000358 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000359 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Rafael Espindola5d7dcd32011-04-12 18:53:30 +0000360 GenericParser(new GenericAsmParser), PlatformParser(0),
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000361 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000362 // Save the old handler.
363 SavedDiagHandler = SrcMgr.getDiagHandler();
364 SavedDiagContext = SrcMgr.getDiagContext();
365 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000366 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000367 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000368
369 // Initialize the generic parser.
370 GenericParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000371
372 // Initialize the platform / file format parser.
373 //
374 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
375 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000376 if (_MAI.hasMicrosoftFastStdCallMangling()) {
377 PlatformParser = createCOFFAsmParser();
378 PlatformParser->Initialize(*this);
379 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000380 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000381 PlatformParser->Initialize(*this);
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000382 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000383 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000384 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000385 }
Chris Lattnerebb89b42009-09-27 21:16:52 +0000386}
387
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000388AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000389 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
390
391 // Destroy any macros.
392 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
393 ie = MacroMap.end(); it != ie; ++it)
394 delete it->getValue();
395
Daniel Dunbare4749702010-07-12 18:12:02 +0000396 delete PlatformParser;
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000397 delete GenericParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000398}
399
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000400void AsmParser::PrintMacroInstantiations() {
401 // Print the active macro instantiation stack.
402 for (std::vector<MacroInstantiation*>::const_reverse_iterator
403 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000404 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
405 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000406}
407
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000408bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000409 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000410 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000411 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000412 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000413 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000414}
415
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000416bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000417 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000418 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000419 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000420 return true;
421}
422
Sean Callananfd0b0282010-01-21 00:19:58 +0000423bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000424 std::string IncludedFile;
425 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000426 if (NewBuf == -1)
427 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000428
Sean Callananfd0b0282010-01-21 00:19:58 +0000429 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000430
Sean Callananfd0b0282010-01-21 00:19:58 +0000431 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000432
Sean Callananfd0b0282010-01-21 00:19:58 +0000433 return false;
434}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000435
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000436/// Process the specified .incbin file by seaching for it in the include paths
437/// then just emiting the byte contents of the file to the streamer. This
438/// returns true on failure.
439bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
440 std::string IncludedFile;
441 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
442 if (NewBuf == -1)
443 return true;
444
445 // Loop picking the bytes from the file and emitting them.
446 const char *BufferStart = SrcMgr.getMemoryBuffer(NewBuf)->getBufferStart();
447 const char *BufferEnd = SrcMgr.getMemoryBuffer(NewBuf)->getBufferEnd();
448 for(const char *p = BufferStart; p < BufferEnd; p++)
449 getStreamer().EmitIntValue(*p, 1, DEFAULT_ADDRSPACE);
450
451 return false;
452}
453
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000454void AsmParser::JumpToLoc(SMLoc Loc) {
455 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
456 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
457}
458
Sean Callananfd0b0282010-01-21 00:19:58 +0000459const AsmToken &AsmParser::Lex() {
460 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000461
Sean Callananfd0b0282010-01-21 00:19:58 +0000462 if (tok->is(AsmToken::Eof)) {
463 // If this is the end of an included file, pop the parent file off the
464 // include stack.
465 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
466 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000467 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000468 tok = &Lexer.Lex();
469 }
470 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000471
Sean Callananfd0b0282010-01-21 00:19:58 +0000472 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000473 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000474
Sean Callananfd0b0282010-01-21 00:19:58 +0000475 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000476}
477
Chris Lattner79180e22010-04-05 23:15:42 +0000478bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000479 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000480 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000481 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000482
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000483 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000484 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000485
486 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000487 AsmCond StartingCondState = TheCondState;
488
Kevin Enderby613b7572011-11-01 22:27:22 +0000489 // If we are generating dwarf for assembly source files save the initial text
490 // section and generate a .file directive.
491 if (getContext().getGenDwarfForAssembly()) {
492 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000493 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
494 getStreamer().EmitLabel(SectionStartSym);
495 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000496 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
497 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
498 }
499
Chris Lattnerb717fb02009-07-02 21:53:43 +0000500 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000501 while (Lexer.isNot(AsmToken::Eof)) {
Chris Lattnerb717fb02009-07-02 21:53:43 +0000502 if (!ParseStatement()) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000503
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000504 // We had an error, validate that one was emitted and recover by skipping to
505 // the next line.
506 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000507 EatToEndOfStatement();
508 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000509
510 if (TheCondState.TheCond != StartingCondState.TheCond ||
511 TheCondState.Ignore != StartingCondState.Ignore)
512 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000513
514 // Check to see there are no empty DwarfFile slots.
515 const std::vector<MCDwarfFile *> &MCDwarfFiles =
516 getContext().getMCDwarfFiles();
517 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000518 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000519 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000520 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000521
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000522 // Check to see that all assembler local symbols were actually defined.
523 // Targets that don't do subsections via symbols may not want this, though,
524 // so conservatively exclude them. Only do this if we're finalizing, though,
525 // as otherwise we won't necessarilly have seen everything yet.
526 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
527 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
528 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
529 e = Symbols.end();
530 i != e; ++i) {
531 MCSymbol *Sym = i->getValue();
532 // Variable symbols may not be marked as defined, so check those
533 // explicitly. If we know it's a variable, we have a definition for
534 // the purposes of this check.
535 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
536 // FIXME: We would really like to refer back to where the symbol was
537 // first referenced for a source location. We need to add something
538 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000539 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
540 "assembler local symbol '" + Sym->getName() +
541 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000542 }
543 }
544
545
Chris Lattner79180e22010-04-05 23:15:42 +0000546 // Finalize the output stream if there are no errors and if the client wants
547 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000548 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000549 Out.Finish();
550
Chris Lattnerb717fb02009-07-02 21:53:43 +0000551 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000552}
553
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000554void AsmParser::CheckForValidSection() {
555 if (!getStreamer().getCurrentSection()) {
556 TokError("expected section directive before assembly directive");
557 Out.SwitchSection(Ctx.getMachOSection(
558 "__TEXT", "__text",
559 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
560 0, SectionKind::getText()));
561 }
562}
563
Chris Lattner2cf5f142009-06-22 01:29:09 +0000564/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
565void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000566 while (Lexer.isNot(AsmToken::EndOfStatement) &&
567 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000568 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000569
Chris Lattner2cf5f142009-06-22 01:29:09 +0000570 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000571 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000572 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000573}
574
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000575StringRef AsmParser::ParseStringToEndOfStatement() {
576 const char *Start = getTok().getLoc().getPointer();
577
578 while (Lexer.isNot(AsmToken::EndOfStatement) &&
579 Lexer.isNot(AsmToken::Eof))
580 Lex();
581
582 const char *End = getTok().getLoc().getPointer();
583 return StringRef(Start, End - Start);
584}
Chris Lattnerc4193832009-06-22 05:51:26 +0000585
Chris Lattner74ec1a32009-06-22 06:32:03 +0000586/// ParseParenExpr - Parse a paren expression and return it.
587/// NOTE: This assumes the leading '(' has already been consumed.
588///
589/// parenexpr ::= expr)
590///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000591bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000592 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000593 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000594 return TokError("expected ')' in parentheses expression");
Chris Lattnerb4307b32010-01-15 19:28:38 +0000595 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000596 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000597 return false;
598}
Chris Lattnerc4193832009-06-22 05:51:26 +0000599
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000600/// ParseBracketExpr - Parse a bracket expression and return it.
601/// NOTE: This assumes the leading '[' has already been consumed.
602///
603/// bracketexpr ::= expr]
604///
605bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
606 if (ParseExpression(Res)) return true;
607 if (Lexer.isNot(AsmToken::RBrac))
608 return TokError("expected ']' in brackets expression");
609 EndLoc = Lexer.getLoc();
610 Lex();
611 return false;
612}
613
Chris Lattner74ec1a32009-06-22 06:32:03 +0000614/// ParsePrimaryExpr - Parse a primary expression and return it.
615/// primaryexpr ::= (parenexpr
616/// primaryexpr ::= symbol
617/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000618/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000619/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000620bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000621 switch (Lexer.getKind()) {
622 default:
623 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000624 // If we have an error assume that we've already handled it.
625 case AsmToken::Error:
626 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000627 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000628 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000629 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000630 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000631 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000632 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000633 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000634 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000635 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000636 EndLoc = Lexer.getLoc();
637
638 StringRef Identifier;
639 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000640 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000641
Daniel Dunbarfffff912009-10-16 01:34:54 +0000642 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000643 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000644 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000645
646 // Lookup the symbol variant if used.
647 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000648 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000649 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000650 if (Variant == MCSymbolRefExpr::VK_Invalid) {
651 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000652 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000653 }
654 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000655
Daniel Dunbarfffff912009-10-16 01:34:54 +0000656 // If this is an absolute variable reference, substitute it now to preserve
657 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000658 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000659 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000660 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000661
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000662 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000663 return false;
664 }
665
666 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000667 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000668 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000669 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000670 case AsmToken::Integer: {
671 SMLoc Loc = getTok().getLoc();
672 int64_t IntVal = getTok().getIntVal();
673 Res = MCConstantExpr::Create(IntVal, getContext());
Chris Lattnerb4307b32010-01-15 19:28:38 +0000674 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000675 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000676 // Look for 'b' or 'f' following an Integer as a directional label
677 if (Lexer.getKind() == AsmToken::Identifier) {
678 StringRef IDVal = getTok().getString();
679 if (IDVal == "f" || IDVal == "b"){
680 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
681 IDVal == "f" ? 1 : 0);
682 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
683 getContext());
684 if(IDVal == "b" && Sym->isUndefined())
685 return Error(Loc, "invalid reference to undefined symbol");
686 EndLoc = Lexer.getLoc();
687 Lex(); // Eat identifier.
688 }
689 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000690 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000691 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000692 case AsmToken::Real: {
693 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000694 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000695 Res = MCConstantExpr::Create(IntVal, getContext());
696 Lex(); // Eat token.
697 return false;
698 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000699 case AsmToken::Dot: {
700 // This is a '.' reference, which references the current PC. Emit a
701 // temporary label to the streamer and refer to it.
702 MCSymbol *Sym = Ctx.CreateTempSymbol();
703 Out.EmitLabel(Sym);
704 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
705 EndLoc = Lexer.getLoc();
706 Lex(); // Eat identifier.
707 return false;
708 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000709 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000710 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000711 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000712 case AsmToken::LBrac:
713 if (!PlatformParser->HasBracketExpressions())
714 return TokError("brackets expression not supported on this target");
715 Lex(); // Eat the '['.
716 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000717 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000718 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000719 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000720 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000721 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000722 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000723 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000724 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000725 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000726 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000727 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000728 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000729 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000730 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000731 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000732 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000733 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000734 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000735 }
736}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000737
Chris Lattnerb4307b32010-01-15 19:28:38 +0000738bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000739 SMLoc EndLoc;
740 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000741}
742
Daniel Dunbarcceba832010-09-17 02:47:07 +0000743const MCExpr *
744AsmParser::ApplyModifierToExpr(const MCExpr *E,
745 MCSymbolRefExpr::VariantKind Variant) {
746 // Recurse over the given expression, rebuilding it to apply the given variant
747 // if there is exactly one symbol.
748 switch (E->getKind()) {
749 case MCExpr::Target:
750 case MCExpr::Constant:
751 return 0;
752
753 case MCExpr::SymbolRef: {
754 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
755
756 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
757 TokError("invalid variant on expression '" +
758 getTok().getIdentifier() + "' (already modified)");
759 return E;
760 }
761
762 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
763 }
764
765 case MCExpr::Unary: {
766 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
767 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
768 if (!Sub)
769 return 0;
770 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
771 }
772
773 case MCExpr::Binary: {
774 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
775 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
776 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
777
778 if (!LHS && !RHS)
779 return 0;
780
781 if (!LHS) LHS = BE->getLHS();
782 if (!RHS) RHS = BE->getRHS();
783
784 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
785 }
786 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000787
788 assert(0 && "Invalid expression kind!");
789 return 0;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000790}
791
Chris Lattner74ec1a32009-06-22 06:32:03 +0000792/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000793///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000794/// expr ::= expr &&,|| expr -> lowest.
795/// expr ::= expr |,^,&,! expr
796/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
797/// expr ::= expr <<,>> expr
798/// expr ::= expr +,- expr
799/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000800/// expr ::= primaryexpr
801///
Chris Lattner54482b42010-01-15 19:39:23 +0000802bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000803 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000804 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000805 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
806 return true;
807
Daniel Dunbarcceba832010-09-17 02:47:07 +0000808 // As a special case, we support 'a op b @ modifier' by rewriting the
809 // expression to include the modifier. This is inefficient, but in general we
810 // expect users to use 'a@modifier op b'.
811 if (Lexer.getKind() == AsmToken::At) {
812 Lex();
813
814 if (Lexer.isNot(AsmToken::Identifier))
815 return TokError("unexpected symbol modifier following '@'");
816
817 MCSymbolRefExpr::VariantKind Variant =
818 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
819 if (Variant == MCSymbolRefExpr::VK_Invalid)
820 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
821
822 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
823 if (!ModifiedRes) {
824 return TokError("invalid modifier '" + getTok().getIdentifier() +
825 "' (no symbols present)");
826 return true;
827 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000828
Daniel Dunbarcceba832010-09-17 02:47:07 +0000829 Res = ModifiedRes;
830 Lex();
831 }
832
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000833 // Try to constant fold it up front, if possible.
834 int64_t Value;
835 if (Res->EvaluateAsAbsolute(Value))
836 Res = MCConstantExpr::Create(Value, getContext());
837
838 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000839}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000840
Chris Lattnerb4307b32010-01-15 19:28:38 +0000841bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000842 Res = 0;
843 return ParseParenExpr(Res, EndLoc) ||
844 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000845}
846
Daniel Dunbar475839e2009-06-29 20:37:27 +0000847bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000848 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000849
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000850 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000851 if (ParseExpression(Expr))
852 return true;
853
Daniel Dunbare00b0112009-10-16 01:57:52 +0000854 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000855 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000856
857 return false;
858}
859
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000860static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000861 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000862 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000863 default:
864 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000865
Jim Grosbachfbe16812011-08-20 16:24:13 +0000866 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000867 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000868 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000869 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000870 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000871 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000872 return 1;
873
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000874
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000875 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +0000876 //
877 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +0000878 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000879 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000880 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000881 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000882 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000883 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000884 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000885 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000886 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000887
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000888 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000889 case AsmToken::EqualEqual:
890 Kind = MCBinaryExpr::EQ;
891 return 3;
892 case AsmToken::ExclaimEqual:
893 case AsmToken::LessGreater:
894 Kind = MCBinaryExpr::NE;
895 return 3;
896 case AsmToken::Less:
897 Kind = MCBinaryExpr::LT;
898 return 3;
899 case AsmToken::LessEqual:
900 Kind = MCBinaryExpr::LTE;
901 return 3;
902 case AsmToken::Greater:
903 Kind = MCBinaryExpr::GT;
904 return 3;
905 case AsmToken::GreaterEqual:
906 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000907 return 3;
908
Jim Grosbachfbe16812011-08-20 16:24:13 +0000909 // Intermediate Precedence: <<, >>
910 case AsmToken::LessLess:
911 Kind = MCBinaryExpr::Shl;
912 return 4;
913 case AsmToken::GreaterGreater:
914 Kind = MCBinaryExpr::Shr;
915 return 4;
916
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000917 // High Intermediate Precedence: +, -
918 case AsmToken::Plus:
919 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000920 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000921 case AsmToken::Minus:
922 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000923 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000924
Jim Grosbachfbe16812011-08-20 16:24:13 +0000925 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +0000926 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000927 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000928 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000929 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000930 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000931 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000932 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000933 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +0000934 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000935 }
936}
937
938
939/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
940/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000941bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
942 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000943 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000944 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000945 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000946
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000947 // If the next token is lower precedence than we are allowed to eat, return
948 // successfully with what we ate already.
949 if (TokPrec < Precedence)
950 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000951
Sean Callanan79ed1a82010-01-19 20:22:31 +0000952 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000953
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000954 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000955 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +0000956 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000957
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000958 // If BinOp binds less tightly with RHS than the operator after RHS, let
959 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000960 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000961 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000962 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +0000963 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000964 }
965
Daniel Dunbar475839e2009-06-29 20:37:27 +0000966 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000967 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000968 }
969}
970
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000971
972
973
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000974/// ParseStatement:
975/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +0000976/// ::= Label* Directive ...Operands... EndOfStatement
977/// ::= Label* Identifier OperandList* EndOfStatement
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000978bool AsmParser::ParseStatement() {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +0000979 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +0000980 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000981 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000982 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000983 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +0000984
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +0000985 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +0000986 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +0000987 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +0000988 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000989 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +0000990 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000991 if (Lexer.is(AsmToken::Hash))
992 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +0000993
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +0000994 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000995 if (Lexer.is(AsmToken::Integer)) {
996 LocalLabelVal = getTok().getIntVal();
997 if (LocalLabelVal < 0) {
998 if (!TheCondState.Ignore)
999 return TokError("unexpected token at start of statement");
1000 IDVal = "";
1001 }
1002 else {
1003 IDVal = getTok().getString();
1004 Lex(); // Consume the integer token to be used as an identifier token.
1005 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001006 if (!TheCondState.Ignore)
1007 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001008 }
1009 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001010
1011 } else if (Lexer.is(AsmToken::Dot)) {
1012 // Treat '.' as a valid identifier in this context.
1013 Lex();
1014 IDVal = ".";
1015
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001016 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001017 if (!TheCondState.Ignore)
1018 return TokError("unexpected token at start of statement");
1019 IDVal = "";
1020 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001021
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001022
Chris Lattner7834fac2010-04-17 18:14:27 +00001023 // Handle conditional assembly here before checking for skipping. We
1024 // have to do this so that .endif isn't skipped in a ".if 0" block for
1025 // example.
1026 if (IDVal == ".if")
1027 return ParseDirectiveIf(IDLoc);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00001028 if (IDVal == ".ifdef")
1029 return ParseDirectiveIfdef(IDLoc, true);
1030 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1031 return ParseDirectiveIfdef(IDLoc, false);
Chris Lattner7834fac2010-04-17 18:14:27 +00001032 if (IDVal == ".elseif")
1033 return ParseDirectiveElseIf(IDLoc);
1034 if (IDVal == ".else")
1035 return ParseDirectiveElse(IDLoc);
1036 if (IDVal == ".endif")
1037 return ParseDirectiveEndIf(IDLoc);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001038
Chris Lattner7834fac2010-04-17 18:14:27 +00001039 // If we are in a ".if 0" block, ignore this statement.
1040 if (TheCondState.Ignore) {
1041 EatToEndOfStatement();
1042 return false;
1043 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001044
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001045 // FIXME: Recurse on local labels?
1046
1047 // See what kind of statement we have.
1048 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001049 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001050 CheckForValidSection();
1051
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001052 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001053 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001054
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001055 // Diagnose attempt to use '.' as a label.
1056 if (IDVal == ".")
1057 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1058
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001059 // Diagnose attempt to use a variable as a label.
1060 //
1061 // FIXME: Diagnostics. Note the location of the definition as a label.
1062 // FIXME: This doesn't diagnose assignment to a symbol which has been
1063 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001064 MCSymbol *Sym;
1065 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001066 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001067 else
1068 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001069 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001070 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001071
Daniel Dunbar959fd882009-08-26 22:13:22 +00001072 // Emit the label.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001073 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001074
Kevin Enderby94c2e852011-12-09 18:09:40 +00001075 // If we are generating dwarf for assembly source files then gather the
1076 // info to make a dwarf subprogram entry for this label if needed.
1077 if (getContext().getGenDwarfForAssembly())
1078 MCGenDwarfSubprogramEntry::Make(Sym, &getStreamer(), getSourceManager(),
1079 IDLoc);
1080
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001081 // Consume any end of statement token, if present, to avoid spurious
1082 // AddBlankLine calls().
1083 if (Lexer.is(AsmToken::EndOfStatement)) {
1084 Lex();
1085 if (Lexer.is(AsmToken::Eof))
1086 return false;
1087 }
1088
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001089 return ParseStatement();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001090 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001091
Daniel Dunbar3f872332009-07-28 16:08:33 +00001092 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001093 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001094 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001095
Nico Weber4c4c7322011-01-28 03:04:41 +00001096 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001097
1098 default: // Normal instruction or directive.
1099 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001100 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001101
1102 // If macros are enabled, check to see if this is a macro instantiation.
1103 if (MacrosEnabled)
1104 if (const Macro *M = MacroMap.lookup(IDVal))
1105 return HandleMacroEntry(IDVal, IDLoc, M);
1106
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001107 // Otherwise, we have a normal instruction or directive.
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001108 if (IDVal[0] == '.' && IDVal != ".") {
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001109 // Assembler features
Roman Divacky50e7a782010-10-28 16:22:58 +00001110 if (IDVal == ".set" || IDVal == ".equ")
Nico Weber4c4c7322011-01-28 03:04:41 +00001111 return ParseDirectiveSet(IDVal, true);
1112 if (IDVal == ".equiv")
1113 return ParseDirectiveSet(IDVal, false);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001114
Daniel Dunbara0d14262009-06-24 23:30:00 +00001115 // Data directives
1116
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001117 if (IDVal == ".ascii")
Rafael Espindola787c3372010-10-28 20:02:27 +00001118 return ParseDirectiveAscii(IDVal, false);
1119 if (IDVal == ".asciz" || IDVal == ".string")
1120 return ParseDirectiveAscii(IDVal, true);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001121
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001122 if (IDVal == ".byte")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001123 return ParseDirectiveValue(1);
Kevin Enderby9c656452009-09-10 20:51:44 +00001124 if (IDVal == ".short")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001125 return ParseDirectiveValue(2);
Rafael Espindolacc3acee2010-11-01 15:29:07 +00001126 if (IDVal == ".value")
1127 return ParseDirectiveValue(2);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001128 if (IDVal == ".2byte")
1129 return ParseDirectiveValue(2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001130 if (IDVal == ".long")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001131 return ParseDirectiveValue(4);
Rafael Espindola435279b2010-11-17 16:24:40 +00001132 if (IDVal == ".int")
1133 return ParseDirectiveValue(4);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001134 if (IDVal == ".4byte")
1135 return ParseDirectiveValue(4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001136 if (IDVal == ".quad")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001137 return ParseDirectiveValue(8);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001138 if (IDVal == ".8byte")
1139 return ParseDirectiveValue(8);
Roman Divacky14e66552011-01-28 14:20:32 +00001140 if (IDVal == ".single" || IDVal == ".float")
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001141 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1142 if (IDVal == ".double")
1143 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001144
Eli Friedman5d68ec22010-07-19 04:17:25 +00001145 if (IDVal == ".align") {
1146 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1147 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1148 }
1149 if (IDVal == ".align32") {
1150 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1151 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1152 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001153 if (IDVal == ".balign")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001154 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001155 if (IDVal == ".balignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001156 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001157 if (IDVal == ".balignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001158 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001159 if (IDVal == ".p2align")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001160 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001161 if (IDVal == ".p2alignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001162 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001163 if (IDVal == ".p2alignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001164 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1165
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001166 if (IDVal == ".org")
Daniel Dunbarc238b582009-06-25 22:44:51 +00001167 return ParseDirectiveOrg();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001168
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001169 if (IDVal == ".fill")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001170 return ParseDirectiveFill();
Rafael Espindolace8463f2011-04-07 20:26:23 +00001171 if (IDVal == ".space" || IDVal == ".skip")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001172 return ParseDirectiveSpace();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001173 if (IDVal == ".zero")
1174 return ParseDirectiveZero();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001175
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001176 // Symbol attribute directives
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001177
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001178 if (IDVal == ".globl" || IDVal == ".global")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001179 return ParseDirectiveSymbolAttribute(MCSA_Global);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001180 if (IDVal == ".indirect_symbol")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001181 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001182 if (IDVal == ".lazy_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001183 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001184 if (IDVal == ".no_dead_strip")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001185 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Kevin Enderbye8e98d72010-11-19 18:39:33 +00001186 if (IDVal == ".symbol_resolver")
1187 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001188 if (IDVal == ".private_extern")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001189 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001190 if (IDVal == ".reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001191 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001192 if (IDVal == ".weak_definition")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001193 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001194 if (IDVal == ".weak_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001195 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Kevin Enderbyf59cac52010-07-08 17:22:42 +00001196 if (IDVal == ".weak_def_can_be_hidden")
1197 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001198
Hans Wennborg5cc64912011-06-18 13:51:54 +00001199 if (IDVal == ".comm" || IDVal == ".common")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001200 return ParseDirectiveComm(/*IsLocal=*/false);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001201 if (IDVal == ".lcomm")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001202 return ParseDirectiveComm(/*IsLocal=*/true);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001203
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001204 if (IDVal == ".abort")
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001205 return ParseDirectiveAbort();
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001206 if (IDVal == ".include")
Kevin Enderby1f049b22009-07-14 23:21:55 +00001207 return ParseDirectiveInclude();
Kevin Enderbyc55acca2011-12-14 21:47:48 +00001208 if (IDVal == ".incbin")
1209 return ParseDirectiveIncbin();
Kevin Enderbya5c78322009-07-13 21:03:15 +00001210
Evan Chengbd27f5a2011-07-27 00:38:12 +00001211 if (IDVal == ".code16")
Roman Divackyf6fbd842011-01-31 20:56:49 +00001212 return TokError(Twine(IDVal) + " not supported yet");
Roman Divackycb727802011-01-28 19:29:48 +00001213
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001214 // Look up the handler in the handler table.
1215 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1216 DirectiveMap.lookup(IDVal);
1217 if (Handler.first)
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +00001218 return (*Handler.second)(Handler.first, IDVal, IDLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001219
Kevin Enderby9c656452009-09-10 20:51:44 +00001220 // Target hook for parsing target specific directives.
1221 if (!getTargetParser().ParseDirective(ID))
1222 return false;
1223
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +00001224 bool retval = Warning(IDLoc, "ignoring directive for now");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001225 EatToEndOfStatement();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +00001226 return retval;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001227 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001228
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001229 CheckForValidSection();
1230
Chris Lattnera7f13542010-05-19 23:34:33 +00001231 // Canonicalize the opcode to lower case.
1232 SmallString<128> Opcode;
1233 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
1234 Opcode.push_back(tolower(IDVal[i]));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001235
Chris Lattner98986712010-01-14 22:21:20 +00001236 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
Chris Lattnera7f13542010-05-19 23:34:33 +00001237 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001238 ParsedOperands);
Chris Lattner2cf5f142009-06-22 01:29:09 +00001239
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001240 // Dump the parsed representation, if requested.
1241 if (getShowParsedOperands()) {
1242 SmallString<256> Str;
1243 raw_svector_ostream OS(Str);
1244 OS << "parsed instruction: [";
1245 for (unsigned i = 0; i != ParsedOperands.size(); ++i) {
1246 if (i != 0)
1247 OS << ", ";
Jim Grosbachb7f689b2011-07-13 15:34:57 +00001248 ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001249 }
1250 OS << "]";
1251
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001252 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001253 }
1254
Kevin Enderby613b7572011-11-01 22:27:22 +00001255 // If we are generating dwarf for assembly source files and the current
1256 // section is the initial text section then generate a .loc directive for
1257 // the instruction.
1258 if (!HadError && getContext().getGenDwarfForAssembly() &&
1259 getContext().getGenDwarfSection() == getStreamer().getCurrentSection() ) {
1260 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
1261 SrcMgr.FindLineNumber(IDLoc, CurBuffer),
1262 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001263 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001264 StringRef());
1265 }
1266
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001267 // If parsing succeeded, match the instruction.
Chris Lattner7036f8b2010-09-29 01:42:58 +00001268 if (!HadError)
1269 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, ParsedOperands,
1270 Out);
Chris Lattner98986712010-01-14 22:21:20 +00001271
Chris Lattner98986712010-01-14 22:21:20 +00001272 // Free any parsed operands.
1273 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
1274 delete ParsedOperands[i];
1275
Chris Lattnercbf8a982010-09-11 16:18:25 +00001276 // Don't skip the rest of the line, the instruction parser is responsible for
1277 // that.
1278 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001279}
Chris Lattner9a023f72009-06-24 04:43:34 +00001280
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001281/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1282/// since they may not be able to be tokenized to get to the end of line token.
1283void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001284 if (!Lexer.is(AsmToken::EndOfStatement))
1285 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001286 // Eat EOL.
1287 Lex();
1288}
1289
1290/// ParseCppHashLineFilenameComment as this:
1291/// ::= # number "filename"
1292/// or just as a full line comment if it doesn't have a number and a string.
1293bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1294 Lex(); // Eat the hash token.
1295
1296 if (getLexer().isNot(AsmToken::Integer)) {
1297 // Consume the line since in cases it is not a well-formed line directive,
1298 // as if were simply a full line comment.
1299 EatToEndOfLine();
1300 return false;
1301 }
1302
1303 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001304 Lex();
1305
1306 if (getLexer().isNot(AsmToken::String)) {
1307 EatToEndOfLine();
1308 return false;
1309 }
1310
1311 StringRef Filename = getTok().getString();
1312 // Get rid of the enclosing quotes.
1313 Filename = Filename.substr(1, Filename.size()-2);
1314
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001315 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1316 CppHashLoc = L;
1317 CppHashFilename = Filename;
1318 CppHashLineNumber = LineNumber;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001319
1320 // Ignore any trailing characters, they're just comment.
1321 EatToEndOfLine();
1322 return false;
1323}
1324
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001325/// DiagHandler - will use the the last parsed cpp hash line filename comment
1326/// for the Filename and LineNo if any in the diagnostic.
1327void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1328 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1329 raw_ostream &OS = errs();
1330
1331 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1332 const SMLoc &DiagLoc = Diag.getLoc();
1333 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1334 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1335
1336 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1337 // before printing the message.
1338 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001339 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001340 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1341 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1342 }
1343
1344 // If we have not parsed a cpp hash line filename comment or the source
1345 // manager changed or buffer changed (like in a nested include) then just
1346 // print the normal diagnostic using its Filename and LineNo.
1347 if (!Parser->CppHashLineNumber ||
1348 &DiagSrcMgr != &Parser->SrcMgr ||
1349 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001350 if (Parser->SavedDiagHandler)
1351 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1352 else
1353 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001354 return;
1355 }
1356
1357 // Use the CppHashFilename and calculate a line number based on the
1358 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1359 // the diagnostic.
1360 const std::string Filename = Parser->CppHashFilename;
1361
1362 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1363 int CppHashLocLineNo =
1364 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1365 int LineNo = Parser->CppHashLineNumber - 1 +
1366 (DiagLocLineNo - CppHashLocLineNo);
1367
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001368 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1369 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001370 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001371 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001372
Benjamin Kramer04a04262011-10-16 10:48:29 +00001373 if (Parser->SavedDiagHandler)
1374 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1375 else
1376 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001377}
1378
Rafael Espindola65366442011-06-05 02:43:45 +00001379bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
1380 const std::vector<StringRef> &Parameters,
1381 const std::vector<std::vector<AsmToken> > &A,
1382 const SMLoc &L) {
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001383 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001384 unsigned NParameters = Parameters.size();
1385 if (NParameters != 0 && NParameters != A.size())
1386 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001387
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001388 while (!Body.empty()) {
1389 // Scan for the next substitution.
1390 std::size_t End = Body.size(), Pos = 0;
1391 for (; Pos != End; ++Pos) {
1392 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001393 if (!NParameters) {
1394 // This macro has no parameters, look for $0, $1, etc.
1395 if (Body[Pos] != '$' || Pos + 1 == End)
1396 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001397
Rafael Espindola65366442011-06-05 02:43:45 +00001398 char Next = Body[Pos + 1];
1399 if (Next == '$' || Next == 'n' || isdigit(Next))
1400 break;
1401 } else {
1402 // This macro has parameters, look for \foo, \bar, etc.
1403 if (Body[Pos] == '\\' && Pos + 1 != End)
1404 break;
1405 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001406 }
1407
1408 // Add the prefix.
1409 OS << Body.slice(0, Pos);
1410
1411 // Check if we reached the end.
1412 if (Pos == End)
1413 break;
1414
Rafael Espindola65366442011-06-05 02:43:45 +00001415 if (!NParameters) {
1416 switch (Body[Pos+1]) {
1417 // $$ => $
1418 case '$':
1419 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001420 break;
1421
Rafael Espindola65366442011-06-05 02:43:45 +00001422 // $n => number of arguments
1423 case 'n':
1424 OS << A.size();
1425 break;
1426
1427 // $[0-9] => argument
1428 default: {
1429 // Missing arguments are ignored.
1430 unsigned Index = Body[Pos+1] - '0';
1431 if (Index >= A.size())
1432 break;
1433
1434 // Otherwise substitute with the token values, with spaces eliminated.
1435 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1436 ie = A[Index].end(); it != ie; ++it)
1437 OS << it->getString();
1438 break;
1439 }
1440 }
1441 Pos += 2;
1442 } else {
1443 unsigned I = Pos + 1;
1444 while (isalnum(Body[I]) && I + 1 != End)
1445 ++I;
1446
1447 const char *Begin = Body.data() + Pos +1;
1448 StringRef Argument(Begin, I - (Pos +1));
1449 unsigned Index = 0;
1450 for (; Index < NParameters; ++Index)
1451 if (Parameters[Index] == Argument)
1452 break;
1453
1454 // FIXME: We should error at the macro definition.
1455 if (Index == NParameters)
1456 return Error(L, "Parameter not found");
1457
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001458 for (std::vector<AsmToken>::const_iterator it = A[Index].begin(),
1459 ie = A[Index].end(); it != ie; ++it)
1460 OS << it->getString();
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001461
Rafael Espindola65366442011-06-05 02:43:45 +00001462 Pos += 1 + Argument.size();
1463 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001464 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001465 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001466 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001467
1468 // We include the .endmacro in the buffer as our queue to exit the macro
1469 // instantiation.
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001470 OS << ".endmacro\n";
Rafael Espindola65366442011-06-05 02:43:45 +00001471 return false;
1472}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001473
Rafael Espindola65366442011-06-05 02:43:45 +00001474MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL, SMLoc EL,
1475 MemoryBuffer *I)
1476 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitLoc(EL)
1477{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001478}
1479
1480bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1481 const Macro *M) {
1482 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1483 // this, although we should protect against infinite loops.
1484 if (ActiveMacros.size() == 20)
1485 return TokError("macros cannot be nested more than 20 levels deep");
1486
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001487 // Parse the macro instantiation arguments.
1488 std::vector<std::vector<AsmToken> > MacroArguments;
1489 MacroArguments.push_back(std::vector<AsmToken>());
1490 unsigned ParenLevel = 0;
1491 for (;;) {
1492 if (Lexer.is(AsmToken::Eof))
1493 return TokError("unexpected token in macro instantiation");
1494 if (Lexer.is(AsmToken::EndOfStatement))
1495 break;
1496
1497 // If we aren't inside parentheses and this is a comma, start a new token
1498 // list.
1499 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1500 MacroArguments.push_back(std::vector<AsmToken>());
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001501 } else {
Daniel Dunbare25c6b92010-08-10 17:38:52 +00001502 // Adjust the current parentheses level.
1503 if (Lexer.is(AsmToken::LParen))
1504 ++ParenLevel;
1505 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1506 --ParenLevel;
1507
1508 // Append the token to the current argument list.
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001509 MacroArguments.back().push_back(getTok());
1510 }
1511 Lex();
1512 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001513
Rafael Espindola65366442011-06-05 02:43:45 +00001514 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1515 // to hold the macro body with substitutions.
1516 SmallString<256> Buf;
1517 StringRef Body = M->Body;
1518
1519 if (expandMacro(Buf, Body, M->Parameters, MacroArguments, getTok().getLoc()))
1520 return true;
1521
1522 MemoryBuffer *Instantiation =
1523 MemoryBuffer::getMemBufferCopy(Buf.str(), "<instantiation>");
1524
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001525 // Create the macro instantiation object and add to the current macro
1526 // instantiation stack.
1527 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001528 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001529 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001530 ActiveMacros.push_back(MI);
1531
1532 // Jump to the macro instantiation and prime the lexer.
1533 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1534 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1535 Lex();
1536
1537 return false;
1538}
1539
1540void AsmParser::HandleMacroExit() {
1541 // Jump to the EndOfStatement we should return to, and consume it.
1542 JumpToLoc(ActiveMacros.back()->ExitLoc);
1543 Lex();
1544
1545 // Pop the instantiation entry.
1546 delete ActiveMacros.back();
1547 ActiveMacros.pop_back();
1548}
1549
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001550static void MarkUsed(const MCExpr *Value) {
1551 switch (Value->getKind()) {
1552 case MCExpr::Binary:
1553 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
1554 MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
1555 break;
1556 case MCExpr::Target:
1557 case MCExpr::Constant:
1558 break;
1559 case MCExpr::SymbolRef: {
1560 static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
1561 break;
1562 }
1563 case MCExpr::Unary:
1564 MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
1565 break;
1566 }
1567}
1568
Nico Weber4c4c7322011-01-28 03:04:41 +00001569bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001570 // FIXME: Use better location, we should use proper tokens.
1571 SMLoc EqualLoc = Lexer.getLoc();
1572
Daniel Dunbar821e3332009-08-31 08:09:28 +00001573 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001574 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001575 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001576
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001577 MarkUsed(Value);
1578
Daniel Dunbar3f872332009-07-28 16:08:33 +00001579 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001580 return TokError("unexpected token in assignment");
1581
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001582 // Error on assignment to '.'.
1583 if (Name == ".") {
1584 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1585 "(use '.space' or '.org').)"));
1586 }
1587
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001588 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001589 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001590
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001591 // Validate that the LHS is allowed to be a variable (either it has not been
1592 // used as a symbol, or it is an absolute symbol).
1593 MCSymbol *Sym = getContext().LookupSymbol(Name);
1594 if (Sym) {
1595 // Diagnose assignment to a label.
1596 //
1597 // FIXME: Diagnostics. Note the location of the definition as a label.
1598 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001599 if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001600 ; // Allow redefinitions of undefined symbols only used in directives.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00001601 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001602 return Error(EqualLoc, "redefinition of '" + Name + "'");
1603 else if (!Sym->isVariable())
1604 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00001605 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001606 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1607 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001608
1609 // Don't count these checks as uses.
1610 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001611 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001612 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001613
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001614 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001615
1616 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00001617 Out.EmitAssignment(Sym, Value);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001618
1619 return false;
1620}
1621
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001622/// ParseIdentifier:
1623/// ::= identifier
1624/// ::= string
1625bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00001626 // The assembler has relaxed rules for accepting identifiers, in particular we
1627 // allow things like '.globl $foo', which would normally be separate
1628 // tokens. At this level, we have already lexed so we cannot (currently)
1629 // handle this as a context dependent token, instead we detect adjacent tokens
1630 // and return the combined identifier.
1631 if (Lexer.is(AsmToken::Dollar)) {
1632 SMLoc DollarLoc = getLexer().getLoc();
1633
1634 // Consume the dollar sign, and check for a following identifier.
1635 Lex();
1636 if (Lexer.isNot(AsmToken::Identifier))
1637 return true;
1638
1639 // We have a '$' followed by an identifier, make sure they are adjacent.
1640 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1641 return true;
1642
1643 // Construct the joined identifier and consume the token.
1644 Res = StringRef(DollarLoc.getPointer(),
1645 getTok().getIdentifier().size() + 1);
1646 Lex();
1647 return false;
1648 }
1649
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001650 if (Lexer.isNot(AsmToken::Identifier) &&
1651 Lexer.isNot(AsmToken::String))
1652 return true;
1653
Sean Callanan18b83232010-01-19 21:44:56 +00001654 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001655
Sean Callanan79ed1a82010-01-19 20:22:31 +00001656 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001657
1658 return false;
1659}
1660
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001661/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00001662/// ::= .equ identifier ',' expression
1663/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001664/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00001665bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001666 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001667
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001668 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00001669 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001670
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001671 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00001672 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001673 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001674
Nico Weber4c4c7322011-01-28 03:04:41 +00001675 return ParseAssignment(Name, allow_redef);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001676}
1677
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001678bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001679 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001680
1681 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00001682 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001683 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
1684 if (Str[i] != '\\') {
1685 Data += Str[i];
1686 continue;
1687 }
1688
1689 // Recognize escaped characters. Note that this escape semantics currently
1690 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
1691 ++i;
1692 if (i == e)
1693 return TokError("unexpected backslash at end of string");
1694
1695 // Recognize octal sequences.
1696 if ((unsigned) (Str[i] - '0') <= 7) {
1697 // Consume up to three octal characters.
1698 unsigned Value = Str[i] - '0';
1699
1700 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1701 ++i;
1702 Value = Value * 8 + (Str[i] - '0');
1703
1704 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1705 ++i;
1706 Value = Value * 8 + (Str[i] - '0');
1707 }
1708 }
1709
1710 if (Value > 255)
1711 return TokError("invalid octal escape sequence (out of range)");
1712
1713 Data += (unsigned char) Value;
1714 continue;
1715 }
1716
1717 // Otherwise recognize individual escapes.
1718 switch (Str[i]) {
1719 default:
1720 // Just reject invalid escape sequences for now.
1721 return TokError("invalid escape sequence (unrecognized character)");
1722
1723 case 'b': Data += '\b'; break;
1724 case 'f': Data += '\f'; break;
1725 case 'n': Data += '\n'; break;
1726 case 'r': Data += '\r'; break;
1727 case 't': Data += '\t'; break;
1728 case '"': Data += '"'; break;
1729 case '\\': Data += '\\'; break;
1730 }
1731 }
1732
1733 return false;
1734}
1735
Daniel Dunbara0d14262009-06-24 23:30:00 +00001736/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00001737/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
1738bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001739 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001740 CheckForValidSection();
1741
Daniel Dunbara0d14262009-06-24 23:30:00 +00001742 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001743 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00001744 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001745
Daniel Dunbar1ab75942009-08-14 18:19:52 +00001746 std::string Data;
1747 if (ParseEscapedString(Data))
1748 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001749
1750 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001751 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001752 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1753
Sean Callanan79ed1a82010-01-19 20:22:31 +00001754 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001755
1756 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001757 break;
1758
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001759 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00001760 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001761 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001762 }
1763 }
1764
Sean Callanan79ed1a82010-01-19 20:22:31 +00001765 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001766 return false;
1767}
1768
1769/// ParseDirectiveValue
1770/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1771bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001772 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001773 CheckForValidSection();
1774
Daniel Dunbara0d14262009-06-24 23:30:00 +00001775 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00001776 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00001777 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00001778 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001779 return true;
1780
Daniel Dunbar414c0c42010-05-23 18:36:38 +00001781 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00001782 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
1783 assert(Size <= 8 && "Invalid size");
1784 uint64_t IntValue = MCE->getValue();
1785 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
1786 return Error(ExprLoc, "literal value out of range for directive");
1787 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
1788 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001789 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001790
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001791 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001792 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001793
Daniel Dunbara0d14262009-06-24 23:30:00 +00001794 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001795 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001796 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001797 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001798 }
1799 }
1800
Sean Callanan79ed1a82010-01-19 20:22:31 +00001801 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001802 return false;
1803}
1804
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001805/// ParseDirectiveRealValue
1806/// ::= (.single | .double) [ expression (, expression)* ]
1807bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
1808 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1809 CheckForValidSection();
1810
1811 for (;;) {
1812 // We don't truly support arithmetic on floating point expressions, so we
1813 // have to manually parse unary prefixes.
1814 bool IsNeg = false;
1815 if (getLexer().is(AsmToken::Minus)) {
1816 Lex();
1817 IsNeg = true;
1818 } else if (getLexer().is(AsmToken::Plus))
1819 Lex();
1820
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001821 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00001822 getLexer().isNot(AsmToken::Real) &&
1823 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001824 return TokError("unexpected token in directive");
1825
1826 // Convert to an APFloat.
1827 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00001828 StringRef IDVal = getTok().getString();
1829 if (getLexer().is(AsmToken::Identifier)) {
1830 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
1831 Value = APFloat::getInf(Semantics);
1832 else if (!IDVal.compare_lower("nan"))
1833 Value = APFloat::getNaN(Semantics, false, ~0);
1834 else
1835 return TokError("invalid floating point literal");
1836 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001837 APFloat::opInvalidOp)
1838 return TokError("invalid floating point literal");
1839 if (IsNeg)
1840 Value.changeSign();
1841
1842 // Consume the numeric token.
1843 Lex();
1844
1845 // Emit the value as an integer.
1846 APInt AsInt = Value.bitcastToAPInt();
1847 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
1848 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
1849
1850 if (getLexer().is(AsmToken::EndOfStatement))
1851 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001852
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001853 if (getLexer().isNot(AsmToken::Comma))
1854 return TokError("unexpected token in directive");
1855 Lex();
1856 }
1857 }
1858
1859 Lex();
1860 return false;
1861}
1862
Daniel Dunbara0d14262009-06-24 23:30:00 +00001863/// ParseDirectiveSpace
1864/// ::= .space expression [ , expression ]
1865bool AsmParser::ParseDirectiveSpace() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001866 CheckForValidSection();
1867
Daniel Dunbara0d14262009-06-24 23:30:00 +00001868 int64_t NumBytes;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001869 if (ParseAbsoluteExpression(NumBytes))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001870 return true;
1871
1872 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001873 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1874 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001875 return TokError("unexpected token in '.space' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001876 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001877
Daniel Dunbar475839e2009-06-29 20:37:27 +00001878 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001879 return true;
1880
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001881 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001882 return TokError("unexpected token in '.space' directive");
1883 }
1884
Sean Callanan79ed1a82010-01-19 20:22:31 +00001885 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001886
1887 if (NumBytes <= 0)
1888 return TokError("invalid number of bytes in '.space' directive");
1889
1890 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001891 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001892
1893 return false;
1894}
1895
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001896/// ParseDirectiveZero
1897/// ::= .zero expression
1898bool AsmParser::ParseDirectiveZero() {
1899 CheckForValidSection();
1900
1901 int64_t NumBytes;
1902 if (ParseAbsoluteExpression(NumBytes))
1903 return true;
1904
Rafael Espindolae452b172010-10-05 19:42:57 +00001905 int64_t Val = 0;
1906 if (getLexer().is(AsmToken::Comma)) {
1907 Lex();
1908 if (ParseAbsoluteExpression(Val))
1909 return true;
1910 }
1911
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001912 if (getLexer().isNot(AsmToken::EndOfStatement))
1913 return TokError("unexpected token in '.zero' directive");
1914
1915 Lex();
1916
Rafael Espindolae452b172010-10-05 19:42:57 +00001917 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001918
1919 return false;
1920}
1921
Daniel Dunbara0d14262009-06-24 23:30:00 +00001922/// ParseDirectiveFill
1923/// ::= .fill expression , expression , expression
1924bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001925 CheckForValidSection();
1926
Daniel Dunbara0d14262009-06-24 23:30:00 +00001927 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001928 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001929 return true;
1930
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001931 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001932 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001933 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001934
Daniel Dunbara0d14262009-06-24 23:30:00 +00001935 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001936 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001937 return true;
1938
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001939 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001940 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001941 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001942
Daniel Dunbara0d14262009-06-24 23:30:00 +00001943 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001944 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001945 return true;
1946
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001947 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00001948 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001949
Sean Callanan79ed1a82010-01-19 20:22:31 +00001950 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001951
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00001952 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1953 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00001954
1955 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001956 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001957
1958 return false;
1959}
Daniel Dunbarc238b582009-06-25 22:44:51 +00001960
1961/// ParseDirectiveOrg
1962/// ::= .org expression [ , expression ]
1963bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001964 CheckForValidSection();
1965
Daniel Dunbar821e3332009-08-31 08:09:28 +00001966 const MCExpr *Offset;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001967 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00001968 return true;
1969
1970 // Parse optional fill expression.
1971 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001972 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1973 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00001974 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00001975 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001976
Daniel Dunbar475839e2009-06-29 20:37:27 +00001977 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00001978 return true;
1979
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001980 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00001981 return TokError("unexpected token in '.org' directive");
1982 }
1983
Sean Callanan79ed1a82010-01-19 20:22:31 +00001984 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00001985
1986 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1987 // has to be relative to the current section.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001988 getStreamer().EmitValueToOffset(Offset, FillExpr);
Daniel Dunbarc238b582009-06-25 22:44:51 +00001989
1990 return false;
1991}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001992
1993/// ParseDirectiveAlign
1994/// ::= {.align, ...} expression [ , expression [ , expression ]]
1995bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001996 CheckForValidSection();
1997
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00001998 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001999 int64_t Alignment;
2000 if (ParseAbsoluteExpression(Alignment))
2001 return true;
2002
2003 SMLoc MaxBytesLoc;
2004 bool HasFillExpr = false;
2005 int64_t FillExpr = 0;
2006 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002007 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2008 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002009 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002010 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002011
2012 // The fill expression can be omitted while specifying a maximum number of
2013 // alignment bytes, e.g:
2014 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002015 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002016 HasFillExpr = true;
2017 if (ParseAbsoluteExpression(FillExpr))
2018 return true;
2019 }
2020
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002021 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2022 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002023 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002024 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002025
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002026 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002027 if (ParseAbsoluteExpression(MaxBytesToFill))
2028 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002029
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002030 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002031 return TokError("unexpected token in directive");
2032 }
2033 }
2034
Sean Callanan79ed1a82010-01-19 20:22:31 +00002035 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002036
Daniel Dunbar648ac512010-05-17 21:54:30 +00002037 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002038 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002039
2040 // Compute alignment in bytes.
2041 if (IsPow2) {
2042 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002043 if (Alignment >= 32) {
2044 Error(AlignmentLoc, "invalid alignment value");
2045 Alignment = 31;
2046 }
2047
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002048 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002049 }
2050
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002051 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002052 if (MaxBytesLoc.isValid()) {
2053 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002054 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2055 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002056 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002057 }
2058
2059 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002060 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2061 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002062 MaxBytesToFill = 0;
2063 }
2064 }
2065
Daniel Dunbar648ac512010-05-17 21:54:30 +00002066 // Check whether we should use optimal code alignment for this .align
2067 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002068 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002069 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2070 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002071 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002072 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002073 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002074 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2075 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002076 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002077
2078 return false;
2079}
2080
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002081/// ParseDirectiveSymbolAttribute
2082/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00002083bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002084 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002085 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002086 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00002087 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002088
2089 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00002090 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002091
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002092 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002093
Jim Grosbach10ec6502011-09-15 17:56:49 +00002094 // Assembler local symbols don't make any sense here. Complain loudly.
2095 if (Sym->isTemporary())
2096 return Error(Loc, "non-local symbol required in directive");
2097
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002098 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002099
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002100 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002101 break;
2102
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002103 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002104 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002105 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002106 }
2107 }
2108
Sean Callanan79ed1a82010-01-19 20:22:31 +00002109 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00002110 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002111}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002112
2113/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00002114/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2115bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002116 CheckForValidSection();
2117
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002118 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002119 StringRef Name;
2120 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002121 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002122
Daniel Dunbar76c4d762009-07-31 21:55:09 +00002123 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002124 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002125
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002126 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002127 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002128 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002129
2130 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002131 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002132 if (ParseAbsoluteExpression(Size))
2133 return true;
2134
2135 int64_t Pow2Alignment = 0;
2136 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002137 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00002138 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002139 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002140 if (ParseAbsoluteExpression(Pow2Alignment))
2141 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002142
Chris Lattner258281d2010-01-19 06:22:22 +00002143 // If this target takes alignments in bytes (not log) validate and convert.
2144 if (Lexer.getMAI().getAlignmentIsInBytes()) {
2145 if (!isPowerOf2_64(Pow2Alignment))
2146 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2147 Pow2Alignment = Log2_64(Pow2Alignment);
2148 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002149 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002150
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002151 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00002152 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002153
Sean Callanan79ed1a82010-01-19 20:22:31 +00002154 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002155
Chris Lattner1fc3d752009-07-09 17:25:12 +00002156 // NOTE: a size of zero for a .comm should create a undefined symbol
2157 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002158 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002159 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2160 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002161
Eric Christopherc260a3e2010-05-14 01:38:54 +00002162 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002163 // may internally end up wanting an alignment in bytes.
2164 // FIXME: Diagnose overflow.
2165 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002166 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2167 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002168
Daniel Dunbar8906ff12009-08-22 07:22:36 +00002169 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002170 return Error(IDLoc, "invalid symbol redefinition");
2171
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002172 // '.lcomm' is equivalent to '.zerofill'.
Chris Lattner1fc3d752009-07-09 17:25:12 +00002173 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002174 if (IsLocal) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002175 getStreamer().EmitZerofill(Ctx.getMachOSection(
2176 "__DATA", "__bss", MCSectionMachO::S_ZEROFILL,
2177 0, SectionKind::getBSS()),
2178 Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002179 return false;
2180 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002181
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002182 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002183 return false;
2184}
Chris Lattner9be3fee2009-07-10 22:20:30 +00002185
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002186/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002187/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002188bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002189 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002190 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002191
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002192 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002193 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002194 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002195
Sean Callanan79ed1a82010-01-19 20:22:31 +00002196 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002197
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002198 if (Str.empty())
2199 Error(Loc, ".abort detected. Assembly stopping.");
2200 else
2201 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002202 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002203
2204 return false;
2205}
Kevin Enderby71148242009-07-14 21:35:03 +00002206
Kevin Enderby1f049b22009-07-14 23:21:55 +00002207/// ParseDirectiveInclude
2208/// ::= .include "filename"
2209bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002210 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002211 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002212
Sean Callanan18b83232010-01-19 21:44:56 +00002213 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002214 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002215 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00002216
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002217 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002218 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002219
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002220 // Strip the quotes.
2221 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002222
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002223 // Attempt to switch the lexer to the included file before consuming the end
2224 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00002225 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00002226 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002227 return true;
2228 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00002229
2230 return false;
2231}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00002232
Kevin Enderbyc55acca2011-12-14 21:47:48 +00002233/// ParseDirectiveIncbin
2234/// ::= .incbin "filename"
2235bool AsmParser::ParseDirectiveIncbin() {
2236 if (getLexer().isNot(AsmToken::String))
2237 return TokError("expected string in '.incbin' directive");
2238
2239 std::string Filename = getTok().getString();
2240 SMLoc IncbinLoc = getLexer().getLoc();
2241 Lex();
2242
2243 if (getLexer().isNot(AsmToken::EndOfStatement))
2244 return TokError("unexpected token in '.incbin' directive");
2245
2246 // Strip the quotes.
2247 Filename = Filename.substr(1, Filename.size()-2);
2248
2249 // Attempt to process the included file.
2250 if (ProcessIncbinFile(Filename)) {
2251 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2252 return true;
2253 }
2254
2255 return false;
2256}
2257
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002258/// ParseDirectiveIf
2259/// ::= .if expression
2260bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002261 TheCondStack.push_back(TheCondState);
2262 TheCondState.TheCond = AsmCond::IfCond;
2263 if(TheCondState.Ignore) {
2264 EatToEndOfStatement();
2265 }
2266 else {
2267 int64_t ExprValue;
2268 if (ParseAbsoluteExpression(ExprValue))
2269 return true;
2270
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002271 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002272 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002273
Sean Callanan79ed1a82010-01-19 20:22:31 +00002274 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002275
2276 TheCondState.CondMet = ExprValue;
2277 TheCondState.Ignore = !TheCondState.CondMet;
2278 }
2279
2280 return false;
2281}
2282
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00002283bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2284 StringRef Name;
2285 TheCondStack.push_back(TheCondState);
2286 TheCondState.TheCond = AsmCond::IfCond;
2287
2288 if (TheCondState.Ignore) {
2289 EatToEndOfStatement();
2290 } else {
2291 if (ParseIdentifier(Name))
2292 return TokError("expected identifier after '.ifdef'");
2293
2294 Lex();
2295
2296 MCSymbol *Sym = getContext().LookupSymbol(Name);
2297
2298 if (expect_defined)
2299 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2300 else
2301 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2302 TheCondState.Ignore = !TheCondState.CondMet;
2303 }
2304
2305 return false;
2306}
2307
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002308/// ParseDirectiveElseIf
2309/// ::= .elseif expression
2310bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2311 if (TheCondState.TheCond != AsmCond::IfCond &&
2312 TheCondState.TheCond != AsmCond::ElseIfCond)
2313 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2314 " an .elseif");
2315 TheCondState.TheCond = AsmCond::ElseIfCond;
2316
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002317 bool LastIgnoreState = false;
2318 if (!TheCondStack.empty())
2319 LastIgnoreState = TheCondStack.back().Ignore;
2320 if (LastIgnoreState || TheCondState.CondMet) {
2321 TheCondState.Ignore = true;
2322 EatToEndOfStatement();
2323 }
2324 else {
2325 int64_t ExprValue;
2326 if (ParseAbsoluteExpression(ExprValue))
2327 return true;
2328
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002329 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002330 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002331
Sean Callanan79ed1a82010-01-19 20:22:31 +00002332 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002333 TheCondState.CondMet = ExprValue;
2334 TheCondState.Ignore = !TheCondState.CondMet;
2335 }
2336
2337 return false;
2338}
2339
2340/// ParseDirectiveElse
2341/// ::= .else
2342bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002343 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002344 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002345
Sean Callanan79ed1a82010-01-19 20:22:31 +00002346 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002347
2348 if (TheCondState.TheCond != AsmCond::IfCond &&
2349 TheCondState.TheCond != AsmCond::ElseIfCond)
2350 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2351 ".elseif");
2352 TheCondState.TheCond = AsmCond::ElseCond;
2353 bool LastIgnoreState = false;
2354 if (!TheCondStack.empty())
2355 LastIgnoreState = TheCondStack.back().Ignore;
2356 if (LastIgnoreState || TheCondState.CondMet)
2357 TheCondState.Ignore = true;
2358 else
2359 TheCondState.Ignore = false;
2360
2361 return false;
2362}
2363
2364/// ParseDirectiveEndIf
2365/// ::= .endif
2366bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002367 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002368 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002369
Sean Callanan79ed1a82010-01-19 20:22:31 +00002370 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002371
2372 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2373 TheCondStack.empty())
2374 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2375 ".else");
2376 if (!TheCondStack.empty()) {
2377 TheCondState = TheCondStack.back();
2378 TheCondStack.pop_back();
2379 }
2380
2381 return false;
2382}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002383
2384/// ParseDirectiveFile
Nick Lewycky44d798d2011-10-17 23:05:28 +00002385/// ::= .file [number] filename
2386/// ::= .file number directory filename
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002387bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002388 // FIXME: I'm not sure what this is.
2389 int64_t FileNumber = -1;
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002390 SMLoc FileNumberLoc = getLexer().getLoc();
Daniel Dunbareceec052010-07-12 17:45:27 +00002391 if (getLexer().is(AsmToken::Integer)) {
Sean Callanan18b83232010-01-19 21:44:56 +00002392 FileNumber = getTok().getIntVal();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002393 Lex();
Daniel Dunbareceec052010-07-12 17:45:27 +00002394
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002395 if (FileNumber < 1)
2396 return TokError("file number less than one");
2397 }
2398
Daniel Dunbareceec052010-07-12 17:45:27 +00002399 if (getLexer().isNot(AsmToken::String))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002400 return TokError("unexpected token in '.file' directive");
Daniel Dunbareceec052010-07-12 17:45:27 +00002401
Nick Lewycky44d798d2011-10-17 23:05:28 +00002402 // Usually the directory and filename together, otherwise just the directory.
2403 StringRef Path = getTok().getString();
2404 Path = Path.substr(1, Path.size()-2);
Sean Callanan79ed1a82010-01-19 20:22:31 +00002405 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002406
Nick Lewycky44d798d2011-10-17 23:05:28 +00002407 StringRef Directory;
2408 StringRef Filename;
2409 if (getLexer().is(AsmToken::String)) {
2410 if (FileNumber == -1)
2411 return TokError("explicit path specified, but no file number");
2412 Filename = getTok().getString();
2413 Filename = Filename.substr(1, Filename.size()-2);
2414 Directory = Path;
2415 Lex();
2416 } else {
2417 Filename = Path;
2418 }
2419
Daniel Dunbareceec052010-07-12 17:45:27 +00002420 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002421 return TokError("unexpected token in '.file' directive");
2422
Kevin Enderby613b7572011-11-01 22:27:22 +00002423 if (getContext().getGenDwarfForAssembly() == true)
2424 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2425 "used to generate dwarf debug info for assembly code");
2426
Chris Lattnerd32e8032010-01-25 19:02:58 +00002427 if (FileNumber == -1)
Daniel Dunbareceec052010-07-12 17:45:27 +00002428 getStreamer().EmitFileDirective(Filename);
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002429 else {
Nick Lewycky44d798d2011-10-17 23:05:28 +00002430 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002431 Error(FileNumberLoc, "file number already allocated");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002432 }
Daniel Dunbareceec052010-07-12 17:45:27 +00002433
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002434 return false;
2435}
2436
2437/// ParseDirectiveLine
2438/// ::= .line [number]
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002439bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbareceec052010-07-12 17:45:27 +00002440 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2441 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002442 return TokError("unexpected token in '.line' directive");
2443
Sean Callanan18b83232010-01-19 21:44:56 +00002444 int64_t LineNumber = getTok().getIntVal();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002445 (void) LineNumber;
Sean Callanan79ed1a82010-01-19 20:22:31 +00002446 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002447
2448 // FIXME: Do something with the .line.
2449 }
2450
Daniel Dunbareceec052010-07-12 17:45:27 +00002451 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar839348a2010-07-01 20:20:01 +00002452 return TokError("unexpected token in '.line' directive");
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002453
2454 return false;
2455}
2456
2457
2458/// ParseDirectiveLoc
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002459/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002460/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2461/// The first number is a file number, must have been previously assigned with
2462/// a .file directive, the second number is the line number and optionally the
2463/// third number is a column position (zero if not specified). The remaining
2464/// optional items are .loc sub-directives.
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002465bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002466
Daniel Dunbareceec052010-07-12 17:45:27 +00002467 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002468 return TokError("unexpected token in '.loc' directive");
Sean Callanan18b83232010-01-19 21:44:56 +00002469 int64_t FileNumber = getTok().getIntVal();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002470 if (FileNumber < 1)
2471 return TokError("file number less than one in '.loc' directive");
Kevin Enderby3f55c242010-10-04 20:17:24 +00002472 if (!getContext().isValidDwarfFileNumber(FileNumber))
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002473 return TokError("unassigned file number in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002474 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002475
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002476 int64_t LineNumber = 0;
2477 if (getLexer().is(AsmToken::Integer)) {
2478 LineNumber = getTok().getIntVal();
2479 if (LineNumber < 1)
2480 return TokError("line number less than one in '.loc' directive");
2481 Lex();
2482 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002483
2484 int64_t ColumnPos = 0;
2485 if (getLexer().is(AsmToken::Integer)) {
2486 ColumnPos = getTok().getIntVal();
2487 if (ColumnPos < 0)
2488 return TokError("column position less than zero in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002489 Lex();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002490 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002491
Kevin Enderbyc0957932010-09-30 16:52:03 +00002492 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002493 unsigned Isa = 0;
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002494 int64_t Discriminator = 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002495 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2496 for (;;) {
2497 if (getLexer().is(AsmToken::EndOfStatement))
2498 break;
2499
2500 StringRef Name;
2501 SMLoc Loc = getTok().getLoc();
2502 if (getParser().ParseIdentifier(Name))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002503 return TokError("unexpected token in '.loc' directive");
2504
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002505 if (Name == "basic_block")
2506 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2507 else if (Name == "prologue_end")
2508 Flags |= DWARF2_FLAG_PROLOGUE_END;
2509 else if (Name == "epilogue_begin")
2510 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2511 else if (Name == "is_stmt") {
2512 SMLoc Loc = getTok().getLoc();
2513 const MCExpr *Value;
2514 if (getParser().ParseExpression(Value))
2515 return true;
2516 // The expression must be the constant 0 or 1.
2517 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2518 int Value = MCE->getValue();
2519 if (Value == 0)
2520 Flags &= ~DWARF2_FLAG_IS_STMT;
2521 else if (Value == 1)
2522 Flags |= DWARF2_FLAG_IS_STMT;
2523 else
2524 return Error(Loc, "is_stmt value not 0 or 1");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002525 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002526 else {
2527 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2528 }
2529 }
2530 else if (Name == "isa") {
2531 SMLoc Loc = getTok().getLoc();
2532 const MCExpr *Value;
2533 if (getParser().ParseExpression(Value))
2534 return true;
2535 // The expression must be a constant greater or equal to 0.
2536 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2537 int Value = MCE->getValue();
2538 if (Value < 0)
2539 return Error(Loc, "isa number less than zero");
2540 Isa = Value;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002541 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002542 else {
2543 return Error(Loc, "isa number not a constant value");
2544 }
2545 }
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002546 else if (Name == "discriminator") {
2547 if (getParser().ParseAbsoluteExpression(Discriminator))
2548 return true;
2549 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002550 else {
2551 return Error(Loc, "unknown sub-directive in '.loc' directive");
2552 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002553
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002554 if (getLexer().is(AsmToken::EndOfStatement))
2555 break;
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002556 }
2557 }
2558
Rafael Espindolaaf6b58082010-11-16 21:20:32 +00002559 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
Devang Patel3f3bf932011-04-18 20:26:49 +00002560 Isa, Discriminator, StringRef());
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002561
2562 return false;
2563}
2564
Daniel Dunbar138abae2010-10-16 04:56:42 +00002565/// ParseDirectiveStabs
2566/// ::= .stabs string, number, number, number
2567bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2568 SMLoc DirectiveLoc) {
2569 return TokError("unsupported directive '" + Directive + "'");
2570}
2571
Rafael Espindolaf9efd832011-05-10 01:10:18 +00002572/// ParseDirectiveCFISections
2573/// ::= .cfi_sections section [, section]
2574bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2575 SMLoc DirectiveLoc) {
2576 StringRef Name;
2577 bool EH = false;
2578 bool Debug = false;
2579
2580 if (getParser().ParseIdentifier(Name))
2581 return TokError("Expected an identifier");
2582
2583 if (Name == ".eh_frame")
2584 EH = true;
2585 else if (Name == ".debug_frame")
2586 Debug = true;
2587
2588 if (getLexer().is(AsmToken::Comma)) {
2589 Lex();
2590
2591 if (getParser().ParseIdentifier(Name))
2592 return TokError("Expected an identifier");
2593
2594 if (Name == ".eh_frame")
2595 EH = true;
2596 else if (Name == ".debug_frame")
2597 Debug = true;
2598 }
2599
2600 getStreamer().EmitCFISections(EH, Debug);
2601
2602 return false;
2603}
2604
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002605/// ParseDirectiveCFIStartProc
2606/// ::= .cfi_startproc
2607bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
2608 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002609 getStreamer().EmitCFIStartProc();
2610 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002611}
2612
2613/// ParseDirectiveCFIEndProc
2614/// ::= .cfi_endproc
2615bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002616 getStreamer().EmitCFIEndProc();
2617 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002618}
2619
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002620/// ParseRegisterOrRegisterNumber - parse register name or number.
2621bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2622 SMLoc DirectiveLoc) {
2623 unsigned RegNo;
2624
Jim Grosbach6f888a82011-06-02 17:14:04 +00002625 if (getLexer().isNot(AsmToken::Integer)) {
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002626 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
2627 DirectiveLoc))
2628 return true;
Evan Cheng0e6a0522011-07-18 20:57:22 +00002629 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002630 } else
2631 return getParser().ParseAbsoluteExpression(Register);
Jim Grosbachde2f5f42011-02-11 19:05:56 +00002632
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002633 return false;
2634}
2635
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002636/// ParseDirectiveCFIDefCfa
2637/// ::= .cfi_def_cfa register, offset
2638bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
2639 SMLoc DirectiveLoc) {
2640 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002641 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002642 return true;
2643
2644 if (getLexer().isNot(AsmToken::Comma))
2645 return TokError("unexpected token in directive");
2646 Lex();
2647
2648 int64_t Offset = 0;
2649 if (getParser().ParseAbsoluteExpression(Offset))
2650 return true;
2651
Rafael Espindola066c2f42011-04-12 23:59:07 +00002652 getStreamer().EmitCFIDefCfa(Register, Offset);
2653 return false;
Rafael Espindolab40a71f2010-12-29 01:42:56 +00002654}
2655
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002656/// ParseDirectiveCFIDefCfaOffset
2657/// ::= .cfi_def_cfa_offset offset
2658bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
2659 SMLoc DirectiveLoc) {
2660 int64_t Offset = 0;
2661 if (getParser().ParseAbsoluteExpression(Offset))
2662 return true;
2663
Rafael Espindola066c2f42011-04-12 23:59:07 +00002664 getStreamer().EmitCFIDefCfaOffset(Offset);
2665 return false;
Rafael Espindola53abbe52011-04-11 20:29:16 +00002666}
2667
2668/// ParseDirectiveCFIAdjustCfaOffset
2669/// ::= .cfi_adjust_cfa_offset adjustment
2670bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
2671 SMLoc DirectiveLoc) {
2672 int64_t Adjustment = 0;
2673 if (getParser().ParseAbsoluteExpression(Adjustment))
2674 return true;
2675
Rafael Espindola5d7dcd32011-04-12 18:53:30 +00002676 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2677 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002678}
2679
2680/// ParseDirectiveCFIDefCfaRegister
2681/// ::= .cfi_def_cfa_register register
2682bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
2683 SMLoc DirectiveLoc) {
2684 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002685 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002686 return true;
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002687
Rafael Espindola066c2f42011-04-12 23:59:07 +00002688 getStreamer().EmitCFIDefCfaRegister(Register);
2689 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002690}
2691
2692/// ParseDirectiveCFIOffset
Rafael Espindolaa61842b2011-04-11 21:49:50 +00002693/// ::= .cfi_offset register, offset
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002694bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
2695 int64_t Register = 0;
2696 int64_t Offset = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00002697
2698 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002699 return true;
2700
2701 if (getLexer().isNot(AsmToken::Comma))
2702 return TokError("unexpected token in directive");
2703 Lex();
2704
2705 if (getParser().ParseAbsoluteExpression(Offset))
2706 return true;
2707
Rafael Espindola066c2f42011-04-12 23:59:07 +00002708 getStreamer().EmitCFIOffset(Register, Offset);
2709 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002710}
2711
Rafael Espindolaa61842b2011-04-11 21:49:50 +00002712/// ParseDirectiveCFIRelOffset
2713/// ::= .cfi_rel_offset register, offset
2714bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
2715 SMLoc DirectiveLoc) {
2716 int64_t Register = 0;
2717
2718 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2719 return true;
2720
2721 if (getLexer().isNot(AsmToken::Comma))
2722 return TokError("unexpected token in directive");
2723 Lex();
2724
2725 int64_t Offset = 0;
2726 if (getParser().ParseAbsoluteExpression(Offset))
2727 return true;
2728
Rafael Espindola25f492e2011-04-12 16:12:03 +00002729 getStreamer().EmitCFIRelOffset(Register, Offset);
2730 return false;
Rafael Espindolaa61842b2011-04-11 21:49:50 +00002731}
2732
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002733static bool isValidEncoding(int64_t Encoding) {
2734 if (Encoding & ~0xff)
2735 return false;
2736
2737 if (Encoding == dwarf::DW_EH_PE_omit)
2738 return true;
2739
2740 const unsigned Format = Encoding & 0xf;
2741 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2742 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2743 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2744 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2745 return false;
2746
Rafael Espindolacaf11582010-12-29 04:31:26 +00002747 const unsigned Application = Encoding & 0x70;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002748 if (Application != dwarf::DW_EH_PE_absptr &&
Rafael Espindolacaf11582010-12-29 04:31:26 +00002749 Application != dwarf::DW_EH_PE_pcrel)
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002750 return false;
2751
2752 return true;
2753}
2754
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002755/// ParseDirectiveCFIPersonalityOrLsda
2756/// ::= .cfi_personality encoding, [symbol_name]
2757/// ::= .cfi_lsda encoding, [symbol_name]
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002758bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002759 SMLoc DirectiveLoc) {
2760 int64_t Encoding = 0;
2761 if (getParser().ParseAbsoluteExpression(Encoding))
2762 return true;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002763 if (Encoding == dwarf::DW_EH_PE_omit)
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002764 return false;
2765
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00002766 if (!isValidEncoding(Encoding))
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002767 return TokError("unsupported encoding.");
2768
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002769 if (getLexer().isNot(AsmToken::Comma))
2770 return TokError("unexpected token in directive");
2771 Lex();
2772
2773 StringRef Name;
2774 if (getParser().ParseIdentifier(Name))
2775 return TokError("expected identifier in directive");
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002776
2777 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2778
2779 if (IDVal == ".cfi_personality")
Rafael Espindola066c2f42011-04-12 23:59:07 +00002780 getStreamer().EmitCFIPersonality(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002781 else {
2782 assert(IDVal == ".cfi_lsda");
Rafael Espindola066c2f42011-04-12 23:59:07 +00002783 getStreamer().EmitCFILsda(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00002784 }
Rafael Espindola066c2f42011-04-12 23:59:07 +00002785 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00002786}
2787
Rafael Espindolafe024d02010-12-28 18:36:23 +00002788/// ParseDirectiveCFIRememberState
2789/// ::= .cfi_remember_state
2790bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
2791 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002792 getStreamer().EmitCFIRememberState();
2793 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00002794}
2795
2796/// ParseDirectiveCFIRestoreState
2797/// ::= .cfi_remember_state
2798bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
2799 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00002800 getStreamer().EmitCFIRestoreState();
2801 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00002802}
2803
Rafael Espindolac5754392011-04-12 15:31:05 +00002804/// ParseDirectiveCFISameValue
2805/// ::= .cfi_same_value register
2806bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
2807 SMLoc DirectiveLoc) {
2808 int64_t Register = 0;
2809
2810 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2811 return true;
2812
2813 getStreamer().EmitCFISameValue(Register);
2814
2815 return false;
2816}
2817
Daniel Dunbar3c802de2010-07-18 18:38:02 +00002818/// ParseDirectiveMacrosOnOff
2819/// ::= .macros_on
2820/// ::= .macros_off
2821bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
2822 SMLoc DirectiveLoc) {
2823 if (getLexer().isNot(AsmToken::EndOfStatement))
2824 return Error(getLexer().getLoc(),
2825 "unexpected token in '" + Directive + "' directive");
2826
2827 getParser().MacrosEnabled = Directive == ".macros_on";
2828
2829 return false;
2830}
Daniel Dunbard1e3b442010-07-17 02:26:10 +00002831
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00002832/// ParseDirectiveMacro
Rafael Espindola65366442011-06-05 02:43:45 +00002833/// ::= .macro name [parameters]
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00002834bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
2835 SMLoc DirectiveLoc) {
2836 StringRef Name;
2837 if (getParser().ParseIdentifier(Name))
2838 return TokError("expected identifier in directive");
2839
Rafael Espindola65366442011-06-05 02:43:45 +00002840 std::vector<StringRef> Parameters;
2841 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2842 for(;;) {
2843 StringRef Parameter;
2844 if (getParser().ParseIdentifier(Parameter))
2845 return TokError("expected identifier in directive");
2846 Parameters.push_back(Parameter);
2847
2848 if (getLexer().isNot(AsmToken::Comma))
2849 break;
2850 Lex();
2851 }
2852 }
2853
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00002854 if (getLexer().isNot(AsmToken::EndOfStatement))
2855 return TokError("unexpected token in '.macro' directive");
2856
2857 // Eat the end of statement.
2858 Lex();
2859
2860 AsmToken EndToken, StartToken = getTok();
2861
2862 // Lex the macro definition.
2863 for (;;) {
2864 // Check whether we have reached the end of the file.
2865 if (getLexer().is(AsmToken::Eof))
2866 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2867
2868 // Otherwise, check whether we have reach the .endmacro.
2869 if (getLexer().is(AsmToken::Identifier) &&
2870 (getTok().getIdentifier() == ".endm" ||
2871 getTok().getIdentifier() == ".endmacro")) {
2872 EndToken = getTok();
2873 Lex();
2874 if (getLexer().isNot(AsmToken::EndOfStatement))
2875 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2876 "' directive");
2877 break;
2878 }
2879
2880 // Otherwise, scan til the end of the statement.
2881 getParser().EatToEndOfStatement();
2882 }
2883
2884 if (getParser().MacroMap.lookup(Name)) {
2885 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
2886 }
2887
2888 const char *BodyStart = StartToken.getLoc().getPointer();
2889 const char *BodyEnd = EndToken.getLoc().getPointer();
2890 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Rafael Espindola65366442011-06-05 02:43:45 +00002891 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00002892 return false;
2893}
2894
2895/// ParseDirectiveEndMacro
2896/// ::= .endm
2897/// ::= .endmacro
2898bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
2899 SMLoc DirectiveLoc) {
2900 if (getLexer().isNot(AsmToken::EndOfStatement))
2901 return TokError("unexpected token in '" + Directive + "' directive");
2902
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00002903 // If we are inside a macro instantiation, terminate the current
2904 // instantiation.
2905 if (!getParser().ActiveMacros.empty()) {
2906 getParser().HandleMacroExit();
2907 return false;
2908 }
2909
2910 // Otherwise, this .endmacro is a stray entry in the file; well formed
2911 // .endmacro directives are handled during the macro definition parsing.
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00002912 return TokError("unexpected '" + Directive + "' in file, "
2913 "no current macro definition");
2914}
2915
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00002916bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
Rafael Espindola3ff57092010-11-02 17:22:24 +00002917 getParser().CheckForValidSection();
2918
2919 const MCExpr *Value;
2920
2921 if (getParser().ParseExpression(Value))
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00002922 return true;
2923
2924 if (getLexer().isNot(AsmToken::EndOfStatement))
2925 return TokError("unexpected token in directive");
2926
2927 if (DirName[1] == 's')
Rafael Espindola3ff57092010-11-02 17:22:24 +00002928 getStreamer().EmitSLEB128Value(Value);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00002929 else
Rafael Espindola3ff57092010-11-02 17:22:24 +00002930 getStreamer().EmitULEB128Value(Value);
2931
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00002932 return false;
2933}
2934
2935
Daniel Dunbard1e3b442010-07-17 02:26:10 +00002936/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00002937MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00002938 MCContext &C, MCStreamer &Out,
2939 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00002940 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00002941}