blob: e1a1f89f423ae4170e106bb8b81569ef76076a50 [file] [log] [blame]
Chris Lattner27aa7d22009-06-21 20:16:42 +00001//===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This class implements the parser for assembly files.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbarb95a0792010-09-24 01:59:56 +000014#include "llvm/ADT/APFloat.h"
Daniel Dunbar7c0a3342009-08-26 22:49:51 +000015#include "llvm/ADT/SmallString.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000016#include "llvm/ADT/StringMap.h"
Daniel Dunbarf9507ff2009-07-27 23:20:52 +000017#include "llvm/ADT/Twine.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000018#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000019#include "llvm/MC/MCContext.h"
Evan Cheng94b95502011-07-26 00:24:13 +000020#include "llvm/MC/MCDwarf.h"
Daniel Dunbar28c251b2009-08-31 08:06:59 +000021#include "llvm/MC/MCExpr.h"
Chad Rosierb1f8c132012-10-18 15:49:34 +000022#include "llvm/MC/MCInstPrinter.h"
23#include "llvm/MC/MCInstrInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000024#include "llvm/MC/MCParser/AsmCond.h"
25#include "llvm/MC/MCParser/AsmLexer.h"
26#include "llvm/MC/MCParser/MCAsmParser.h"
27#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Evan Chenge76a33b2011-07-20 05:58:47 +000028#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000029#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000030#include "llvm/MC/MCStreamer.h"
Daniel Dunbardce0f3c2009-06-29 23:43:14 +000031#include "llvm/MC/MCSymbol.h"
Evan Cheng94b95502011-07-26 00:24:13 +000032#include "llvm/MC/MCTargetAsmParser.h"
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000033#include "llvm/Support/CommandLine.h"
Benjamin Kramer518ff562012-01-28 15:28:41 +000034#include "llvm/Support/ErrorHandling.h"
Jim Grosbach254cf032011-06-29 16:05:14 +000035#include "llvm/Support/MathExtras.h"
Kevin Enderbyf187ac52010-06-28 21:45:58 +000036#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000037#include "llvm/Support/SourceMgr.h"
Chris Lattnerb0789ed2009-06-21 20:54:55 +000038#include "llvm/Support/raw_ostream.h"
Nick Lewycky476b2422010-12-19 20:43:38 +000039#include <cctype>
Chad Rosierb1f8c132012-10-18 15:49:34 +000040#include <set>
41#include <string>
Daniel Dunbaraef87e32010-07-18 18:31:38 +000042#include <vector>
Chris Lattner27aa7d22009-06-21 20:16:42 +000043using namespace llvm;
44
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000045static cl::opt<bool>
46FatalAssemblerWarnings("fatal-assembler-warnings",
47 cl::desc("Consider warnings as error"));
48
Eric Christopher2318ba12012-12-18 00:30:54 +000049MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
Nick Lewycky0d7d11d2012-10-19 07:00:09 +000050
Daniel Dunbar81ea00f2010-07-12 17:54:38 +000051namespace {
52
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000053/// \brief Helper class for tracking macro definitions.
Rafael Espindola28c1f6662012-06-03 22:41:23 +000054typedef std::vector<AsmToken> MacroArgument;
Rafael Espindola8a403d32012-08-08 14:51:03 +000055typedef std::vector<MacroArgument> MacroArguments;
Preston Gurd6c9176a2012-09-19 20:29:04 +000056typedef std::pair<StringRef, MacroArgument> MacroParameter;
Rafael Espindola8a403d32012-08-08 14:51:03 +000057typedef std::vector<MacroParameter> MacroParameters;
Rafael Espindola28c1f6662012-06-03 22:41:23 +000058
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000059struct Macro {
60 StringRef Name;
61 StringRef Body;
Rafael Espindola8a403d32012-08-08 14:51:03 +000062 MacroParameters Parameters;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000063
64public:
Rafael Espindola8a403d32012-08-08 14:51:03 +000065 Macro(StringRef N, StringRef B, const MacroParameters &P) :
Rafael Espindola65366442011-06-05 02:43:45 +000066 Name(N), Body(B), Parameters(P) {}
Daniel Dunbar6d8cf082010-07-18 18:47:21 +000067};
68
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000069/// \brief Helper class for storing information about an active macro
70/// instantiation.
71struct MacroInstantiation {
72 /// The macro being instantiated.
73 const Macro *TheMacro;
74
75 /// The macro instantiation with substitutions.
76 MemoryBuffer *Instantiation;
77
78 /// The location of the instantiation.
79 SMLoc InstantiationLoc;
80
Daniel Dunbar4259a1a2012-12-01 01:38:48 +000081 /// The buffer where parsing should resume upon instantiation completion.
82 int ExitBuffer;
83
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000084 /// The location where parsing should resume upon instantiation completion.
85 SMLoc ExitLoc;
86
87public:
Daniel Dunbar4259a1a2012-12-01 01:38:48 +000088 MacroInstantiation(const Macro *M, SMLoc IL, int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000089 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000090};
91
Chad Rosier6a020a72012-10-25 20:41:34 +000092//struct AsmRewrite;
Eli Friedman2128aae2012-10-22 23:58:19 +000093struct ParseStatementInfo {
94 /// ParsedOperands - The parsed operands from the last parsed statement.
95 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
96
97 /// Opcode - The opcode from the last parsed instruction.
98 unsigned Opcode;
99
Chad Rosier57498012012-12-12 22:45:52 +0000100 /// Error - Was there an error parsing the inline assembly?
101 bool ParseError;
102
Eli Friedman2128aae2012-10-22 23:58:19 +0000103 SmallVectorImpl<AsmRewrite> *AsmRewrites;
104
Chad Rosier57498012012-12-12 22:45:52 +0000105 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
Eli Friedman2128aae2012-10-22 23:58:19 +0000106 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier57498012012-12-12 22:45:52 +0000107 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman2128aae2012-10-22 23:58:19 +0000108
109 ~ParseStatementInfo() {
110 // Free any parsed operands.
111 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
112 delete ParsedOperands[i];
113 ParsedOperands.clear();
114 }
115};
116
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000117/// \brief The concrete assembly parser instance.
118class AsmParser : public MCAsmParser {
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000119 friend class GenericAsmParser;
120
Craig Topper85aadc02012-09-15 16:23:52 +0000121 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
122 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000123private:
124 AsmLexer Lexer;
125 MCContext &Ctx;
126 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000127 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000128 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +0000129 SourceMgr::DiagHandlerTy SavedDiagHandler;
130 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000131 MCAsmParserExtension *GenericParser;
132 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000133
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000134 /// This is the current buffer index we're lexing from as managed by the
135 /// SourceMgr object.
136 int CurBuffer;
137
138 AsmCond TheCondState;
139 std::vector<AsmCond> TheCondStack;
140
141 /// DirectiveMap - This is a table handlers for directives. Each handler is
142 /// invoked after the directive identifier is read and is responsible for
143 /// parsing and validating the rest of the directive. The handler is passed
144 /// in the directive name and the location of the directive keyword.
145 StringMap<std::pair<MCAsmParserExtension*, DirectiveHandler> > DirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000146
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000147 /// MacroMap - Map of currently defined macros.
148 StringMap<Macro*> MacroMap;
149
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000150 /// ActiveMacros - Stack of active macro instantiations.
151 std::vector<MacroInstantiation*> ActiveMacros;
152
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000153 /// Boolean tracking whether macro substitution is enabled.
154 unsigned MacrosEnabled : 1;
155
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000156 /// Flag tracking whether any errors have been encountered.
157 unsigned HadError : 1;
158
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000159 /// The values from the last parsed cpp hash file line comment if any.
160 StringRef CppHashFilename;
161 int64_t CppHashLineNumber;
162 SMLoc CppHashLoc;
Kevin Enderby32c1a822012-11-05 21:55:41 +0000163 int CppHashBuf;
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000164
Devang Patel0db58bf2012-01-31 18:14:05 +0000165 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
166 unsigned AssemblerDialect;
167
Preston Gurd7b6f2032012-09-19 20:36:12 +0000168 /// IsDarwin - is Darwin compatibility enabled?
169 bool IsDarwin;
170
Chad Rosier8f138d12012-10-15 17:19:13 +0000171 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000172 bool ParsingInlineAsm;
173
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000174public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000175 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000176 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000177 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000178
179 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
180
Craig Topper345d16d2012-08-29 05:48:09 +0000181 virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
182 StringRef Directive,
183 DirectiveHandler Handler) {
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000184 DirectiveMap[Directive] = std::make_pair(Object, Handler);
185 }
186
187public:
188 /// @name MCAsmParser Interface
189 /// {
190
191 virtual SourceMgr &getSourceManager() { return SrcMgr; }
192 virtual MCAsmLexer &getLexer() { return Lexer; }
193 virtual MCContext &getContext() { return Ctx; }
194 virtual MCStreamer &getStreamer() { return Out; }
Eric Christopher2318ba12012-12-18 00:30:54 +0000195 virtual unsigned getAssemblerDialect() {
Devang Patel0db58bf2012-01-31 18:14:05 +0000196 if (AssemblerDialect == ~0U)
Eric Christopher2318ba12012-12-18 00:30:54 +0000197 return MAI.getAssemblerDialect();
Devang Patel0db58bf2012-01-31 18:14:05 +0000198 else
199 return AssemblerDialect;
200 }
201 virtual void setAssemblerDialect(unsigned i) {
202 AssemblerDialect = i;
203 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000204
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000205 virtual bool Warning(SMLoc L, const Twine &Msg,
206 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
207 virtual bool Error(SMLoc L, const Twine &Msg,
208 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000209
Craig Topper345d16d2012-08-29 05:48:09 +0000210 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000211
Chad Rosier84125ca2012-10-13 00:26:04 +0000212 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosierc5ac87d2012-10-16 20:16:20 +0000213 bool isParsingInlineAsm() { return ParsingInlineAsm; }
Chad Rosierb1f8c132012-10-18 15:49:34 +0000214
215 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
216 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +0000217 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000218 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000219 SmallVectorImpl<std::string> &Clobbers,
220 const MCInstrInfo *MII,
221 const MCInstPrinter *IP,
222 MCAsmParserSemaCallback &SI);
Chad Rosier84125ca2012-10-13 00:26:04 +0000223
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000224 bool ParseExpression(const MCExpr *&Res);
225 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
226 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
227 virtual bool ParseAbsoluteExpression(int64_t &Res);
228
229 /// }
230
231private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000232 void CheckForValidSection();
233
Eli Friedman2128aae2012-10-22 23:58:19 +0000234 bool ParseStatement(ParseStatementInfo &Info);
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000235 void EatToEndOfLine();
236 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000237
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000238 bool HandleMacroEntry(StringRef Name, SMLoc NameLoc, const Macro *M);
Rafael Espindola761cb062012-06-03 23:57:14 +0000239 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +0000240 const MacroParameters &Parameters,
241 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000242 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000243 void HandleMacroExit();
244
245 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000246 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000247 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
248 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000249 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000250 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000251
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000252 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
253 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000254 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
255 /// This returns true on failure.
256 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000257
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000258 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000259 /// current token is not set; clients should ensure Lex() is called
260 /// subsequently.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000261 ///
262 /// \param InBuffer If not -1, should be the known buffer id that contains the
263 /// location.
264 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000265
Craig Topper345d16d2012-08-29 05:48:09 +0000266 virtual void EatToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000267
Preston Gurd7b6f2032012-09-19 20:36:12 +0000268 bool ParseMacroArgument(MacroArgument &MA,
269 AsmToken::TokenKind &ArgumentDelimiter);
Rafael Espindola8a403d32012-08-08 14:51:03 +0000270 bool ParseMacroArguments(const Macro *M, MacroArguments &A);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000271
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000272 /// \brief Parse up to the end of statement and a return the contents from the
273 /// current token until the end of the statement; the current token on exit
274 /// will be either the EndOfStatement or EOF.
Craig Topper345d16d2012-08-29 05:48:09 +0000275 virtual StringRef ParseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000276
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000277 /// \brief Parse until the end of a statement or a comma is encountered,
278 /// return the contents from the current token up to the end or comma.
279 StringRef ParseStringToComma();
280
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000281 bool ParseAssignment(StringRef Name, bool allow_redef,
282 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000283
284 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
285 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
286 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000287 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000288
289 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000290 /// and set \p Res to the identifier contents.
Craig Topper345d16d2012-08-29 05:48:09 +0000291 virtual bool ParseIdentifier(StringRef &Res);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000292
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000293 // Directive Parsing.
Rafael Espindola787c3372010-10-28 20:02:27 +0000294
Eli Bendersky14b8f792012-12-17 22:50:56 +0000295 // ".ascii", ".asciiz", ".string"
Rafael Espindola787c3372010-10-28 20:02:27 +0000296 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000297 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000298 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000299 bool ParseDirectiveFill(); // ".fill"
300 bool ParseDirectiveSpace(); // ".space"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000301 bool ParseDirectiveZero(); // ".zero"
Eric Christopher2318ba12012-12-18 00:30:54 +0000302 // ".set", ".equ", ".equiv"
303 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000304 bool ParseDirectiveOrg(); // ".org"
305 // ".align{,32}", ".p2align{,w,l}"
306 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
307
308 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
309 /// accepts a single symbol (which should be a label or an external).
310 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000311
312 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
313
314 bool ParseDirectiveAbort(); // ".abort"
315 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000316 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000317
318 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000319 // ".ifb" or ".ifnb", depending on ExpectBlank.
320 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000321 // ".ifc" or ".ifnc", depending on ExpectEqual.
322 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000323 // ".ifdef" or ".ifndef", depending on expect_defined
324 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000325 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
326 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
327 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
328
329 /// ParseEscapedString - Parse the current token as a string which may include
330 /// escaped characters and return the string contents.
331 bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000332
333 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
334 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000335
Rafael Espindola761cb062012-06-03 23:57:14 +0000336 // Macro-like directives
337 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
338 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
339 raw_svector_ostream &OS);
340 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000341 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000342 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000343 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000344
Eli Friedman2128aae2012-10-22 23:58:19 +0000345 // "_emit"
346 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000347};
348
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000349/// \brief Generic implementations of directive handling, etc. which is shared
350/// (or the default, at least) for all assembler parser.
351class GenericAsmParser : public MCAsmParserExtension {
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000352 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
353 void AddDirectiveHandler(StringRef Directive) {
354 getParser().AddDirectiveHandler(this, Directive,
355 HandleDirective<GenericAsmParser, Handler>);
356 }
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000357public:
358 GenericAsmParser() {}
359
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000360 AsmParser &getParser() {
361 return (AsmParser&) this->MCAsmParserExtension::getParser();
362 }
363
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000364 virtual void Initialize(MCAsmParser &Parser) {
365 // Call the base implementation.
366 this->MCAsmParserExtension::Initialize(Parser);
367
368 // Debugging directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000369 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
370 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
371 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
Daniel Dunbar138abae2010-10-16 04:56:42 +0000372 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000373
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000374 // CFI directives.
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000375 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
376 ".cfi_sections");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000377 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
378 ".cfi_startproc");
379 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
380 ".cfi_endproc");
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000381 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
382 ".cfi_def_cfa");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000383 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
384 ".cfi_def_cfa_offset");
Rafael Espindola53abbe52011-04-11 20:29:16 +0000385 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
386 ".cfi_adjust_cfa_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000387 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
388 ".cfi_def_cfa_register");
389 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
390 ".cfi_offset");
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000391 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
392 ".cfi_rel_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000393 AddDirectiveHandler<
394 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
395 AddDirectiveHandler<
396 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
Rafael Espindolafe024d02010-12-28 18:36:23 +0000397 AddDirectiveHandler<
398 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
399 AddDirectiveHandler<
400 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
Rafael Espindolac5754392011-04-12 15:31:05 +0000401 AddDirectiveHandler<
402 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000403 AddDirectiveHandler<
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000404 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
405 AddDirectiveHandler<
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000406 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
Rafael Espindola16d7d432012-01-23 21:51:52 +0000407 AddDirectiveHandler<
408 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
Rafael Espindolac8fec7e2012-11-23 16:59:41 +0000409 AddDirectiveHandler<
410 &GenericAsmParser::ParseDirectiveCFIUndefined>(".cfi_undefined");
Rafael Espindolaf4f14f62012-11-25 15:14:49 +0000411 AddDirectiveHandler<
412 &GenericAsmParser::ParseDirectiveCFIRegister>(".cfi_register");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000413
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000414 // Macro directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000415 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
416 ".macros_on");
417 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
418 ".macros_off");
419 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
420 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
421 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000422 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000423
424 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
425 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000426 }
427
Roman Divacky54b0f4f2011-01-27 17:16:37 +0000428 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
429
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000430 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
431 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
432 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar138abae2010-10-16 04:56:42 +0000433 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000434 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000435 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
436 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000437 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000438 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola53abbe52011-04-11 20:29:16 +0000439 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000440 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
441 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000442 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000443 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
Rafael Espindolafe024d02010-12-28 18:36:23 +0000444 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
445 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac5754392011-04-12 15:31:05 +0000446 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000447 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000448 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
Rafael Espindola16d7d432012-01-23 21:51:52 +0000449 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac8fec7e2012-11-23 16:59:41 +0000450 bool ParseDirectiveCFIUndefined(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf4f14f62012-11-25 15:14:49 +0000451 bool ParseDirectiveCFIRegister(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000452
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000453 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000454 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
455 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000456 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000457
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000458 bool ParseDirectiveLEB128(StringRef, SMLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000459};
460
461}
462
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000463namespace llvm {
464
465extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000466extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000467extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000468
469}
470
Chris Lattneraaec2052010-01-19 19:46:13 +0000471enum { DEFAULT_ADDRSPACE = 0 };
472
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000473AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000474 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000475 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Rafael Espindola5d7dcd32011-04-12 18:53:30 +0000476 GenericParser(new GenericAsmParser), PlatformParser(0),
Preston Gurd7b6f2032012-09-19 20:36:12 +0000477 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000478 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000479 // Save the old handler.
480 SavedDiagHandler = SrcMgr.getDiagHandler();
481 SavedDiagContext = SrcMgr.getDiagContext();
482 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000483 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000484 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000485
486 // Initialize the generic parser.
487 GenericParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000488
489 // Initialize the platform / file format parser.
490 //
491 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
492 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000493 if (_MAI.hasMicrosoftFastStdCallMangling()) {
494 PlatformParser = createCOFFAsmParser();
495 PlatformParser->Initialize(*this);
496 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000497 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000498 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000499 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000500 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000501 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000502 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000503 }
Chris Lattnerebb89b42009-09-27 21:16:52 +0000504}
505
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000506AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000507 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
508
509 // Destroy any macros.
510 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
511 ie = MacroMap.end(); it != ie; ++it)
512 delete it->getValue();
513
Daniel Dunbare4749702010-07-12 18:12:02 +0000514 delete PlatformParser;
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000515 delete GenericParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000516}
517
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000518void AsmParser::PrintMacroInstantiations() {
519 // Print the active macro instantiation stack.
520 for (std::vector<MacroInstantiation*>::const_reverse_iterator
521 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000522 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
523 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000524}
525
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000526bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000527 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000528 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000529 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000530 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000531 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000532}
533
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000534bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000535 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000536 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000537 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000538 return true;
539}
540
Sean Callananfd0b0282010-01-21 00:19:58 +0000541bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000542 std::string IncludedFile;
543 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000544 if (NewBuf == -1)
545 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000546
Sean Callananfd0b0282010-01-21 00:19:58 +0000547 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000548
Sean Callananfd0b0282010-01-21 00:19:58 +0000549 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000550
Sean Callananfd0b0282010-01-21 00:19:58 +0000551 return false;
552}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000553
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000554/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000555/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000556/// returns true on failure.
557bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
558 std::string IncludedFile;
559 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
560 if (NewBuf == -1)
561 return true;
562
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000563 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000564 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
565 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000566 return false;
567}
568
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000569void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
570 if (InBuffer != -1) {
571 CurBuffer = InBuffer;
572 } else {
573 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
574 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000575 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
576}
577
Sean Callananfd0b0282010-01-21 00:19:58 +0000578const AsmToken &AsmParser::Lex() {
579 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000580
Sean Callananfd0b0282010-01-21 00:19:58 +0000581 if (tok->is(AsmToken::Eof)) {
582 // If this is the end of an included file, pop the parent file off the
583 // include stack.
584 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
585 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000586 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000587 tok = &Lexer.Lex();
588 }
589 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000590
Sean Callananfd0b0282010-01-21 00:19:58 +0000591 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000592 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000593
Sean Callananfd0b0282010-01-21 00:19:58 +0000594 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000595}
596
Chris Lattner79180e22010-04-05 23:15:42 +0000597bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000598 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000599 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000600 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000601
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000602 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000603 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000604
605 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000606 AsmCond StartingCondState = TheCondState;
607
Kevin Enderby613b7572011-11-01 22:27:22 +0000608 // If we are generating dwarf for assembly source files save the initial text
609 // section and generate a .file directive.
610 if (getContext().getGenDwarfForAssembly()) {
611 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000612 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
613 getStreamer().EmitLabel(SectionStartSym);
614 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000615 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
616 StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier());
617 }
618
Chris Lattnerb717fb02009-07-02 21:53:43 +0000619 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000620 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000621 ParseStatementInfo Info;
622 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000623
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000624 // We had an error, validate that one was emitted and recover by skipping to
625 // the next line.
626 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000627 EatToEndOfStatement();
628 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000629
630 if (TheCondState.TheCond != StartingCondState.TheCond ||
631 TheCondState.Ignore != StartingCondState.Ignore)
632 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000633
634 // Check to see there are no empty DwarfFile slots.
635 const std::vector<MCDwarfFile *> &MCDwarfFiles =
636 getContext().getMCDwarfFiles();
637 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000638 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000639 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000640 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000641
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000642 // Check to see that all assembler local symbols were actually defined.
643 // Targets that don't do subsections via symbols may not want this, though,
644 // so conservatively exclude them. Only do this if we're finalizing, though,
645 // as otherwise we won't necessarilly have seen everything yet.
646 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
647 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
648 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
649 e = Symbols.end();
650 i != e; ++i) {
651 MCSymbol *Sym = i->getValue();
652 // Variable symbols may not be marked as defined, so check those
653 // explicitly. If we know it's a variable, we have a definition for
654 // the purposes of this check.
655 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
656 // FIXME: We would really like to refer back to where the symbol was
657 // first referenced for a source location. We need to add something
658 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000659 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
660 "assembler local symbol '" + Sym->getName() +
661 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000662 }
663 }
664
665
Chris Lattner79180e22010-04-05 23:15:42 +0000666 // Finalize the output stream if there are no errors and if the client wants
667 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000668 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000669 Out.Finish();
670
Chris Lattnerb717fb02009-07-02 21:53:43 +0000671 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000672}
673
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000674void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000675 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000676 TokError("expected section directive before assembly directive");
677 Out.SwitchSection(Ctx.getMachOSection(
678 "__TEXT", "__text",
679 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
680 0, SectionKind::getText()));
681 }
682}
683
Chris Lattner2cf5f142009-06-22 01:29:09 +0000684/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
685void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000686 while (Lexer.isNot(AsmToken::EndOfStatement) &&
687 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000688 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000689
Chris Lattner2cf5f142009-06-22 01:29:09 +0000690 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000691 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000692 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000693}
694
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000695StringRef AsmParser::ParseStringToEndOfStatement() {
696 const char *Start = getTok().getLoc().getPointer();
697
698 while (Lexer.isNot(AsmToken::EndOfStatement) &&
699 Lexer.isNot(AsmToken::Eof))
700 Lex();
701
702 const char *End = getTok().getLoc().getPointer();
703 return StringRef(Start, End - Start);
704}
Chris Lattnerc4193832009-06-22 05:51:26 +0000705
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000706StringRef AsmParser::ParseStringToComma() {
707 const char *Start = getTok().getLoc().getPointer();
708
709 while (Lexer.isNot(AsmToken::EndOfStatement) &&
710 Lexer.isNot(AsmToken::Comma) &&
711 Lexer.isNot(AsmToken::Eof))
712 Lex();
713
714 const char *End = getTok().getLoc().getPointer();
715 return StringRef(Start, End - Start);
716}
717
Chris Lattner74ec1a32009-06-22 06:32:03 +0000718/// ParseParenExpr - Parse a paren expression and return it.
719/// NOTE: This assumes the leading '(' has already been consumed.
720///
721/// parenexpr ::= expr)
722///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000723bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000724 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000725 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000726 return TokError("expected ')' in parentheses expression");
Chris Lattnerb4307b32010-01-15 19:28:38 +0000727 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000728 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000729 return false;
730}
Chris Lattnerc4193832009-06-22 05:51:26 +0000731
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000732/// ParseBracketExpr - Parse a bracket expression and return it.
733/// NOTE: This assumes the leading '[' has already been consumed.
734///
735/// bracketexpr ::= expr]
736///
737bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
738 if (ParseExpression(Res)) return true;
739 if (Lexer.isNot(AsmToken::RBrac))
740 return TokError("expected ']' in brackets expression");
741 EndLoc = Lexer.getLoc();
742 Lex();
743 return false;
744}
745
Chris Lattner74ec1a32009-06-22 06:32:03 +0000746/// ParsePrimaryExpr - Parse a primary expression and return it.
747/// primaryexpr ::= (parenexpr
748/// primaryexpr ::= symbol
749/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000750/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000751/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000752bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000753 switch (Lexer.getKind()) {
754 default:
755 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000756 // If we have an error assume that we've already handled it.
757 case AsmToken::Error:
758 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000759 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000760 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000761 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000762 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000763 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000764 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000765 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000766 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000767 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000768 EndLoc = Lexer.getLoc();
769
770 StringRef Identifier;
771 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000772 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000773
Daniel Dunbarfffff912009-10-16 01:34:54 +0000774 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000775 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000776 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000777
778 // Lookup the symbol variant if used.
779 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000780 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000781 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000782 if (Variant == MCSymbolRefExpr::VK_Invalid) {
783 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000784 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000785 }
786 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000787
Daniel Dunbarfffff912009-10-16 01:34:54 +0000788 // If this is an absolute variable reference, substitute it now to preserve
789 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000790 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000791 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000792 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000793
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000794 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000795 return false;
796 }
797
798 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000799 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000800 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000801 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000802 case AsmToken::Integer: {
803 SMLoc Loc = getTok().getLoc();
804 int64_t IntVal = getTok().getIntVal();
805 Res = MCConstantExpr::Create(IntVal, getContext());
Chris Lattnerb4307b32010-01-15 19:28:38 +0000806 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000807 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000808 // Look for 'b' or 'f' following an Integer as a directional label
809 if (Lexer.getKind() == AsmToken::Identifier) {
810 StringRef IDVal = getTok().getString();
811 if (IDVal == "f" || IDVal == "b"){
812 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
813 IDVal == "f" ? 1 : 0);
814 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
815 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000816 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000817 return Error(Loc, "invalid reference to undefined symbol");
818 EndLoc = Lexer.getLoc();
819 Lex(); // Eat identifier.
820 }
821 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000822 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000823 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000824 case AsmToken::Real: {
825 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000826 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000827 Res = MCConstantExpr::Create(IntVal, getContext());
828 Lex(); // Eat token.
829 return false;
830 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000831 case AsmToken::Dot: {
832 // This is a '.' reference, which references the current PC. Emit a
833 // temporary label to the streamer and refer to it.
834 MCSymbol *Sym = Ctx.CreateTempSymbol();
835 Out.EmitLabel(Sym);
836 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
837 EndLoc = Lexer.getLoc();
838 Lex(); // Eat identifier.
839 return false;
840 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000841 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000842 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000843 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000844 case AsmToken::LBrac:
845 if (!PlatformParser->HasBracketExpressions())
846 return TokError("brackets expression not supported on this target");
847 Lex(); // Eat the '['.
848 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000849 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000850 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000851 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000852 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000853 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000854 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000855 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000856 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000857 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000858 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000859 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000860 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000861 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000862 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000863 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000864 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000865 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000866 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000867 }
868}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000869
Chris Lattnerb4307b32010-01-15 19:28:38 +0000870bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000871 SMLoc EndLoc;
872 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000873}
874
Daniel Dunbarcceba832010-09-17 02:47:07 +0000875const MCExpr *
876AsmParser::ApplyModifierToExpr(const MCExpr *E,
877 MCSymbolRefExpr::VariantKind Variant) {
878 // Recurse over the given expression, rebuilding it to apply the given variant
879 // if there is exactly one symbol.
880 switch (E->getKind()) {
881 case MCExpr::Target:
882 case MCExpr::Constant:
883 return 0;
884
885 case MCExpr::SymbolRef: {
886 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
887
888 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
889 TokError("invalid variant on expression '" +
890 getTok().getIdentifier() + "' (already modified)");
891 return E;
892 }
893
894 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
895 }
896
897 case MCExpr::Unary: {
898 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
899 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
900 if (!Sub)
901 return 0;
902 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
903 }
904
905 case MCExpr::Binary: {
906 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
907 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
908 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
909
910 if (!LHS && !RHS)
911 return 0;
912
913 if (!LHS) LHS = BE->getLHS();
914 if (!RHS) RHS = BE->getRHS();
915
916 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
917 }
918 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000919
Craig Topper85814382012-02-07 05:05:23 +0000920 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000921}
922
Chris Lattner74ec1a32009-06-22 06:32:03 +0000923/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000924///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000925/// expr ::= expr &&,|| expr -> lowest.
926/// expr ::= expr |,^,&,! expr
927/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
928/// expr ::= expr <<,>> expr
929/// expr ::= expr +,- expr
930/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000931/// expr ::= primaryexpr
932///
Chris Lattner54482b42010-01-15 19:39:23 +0000933bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000934 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000935 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000936 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
937 return true;
938
Daniel Dunbarcceba832010-09-17 02:47:07 +0000939 // As a special case, we support 'a op b @ modifier' by rewriting the
940 // expression to include the modifier. This is inefficient, but in general we
941 // expect users to use 'a@modifier op b'.
942 if (Lexer.getKind() == AsmToken::At) {
943 Lex();
944
945 if (Lexer.isNot(AsmToken::Identifier))
946 return TokError("unexpected symbol modifier following '@'");
947
948 MCSymbolRefExpr::VariantKind Variant =
949 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
950 if (Variant == MCSymbolRefExpr::VK_Invalid)
951 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
952
953 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
954 if (!ModifiedRes) {
955 return TokError("invalid modifier '" + getTok().getIdentifier() +
956 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000957 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000958
Daniel Dunbarcceba832010-09-17 02:47:07 +0000959 Res = ModifiedRes;
960 Lex();
961 }
962
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000963 // Try to constant fold it up front, if possible.
964 int64_t Value;
965 if (Res->EvaluateAsAbsolute(Value))
966 Res = MCConstantExpr::Create(Value, getContext());
967
968 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000969}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000970
Chris Lattnerb4307b32010-01-15 19:28:38 +0000971bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000972 Res = 0;
973 return ParseParenExpr(Res, EndLoc) ||
974 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000975}
976
Daniel Dunbar475839e2009-06-29 20:37:27 +0000977bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000978 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000979
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000980 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000981 if (ParseExpression(Expr))
982 return true;
983
Daniel Dunbare00b0112009-10-16 01:57:52 +0000984 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000985 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000986
987 return false;
988}
989
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000990static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000991 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000992 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000993 default:
994 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000995
Jim Grosbachfbe16812011-08-20 16:24:13 +0000996 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000997 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000998 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000999 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001000 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001001 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001002 return 1;
1003
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001004
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001005 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +00001006 //
1007 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +00001008 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001009 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001010 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001011 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001012 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001013 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001014 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001015 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001016 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001017
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001018 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001019 case AsmToken::EqualEqual:
1020 Kind = MCBinaryExpr::EQ;
1021 return 3;
1022 case AsmToken::ExclaimEqual:
1023 case AsmToken::LessGreater:
1024 Kind = MCBinaryExpr::NE;
1025 return 3;
1026 case AsmToken::Less:
1027 Kind = MCBinaryExpr::LT;
1028 return 3;
1029 case AsmToken::LessEqual:
1030 Kind = MCBinaryExpr::LTE;
1031 return 3;
1032 case AsmToken::Greater:
1033 Kind = MCBinaryExpr::GT;
1034 return 3;
1035 case AsmToken::GreaterEqual:
1036 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001037 return 3;
1038
Jim Grosbachfbe16812011-08-20 16:24:13 +00001039 // Intermediate Precedence: <<, >>
1040 case AsmToken::LessLess:
1041 Kind = MCBinaryExpr::Shl;
1042 return 4;
1043 case AsmToken::GreaterGreater:
1044 Kind = MCBinaryExpr::Shr;
1045 return 4;
1046
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001047 // High Intermediate Precedence: +, -
1048 case AsmToken::Plus:
1049 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001050 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001051 case AsmToken::Minus:
1052 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001053 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001054
Jim Grosbachfbe16812011-08-20 16:24:13 +00001055 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001056 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001057 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001058 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001059 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001060 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001061 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001062 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001063 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001064 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001065 }
1066}
1067
1068
1069/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1070/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001071bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1072 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001073 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001074 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001075 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001076
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001077 // If the next token is lower precedence than we are allowed to eat, return
1078 // successfully with what we ate already.
1079 if (TokPrec < Precedence)
1080 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001081
Sean Callanan79ed1a82010-01-19 20:22:31 +00001082 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001083
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001084 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001085 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001086 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001087
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001088 // If BinOp binds less tightly with RHS than the operator after RHS, let
1089 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001090 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001091 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001092 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001093 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001094 }
1095
Daniel Dunbar475839e2009-06-29 20:37:27 +00001096 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001097 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001098 }
1099}
1100
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001101/// ParseStatement:
1102/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001103/// ::= Label* Directive ...Operands... EndOfStatement
1104/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001105bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001106 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001107 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001108 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001109 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001110 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001111
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001112 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001113 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001114 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001115 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001116 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001117 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001118 if (Lexer.is(AsmToken::Hash))
1119 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001120
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001121 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001122 if (Lexer.is(AsmToken::Integer)) {
1123 LocalLabelVal = getTok().getIntVal();
1124 if (LocalLabelVal < 0) {
1125 if (!TheCondState.Ignore)
1126 return TokError("unexpected token at start of statement");
1127 IDVal = "";
1128 }
1129 else {
1130 IDVal = getTok().getString();
1131 Lex(); // Consume the integer token to be used as an identifier token.
1132 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001133 if (!TheCondState.Ignore)
1134 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001135 }
1136 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001137
1138 } else if (Lexer.is(AsmToken::Dot)) {
1139 // Treat '.' as a valid identifier in this context.
1140 Lex();
1141 IDVal = ".";
1142
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001143 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001144 if (!TheCondState.Ignore)
1145 return TokError("unexpected token at start of statement");
1146 IDVal = "";
1147 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001148
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001149
Chris Lattner7834fac2010-04-17 18:14:27 +00001150 // Handle conditional assembly here before checking for skipping. We
1151 // have to do this so that .endif isn't skipped in a ".if 0" block for
1152 // example.
1153 if (IDVal == ".if")
1154 return ParseDirectiveIf(IDLoc);
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00001155 if (IDVal == ".ifb")
1156 return ParseDirectiveIfb(IDLoc, true);
1157 if (IDVal == ".ifnb")
1158 return ParseDirectiveIfb(IDLoc, false);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00001159 if (IDVal == ".ifc")
1160 return ParseDirectiveIfc(IDLoc, true);
1161 if (IDVal == ".ifnc")
1162 return ParseDirectiveIfc(IDLoc, false);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00001163 if (IDVal == ".ifdef")
1164 return ParseDirectiveIfdef(IDLoc, true);
1165 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1166 return ParseDirectiveIfdef(IDLoc, false);
Chris Lattner7834fac2010-04-17 18:14:27 +00001167 if (IDVal == ".elseif")
1168 return ParseDirectiveElseIf(IDLoc);
1169 if (IDVal == ".else")
1170 return ParseDirectiveElse(IDLoc);
1171 if (IDVal == ".endif")
1172 return ParseDirectiveEndIf(IDLoc);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001173
Chris Lattner7834fac2010-04-17 18:14:27 +00001174 // If we are in a ".if 0" block, ignore this statement.
Chad Rosier17feeec2012-10-20 00:47:08 +00001175 if (TheCondState.Ignore) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001176 EatToEndOfStatement();
1177 return false;
1178 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001179
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001180 // FIXME: Recurse on local labels?
1181
1182 // See what kind of statement we have.
1183 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001184 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001185 CheckForValidSection();
1186
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001187 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001188 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001189
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001190 // Diagnose attempt to use '.' as a label.
1191 if (IDVal == ".")
1192 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1193
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001194 // Diagnose attempt to use a variable as a label.
1195 //
1196 // FIXME: Diagnostics. Note the location of the definition as a label.
1197 // FIXME: This doesn't diagnose assignment to a symbol which has been
1198 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001199 MCSymbol *Sym;
1200 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001201 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001202 else
1203 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001204 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001205 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001206
Daniel Dunbar959fd882009-08-26 22:13:22 +00001207 // Emit the label.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001208 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001209
Kevin Enderby94c2e852011-12-09 18:09:40 +00001210 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001211 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001212 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001213 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1214 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001215
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001216 // Consume any end of statement token, if present, to avoid spurious
1217 // AddBlankLine calls().
1218 if (Lexer.is(AsmToken::EndOfStatement)) {
1219 Lex();
1220 if (Lexer.is(AsmToken::Eof))
1221 return false;
1222 }
1223
Eli Friedman2128aae2012-10-22 23:58:19 +00001224 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001225 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001226
Daniel Dunbar3f872332009-07-28 16:08:33 +00001227 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001228 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001229 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001230
Nico Weber4c4c7322011-01-28 03:04:41 +00001231 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001232
1233 default: // Normal instruction or directive.
1234 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001235 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001236
1237 // If macros are enabled, check to see if this is a macro instantiation.
1238 if (MacrosEnabled)
1239 if (const Macro *M = MacroMap.lookup(IDVal))
1240 return HandleMacroEntry(IDVal, IDLoc, M);
1241
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001242 // Otherwise, we have a normal instruction or directive.
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001243 if (IDVal[0] == '.' && IDVal != ".") {
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001244
1245 // Target hook for parsing target specific directives.
1246 if (!getTargetParser().ParseDirective(ID))
1247 return false;
1248
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001249 // Assembler features
Roman Divacky50e7a782010-10-28 16:22:58 +00001250 if (IDVal == ".set" || IDVal == ".equ")
Nico Weber4c4c7322011-01-28 03:04:41 +00001251 return ParseDirectiveSet(IDVal, true);
1252 if (IDVal == ".equiv")
1253 return ParseDirectiveSet(IDVal, false);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001254
Daniel Dunbara0d14262009-06-24 23:30:00 +00001255 // Data directives
1256
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001257 if (IDVal == ".ascii")
Rafael Espindola787c3372010-10-28 20:02:27 +00001258 return ParseDirectiveAscii(IDVal, false);
1259 if (IDVal == ".asciz" || IDVal == ".string")
1260 return ParseDirectiveAscii(IDVal, true);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001261
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001262 if (IDVal == ".byte")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001263 return ParseDirectiveValue(1);
Kevin Enderby9c656452009-09-10 20:51:44 +00001264 if (IDVal == ".short")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001265 return ParseDirectiveValue(2);
Rafael Espindolacc3acee2010-11-01 15:29:07 +00001266 if (IDVal == ".value")
1267 return ParseDirectiveValue(2);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001268 if (IDVal == ".2byte")
1269 return ParseDirectiveValue(2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001270 if (IDVal == ".long")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001271 return ParseDirectiveValue(4);
Rafael Espindola435279b2010-11-17 16:24:40 +00001272 if (IDVal == ".int")
1273 return ParseDirectiveValue(4);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001274 if (IDVal == ".4byte")
1275 return ParseDirectiveValue(4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001276 if (IDVal == ".quad")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001277 return ParseDirectiveValue(8);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001278 if (IDVal == ".8byte")
1279 return ParseDirectiveValue(8);
Roman Divacky14e66552011-01-28 14:20:32 +00001280 if (IDVal == ".single" || IDVal == ".float")
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001281 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1282 if (IDVal == ".double")
1283 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001284
Eli Friedman5d68ec22010-07-19 04:17:25 +00001285 if (IDVal == ".align") {
1286 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1287 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1288 }
1289 if (IDVal == ".align32") {
1290 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1291 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1292 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001293 if (IDVal == ".balign")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001294 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001295 if (IDVal == ".balignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001296 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001297 if (IDVal == ".balignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001298 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001299 if (IDVal == ".p2align")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001300 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001301 if (IDVal == ".p2alignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001302 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001303 if (IDVal == ".p2alignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001304 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1305
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001306 if (IDVal == ".org")
Daniel Dunbarc238b582009-06-25 22:44:51 +00001307 return ParseDirectiveOrg();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001308
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001309 if (IDVal == ".fill")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001310 return ParseDirectiveFill();
Rafael Espindolace8463f2011-04-07 20:26:23 +00001311 if (IDVal == ".space" || IDVal == ".skip")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001312 return ParseDirectiveSpace();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001313 if (IDVal == ".zero")
1314 return ParseDirectiveZero();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001315
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001316 // Symbol attribute directives
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001317
Benjamin Kramere14a3c52012-05-12 11:18:59 +00001318 if (IDVal == ".extern") {
1319 EatToEndOfStatement(); // .extern is the default, ignore it.
1320 return false;
1321 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001322 if (IDVal == ".globl" || IDVal == ".global")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001323 return ParseDirectiveSymbolAttribute(MCSA_Global);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001324 if (IDVal == ".indirect_symbol")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001325 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001326 if (IDVal == ".lazy_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001327 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001328 if (IDVal == ".no_dead_strip")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001329 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Kevin Enderbye8e98d72010-11-19 18:39:33 +00001330 if (IDVal == ".symbol_resolver")
1331 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001332 if (IDVal == ".private_extern")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001333 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001334 if (IDVal == ".reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001335 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001336 if (IDVal == ".weak_definition")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001337 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001338 if (IDVal == ".weak_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001339 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Kevin Enderbyf59cac52010-07-08 17:22:42 +00001340 if (IDVal == ".weak_def_can_be_hidden")
1341 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001342
Hans Wennborg5cc64912011-06-18 13:51:54 +00001343 if (IDVal == ".comm" || IDVal == ".common")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001344 return ParseDirectiveComm(/*IsLocal=*/false);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001345 if (IDVal == ".lcomm")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001346 return ParseDirectiveComm(/*IsLocal=*/true);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001347
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001348 if (IDVal == ".abort")
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001349 return ParseDirectiveAbort();
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001350 if (IDVal == ".include")
Kevin Enderby1f049b22009-07-14 23:21:55 +00001351 return ParseDirectiveInclude();
Kevin Enderbyc55acca2011-12-14 21:47:48 +00001352 if (IDVal == ".incbin")
1353 return ParseDirectiveIncbin();
Kevin Enderbya5c78322009-07-13 21:03:15 +00001354
Benjamin Kramer5cdf0ad2012-05-12 11:19:04 +00001355 if (IDVal == ".code16" || IDVal == ".code16gcc")
Roman Divackyf6fbd842011-01-31 20:56:49 +00001356 return TokError(Twine(IDVal) + " not supported yet");
Roman Divackycb727802011-01-28 19:29:48 +00001357
Rafael Espindola761cb062012-06-03 23:57:14 +00001358 // Macro-like directives
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001359 if (IDVal == ".rept")
1360 return ParseDirectiveRept(IDLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001361 if (IDVal == ".irp")
1362 return ParseDirectiveIrp(IDLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00001363 if (IDVal == ".irpc")
1364 return ParseDirectiveIrpc(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001365 if (IDVal == ".endr")
Rafael Espindola761cb062012-06-03 23:57:14 +00001366 return ParseDirectiveEndr(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001367
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001368 // Look up the handler in the handler table.
1369 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1370 DirectiveMap.lookup(IDVal);
1371 if (Handler.first)
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +00001372 return (*Handler.second)(Handler.first, IDVal, IDLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001373
Kevin Enderby9c656452009-09-10 20:51:44 +00001374
Jim Grosbach686c0182012-05-01 18:38:27 +00001375 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001376 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001377
Eli Friedman2128aae2012-10-22 23:58:19 +00001378 // _emit
1379 if (ParsingInlineAsm && IDVal == "_emit")
1380 return ParseDirectiveEmit(IDLoc, Info);
1381
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001382 CheckForValidSection();
1383
Chris Lattnera7f13542010-05-19 23:34:33 +00001384 // Canonicalize the opcode to lower case.
Chad Rosier8f138d12012-10-15 17:19:13 +00001385 SmallString<128> OpcodeStr;
Chris Lattnera7f13542010-05-19 23:34:33 +00001386 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
Chad Rosier8f138d12012-10-15 17:19:13 +00001387 OpcodeStr.push_back(tolower(IDVal[i]));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001388
Chad Rosier6a020a72012-10-25 20:41:34 +00001389 ParseInstructionInfo IInfo(Info.AsmRewrites);
1390 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1391 IDLoc,Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001392 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001393
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001394 // Dump the parsed representation, if requested.
1395 if (getShowParsedOperands()) {
1396 SmallString<256> Str;
1397 raw_svector_ostream OS(Str);
1398 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001399 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001400 if (i != 0)
1401 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001402 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001403 }
1404 OS << "]";
1405
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001406 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001407 }
1408
Kevin Enderby613b7572011-11-01 22:27:22 +00001409 // If we are generating dwarf for assembly source files and the current
1410 // section is the initial text section then generate a .loc directive for
1411 // the instruction.
1412 if (!HadError && getContext().getGenDwarfForAssembly() &&
Eric Christopher2318ba12012-12-18 00:30:54 +00001413 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001414
1415 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1416
1417 // If we previously parsed a cpp hash file line comment then make sure the
1418 // current Dwarf File is for the CppHashFilename if not then emit the
1419 // Dwarf File table for it and adjust the line number for the .loc.
1420 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1421 getContext().getMCDwarfFiles();
1422 if (CppHashFilename.size() != 0) {
1423 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1424 CppHashFilename)
Eric Christopher2318ba12012-12-18 00:30:54 +00001425 getStreamer().EmitDwarfFileDirective(
1426 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001427
Kevin Enderby32c1a822012-11-05 21:55:41 +00001428 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
Kevin Enderby938482f2012-11-01 17:31:35 +00001429 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1430 }
1431
Kevin Enderby613b7572011-11-01 22:27:22 +00001432 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001433 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001434 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001435 StringRef());
1436 }
1437
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001438 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001439 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001440 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001441 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1442 Info.ParsedOperands,
1443 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001444 ParsingInlineAsm);
1445 }
Chris Lattner98986712010-01-14 22:21:20 +00001446
Chris Lattnercbf8a982010-09-11 16:18:25 +00001447 // Don't skip the rest of the line, the instruction parser is responsible for
1448 // that.
1449 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001450}
Chris Lattner9a023f72009-06-24 04:43:34 +00001451
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001452/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1453/// since they may not be able to be tokenized to get to the end of line token.
1454void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001455 if (!Lexer.is(AsmToken::EndOfStatement))
1456 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001457 // Eat EOL.
1458 Lex();
1459}
1460
1461/// ParseCppHashLineFilenameComment as this:
1462/// ::= # number "filename"
1463/// or just as a full line comment if it doesn't have a number and a string.
1464bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1465 Lex(); // Eat the hash token.
1466
1467 if (getLexer().isNot(AsmToken::Integer)) {
1468 // Consume the line since in cases it is not a well-formed line directive,
1469 // as if were simply a full line comment.
1470 EatToEndOfLine();
1471 return false;
1472 }
1473
1474 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001475 Lex();
1476
1477 if (getLexer().isNot(AsmToken::String)) {
1478 EatToEndOfLine();
1479 return false;
1480 }
1481
1482 StringRef Filename = getTok().getString();
1483 // Get rid of the enclosing quotes.
1484 Filename = Filename.substr(1, Filename.size()-2);
1485
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001486 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1487 CppHashLoc = L;
1488 CppHashFilename = Filename;
1489 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001490 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001491
1492 // Ignore any trailing characters, they're just comment.
1493 EatToEndOfLine();
1494 return false;
1495}
1496
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001497/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001498/// for the Filename and LineNo if any in the diagnostic.
1499void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1500 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1501 raw_ostream &OS = errs();
1502
1503 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1504 const SMLoc &DiagLoc = Diag.getLoc();
1505 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1506 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1507
1508 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1509 // before printing the message.
1510 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001511 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001512 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1513 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1514 }
1515
Eric Christopher2318ba12012-12-18 00:30:54 +00001516 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001517 // manager changed or buffer changed (like in a nested include) then just
1518 // print the normal diagnostic using its Filename and LineNo.
1519 if (!Parser->CppHashLineNumber ||
1520 &DiagSrcMgr != &Parser->SrcMgr ||
1521 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001522 if (Parser->SavedDiagHandler)
1523 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1524 else
1525 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001526 return;
1527 }
1528
Eric Christopher2318ba12012-12-18 00:30:54 +00001529 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001530 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1531 // the diagnostic.
1532 const std::string Filename = Parser->CppHashFilename;
1533
1534 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1535 int CppHashLocLineNo =
1536 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1537 int LineNo = Parser->CppHashLineNumber - 1 +
1538 (DiagLocLineNo - CppHashLocLineNo);
1539
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001540 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1541 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001542 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001543 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001544
Benjamin Kramer04a04262011-10-16 10:48:29 +00001545 if (Parser->SavedDiagHandler)
1546 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1547 else
1548 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001549}
1550
Rafael Espindola799aacf2012-08-21 18:29:30 +00001551// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1552// difference being that that function accepts '@' as part of identifiers and
1553// we can't do that. AsmLexer.cpp should probably be changed to handle
1554// '@' as a special case when needed.
1555static bool isIdentifierChar(char c) {
1556 return isalnum(c) || c == '_' || c == '$' || c == '.';
1557}
1558
Rafael Espindola761cb062012-06-03 23:57:14 +00001559bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +00001560 const MacroParameters &Parameters,
1561 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001562 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001563 unsigned NParameters = Parameters.size();
1564 if (NParameters != 0 && NParameters != A.size())
1565 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001566
Preston Gurd7b6f2032012-09-19 20:36:12 +00001567 // A macro without parameters is handled differently on Darwin:
1568 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001569 while (!Body.empty()) {
1570 // Scan for the next substitution.
1571 std::size_t End = Body.size(), Pos = 0;
1572 for (; Pos != End; ++Pos) {
1573 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001574 if (!NParameters) {
1575 // This macro has no parameters, look for $0, $1, etc.
1576 if (Body[Pos] != '$' || Pos + 1 == End)
1577 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001578
Rafael Espindola65366442011-06-05 02:43:45 +00001579 char Next = Body[Pos + 1];
1580 if (Next == '$' || Next == 'n' || isdigit(Next))
1581 break;
1582 } else {
1583 // This macro has parameters, look for \foo, \bar, etc.
1584 if (Body[Pos] == '\\' && Pos + 1 != End)
1585 break;
1586 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001587 }
1588
1589 // Add the prefix.
1590 OS << Body.slice(0, Pos);
1591
1592 // Check if we reached the end.
1593 if (Pos == End)
1594 break;
1595
Rafael Espindola65366442011-06-05 02:43:45 +00001596 if (!NParameters) {
1597 switch (Body[Pos+1]) {
1598 // $$ => $
1599 case '$':
1600 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001601 break;
1602
Rafael Espindola65366442011-06-05 02:43:45 +00001603 // $n => number of arguments
1604 case 'n':
1605 OS << A.size();
1606 break;
1607
1608 // $[0-9] => argument
1609 default: {
1610 // Missing arguments are ignored.
1611 unsigned Index = Body[Pos+1] - '0';
1612 if (Index >= A.size())
1613 break;
1614
1615 // Otherwise substitute with the token values, with spaces eliminated.
Rafael Espindola28c1f6662012-06-03 22:41:23 +00001616 for (MacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001617 ie = A[Index].end(); it != ie; ++it)
1618 OS << it->getString();
1619 break;
1620 }
1621 }
1622 Pos += 2;
1623 } else {
1624 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001625 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001626 ++I;
1627
1628 const char *Begin = Body.data() + Pos +1;
1629 StringRef Argument(Begin, I - (Pos +1));
1630 unsigned Index = 0;
1631 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001632 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001633 break;
1634
Preston Gurd7b6f2032012-09-19 20:36:12 +00001635 if (Index == NParameters) {
1636 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1637 Pos += 3;
1638 else {
1639 OS << '\\' << Argument;
1640 Pos = I;
1641 }
1642 } else {
1643 for (MacroArgument::const_iterator it = A[Index].begin(),
1644 ie = A[Index].end(); it != ie; ++it)
1645 if (it->getKind() == AsmToken::String)
1646 OS << it->getStringContents();
1647 else
1648 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001649
Preston Gurd7b6f2032012-09-19 20:36:12 +00001650 Pos += 1 + Argument.size();
1651 }
Rafael Espindola65366442011-06-05 02:43:45 +00001652 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001653 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001654 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001655 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001656
Rafael Espindola65366442011-06-05 02:43:45 +00001657 return false;
1658}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001659
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001660MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL,
1661 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001662 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001663 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1664 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001665{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001666}
1667
Preston Gurd7b6f2032012-09-19 20:36:12 +00001668static bool IsOperator(AsmToken::TokenKind kind)
1669{
1670 switch (kind)
1671 {
1672 default:
1673 return false;
1674 case AsmToken::Plus:
1675 case AsmToken::Minus:
1676 case AsmToken::Tilde:
1677 case AsmToken::Slash:
1678 case AsmToken::Star:
1679 case AsmToken::Dot:
1680 case AsmToken::Equal:
1681 case AsmToken::EqualEqual:
1682 case AsmToken::Pipe:
1683 case AsmToken::PipePipe:
1684 case AsmToken::Caret:
1685 case AsmToken::Amp:
1686 case AsmToken::AmpAmp:
1687 case AsmToken::Exclaim:
1688 case AsmToken::ExclaimEqual:
1689 case AsmToken::Percent:
1690 case AsmToken::Less:
1691 case AsmToken::LessEqual:
1692 case AsmToken::LessLess:
1693 case AsmToken::LessGreater:
1694 case AsmToken::Greater:
1695 case AsmToken::GreaterEqual:
1696 case AsmToken::GreaterGreater:
1697 return true;
1698 }
1699}
1700
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001701/// ParseMacroArgument - Extract AsmTokens for a macro argument.
1702/// This is used for both default macro parameter values and the
1703/// arguments in macro invocations
Preston Gurd7b6f2032012-09-19 20:36:12 +00001704bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1705 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001706 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001707 unsigned AddTokens = 0;
1708
1709 // gas accepts arguments separated by whitespace, except on Darwin
1710 if (!IsDarwin)
1711 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001712
1713 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001714 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1715 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001716 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001717 }
1718
1719 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1720 // Spaces and commas cannot be mixed to delimit parameters
1721 if (ArgumentDelimiter == AsmToken::Eof)
1722 ArgumentDelimiter = AsmToken::Comma;
1723 else if (ArgumentDelimiter != AsmToken::Comma) {
1724 Lexer.setSkipSpace(true);
1725 return TokError("expected ' ' for macro argument separator");
1726 }
1727 break;
1728 }
1729
1730 if (Lexer.is(AsmToken::Space)) {
1731 Lex(); // Eat spaces
1732
1733 // Spaces can delimit parameters, but could also be part an expression.
1734 // If the token after a space is an operator, add the token and the next
1735 // one into this argument
1736 if (ArgumentDelimiter == AsmToken::Space ||
1737 ArgumentDelimiter == AsmToken::Eof) {
1738 if (IsOperator(Lexer.getKind())) {
1739 // Check to see whether the token is used as an operator,
1740 // or part of an identifier
1741 const char *NextChar = getTok().getEndLoc().getPointer() + 1;
1742 if (*NextChar == ' ')
1743 AddTokens = 2;
1744 }
1745
1746 if (!AddTokens && ParenLevel == 0) {
1747 if (ArgumentDelimiter == AsmToken::Eof &&
1748 !IsOperator(Lexer.getKind()))
1749 ArgumentDelimiter = AsmToken::Space;
1750 break;
1751 }
1752 }
1753 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001754
1755 // HandleMacroEntry relies on not advancing the lexer here
1756 // to be able to fill in the remaining default parameter values
1757 if (Lexer.is(AsmToken::EndOfStatement))
1758 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001759
1760 // Adjust the current parentheses level.
1761 if (Lexer.is(AsmToken::LParen))
1762 ++ParenLevel;
1763 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1764 --ParenLevel;
1765
1766 // Append the token to the current argument list.
1767 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001768 if (AddTokens)
1769 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001770 Lex();
1771 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001772
1773 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001774 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001775 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001776 return false;
1777}
1778
1779// Parse the macro instantiation arguments.
Rafael Espindola8a403d32012-08-08 14:51:03 +00001780bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001781 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001782 // Argument delimiter is initially unknown. It will be set by
1783 // ParseMacroArgument()
1784 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001785
1786 // Parse two kinds of macro invocations:
1787 // - macros defined without any parameters accept an arbitrary number of them
1788 // - macros defined with parameters accept at most that many of them
1789 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1790 ++Parameter) {
1791 MacroArgument MA;
1792
Preston Gurd7b6f2032012-09-19 20:36:12 +00001793 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001794 return true;
1795
Preston Gurd6c9176a2012-09-19 20:29:04 +00001796 if (!MA.empty() || !NParameters)
1797 A.push_back(MA);
1798 else if (NParameters) {
1799 if (!M->Parameters[Parameter].second.empty())
1800 A.push_back(M->Parameters[Parameter].second);
1801 }
Jim Grosbach97146442012-07-30 22:44:17 +00001802
Preston Gurd6c9176a2012-09-19 20:29:04 +00001803 // At the end of the statement, fill in remaining arguments that have
1804 // default values. If there aren't any, then the next argument is
1805 // required but missing
1806 if (Lexer.is(AsmToken::EndOfStatement)) {
1807 if (NParameters && Parameter < NParameters - 1) {
1808 if (M->Parameters[Parameter + 1].second.empty())
1809 return TokError("macro argument '" +
1810 Twine(M->Parameters[Parameter + 1].first) +
1811 "' is missing");
1812 else
1813 continue;
1814 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001815 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001816 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001817
1818 if (Lexer.is(AsmToken::Comma))
1819 Lex();
1820 }
1821 return TokError("Too many arguments");
1822}
1823
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001824bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1825 const Macro *M) {
1826 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1827 // this, although we should protect against infinite loops.
1828 if (ActiveMacros.size() == 20)
1829 return TokError("macros cannot be nested more than 20 levels deep");
1830
Rafael Espindola8a403d32012-08-08 14:51:03 +00001831 MacroArguments A;
1832 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001833 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001834
Jim Grosbach97146442012-07-30 22:44:17 +00001835 // Remove any trailing empty arguments. Do this after-the-fact as we have
1836 // to keep empty arguments in the middle of the list or positionality
1837 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001838 while (!A.empty() && A.back().empty())
1839 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001840
Rafael Espindola65366442011-06-05 02:43:45 +00001841 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1842 // to hold the macro body with substitutions.
1843 SmallString<256> Buf;
1844 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001845 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001846
Rafael Espindola8a403d32012-08-08 14:51:03 +00001847 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001848 return true;
1849
Rafael Espindola761cb062012-06-03 23:57:14 +00001850 // We include the .endmacro in the buffer as our queue to exit the macro
1851 // instantiation.
1852 OS << ".endmacro\n";
1853
Rafael Espindola65366442011-06-05 02:43:45 +00001854 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001855 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001856
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001857 // Create the macro instantiation object and add to the current macro
1858 // instantiation stack.
1859 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001860 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001861 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001862 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001863 ActiveMacros.push_back(MI);
1864
1865 // Jump to the macro instantiation and prime the lexer.
1866 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1867 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1868 Lex();
1869
1870 return false;
1871}
1872
1873void AsmParser::HandleMacroExit() {
1874 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001875 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001876 Lex();
1877
1878 // Pop the instantiation entry.
1879 delete ActiveMacros.back();
1880 ActiveMacros.pop_back();
1881}
1882
Rafael Espindolae71cc862012-01-28 05:57:00 +00001883static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001884 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001885 case MCExpr::Binary: {
1886 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1887 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001888 break;
1889 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001890 case MCExpr::Target:
1891 case MCExpr::Constant:
1892 return false;
1893 case MCExpr::SymbolRef: {
1894 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001895 if (S.isVariable())
1896 return IsUsedIn(Sym, S.getVariableValue());
1897 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001898 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001899 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001900 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001901 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001902
1903 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001904}
1905
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001906bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1907 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001908 // FIXME: Use better location, we should use proper tokens.
1909 SMLoc EqualLoc = Lexer.getLoc();
1910
Daniel Dunbar821e3332009-08-31 08:09:28 +00001911 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001912 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001913 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001914
Rafael Espindolae71cc862012-01-28 05:57:00 +00001915 // Note: we don't count b as used in "a = b". This is to allow
1916 // a = b
1917 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001918
Daniel Dunbar3f872332009-07-28 16:08:33 +00001919 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001920 return TokError("unexpected token in assignment");
1921
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001922 // Error on assignment to '.'.
1923 if (Name == ".") {
1924 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1925 "(use '.space' or '.org').)"));
1926 }
1927
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001928 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001929 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001930
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001931 // Validate that the LHS is allowed to be a variable (either it has not been
1932 // used as a symbol, or it is an absolute symbol).
1933 MCSymbol *Sym = getContext().LookupSymbol(Name);
1934 if (Sym) {
1935 // Diagnose assignment to a label.
1936 //
1937 // FIXME: Diagnostics. Note the location of the definition as a label.
1938 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00001939 if (IsUsedIn(Sym, Value))
1940 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1941 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001942 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00001943 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1944 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00001945 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001946 return Error(EqualLoc, "redefinition of '" + Name + "'");
1947 else if (!Sym->isVariable())
1948 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00001949 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001950 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1951 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001952
1953 // Don't count these checks as uses.
1954 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001955 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001956 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001957
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001958 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001959
1960 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00001961 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001962 if (NoDeadStrip)
1963 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1964
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001965
1966 return false;
1967}
1968
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001969/// ParseIdentifier:
1970/// ::= identifier
1971/// ::= string
1972bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00001973 // The assembler has relaxed rules for accepting identifiers, in particular we
1974 // allow things like '.globl $foo', which would normally be separate
1975 // tokens. At this level, we have already lexed so we cannot (currently)
1976 // handle this as a context dependent token, instead we detect adjacent tokens
1977 // and return the combined identifier.
1978 if (Lexer.is(AsmToken::Dollar)) {
1979 SMLoc DollarLoc = getLexer().getLoc();
1980
1981 // Consume the dollar sign, and check for a following identifier.
1982 Lex();
1983 if (Lexer.isNot(AsmToken::Identifier))
1984 return true;
1985
1986 // We have a '$' followed by an identifier, make sure they are adjacent.
1987 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1988 return true;
1989
1990 // Construct the joined identifier and consume the token.
1991 Res = StringRef(DollarLoc.getPointer(),
1992 getTok().getIdentifier().size() + 1);
1993 Lex();
1994 return false;
1995 }
1996
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001997 if (Lexer.isNot(AsmToken::Identifier) &&
1998 Lexer.isNot(AsmToken::String))
1999 return true;
2000
Sean Callanan18b83232010-01-19 21:44:56 +00002001 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002002
Sean Callanan79ed1a82010-01-19 20:22:31 +00002003 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002004
2005 return false;
2006}
2007
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002008/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002009/// ::= .equ identifier ',' expression
2010/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002011/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002012bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002013 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002014
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002015 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002016 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002017
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002018 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002019 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002020 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002021
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002022 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002023}
2024
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002025bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002026 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002027
2028 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002029 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002030 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2031 if (Str[i] != '\\') {
2032 Data += Str[i];
2033 continue;
2034 }
2035
2036 // Recognize escaped characters. Note that this escape semantics currently
2037 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2038 ++i;
2039 if (i == e)
2040 return TokError("unexpected backslash at end of string");
2041
2042 // Recognize octal sequences.
2043 if ((unsigned) (Str[i] - '0') <= 7) {
2044 // Consume up to three octal characters.
2045 unsigned Value = Str[i] - '0';
2046
2047 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2048 ++i;
2049 Value = Value * 8 + (Str[i] - '0');
2050
2051 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2052 ++i;
2053 Value = Value * 8 + (Str[i] - '0');
2054 }
2055 }
2056
2057 if (Value > 255)
2058 return TokError("invalid octal escape sequence (out of range)");
2059
2060 Data += (unsigned char) Value;
2061 continue;
2062 }
2063
2064 // Otherwise recognize individual escapes.
2065 switch (Str[i]) {
2066 default:
2067 // Just reject invalid escape sequences for now.
2068 return TokError("invalid escape sequence (unrecognized character)");
2069
2070 case 'b': Data += '\b'; break;
2071 case 'f': Data += '\f'; break;
2072 case 'n': Data += '\n'; break;
2073 case 'r': Data += '\r'; break;
2074 case 't': Data += '\t'; break;
2075 case '"': Data += '"'; break;
2076 case '\\': Data += '\\'; break;
2077 }
2078 }
2079
2080 return false;
2081}
2082
Daniel Dunbara0d14262009-06-24 23:30:00 +00002083/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002084/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2085bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002086 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002087 CheckForValidSection();
2088
Daniel Dunbara0d14262009-06-24 23:30:00 +00002089 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002090 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002091 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002092
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002093 std::string Data;
2094 if (ParseEscapedString(Data))
2095 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002096
2097 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002098 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002099 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2100
Sean Callanan79ed1a82010-01-19 20:22:31 +00002101 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002102
2103 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002104 break;
2105
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002106 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002107 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002108 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002109 }
2110 }
2111
Sean Callanan79ed1a82010-01-19 20:22:31 +00002112 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002113 return false;
2114}
2115
2116/// ParseDirectiveValue
2117/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2118bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002119 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002120 CheckForValidSection();
2121
Daniel Dunbara0d14262009-06-24 23:30:00 +00002122 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002123 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002124 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002125 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002126 return true;
2127
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002128 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002129 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2130 assert(Size <= 8 && "Invalid size");
2131 uint64_t IntValue = MCE->getValue();
2132 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2133 return Error(ExprLoc, "literal value out of range for directive");
2134 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2135 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002136 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002137
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002138 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002139 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002140
Daniel Dunbara0d14262009-06-24 23:30:00 +00002141 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002142 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002143 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002144 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002145 }
2146 }
2147
Sean Callanan79ed1a82010-01-19 20:22:31 +00002148 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002149 return false;
2150}
2151
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002152/// ParseDirectiveRealValue
2153/// ::= (.single | .double) [ expression (, expression)* ]
2154bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2155 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2156 CheckForValidSection();
2157
2158 for (;;) {
2159 // We don't truly support arithmetic on floating point expressions, so we
2160 // have to manually parse unary prefixes.
2161 bool IsNeg = false;
2162 if (getLexer().is(AsmToken::Minus)) {
2163 Lex();
2164 IsNeg = true;
2165 } else if (getLexer().is(AsmToken::Plus))
2166 Lex();
2167
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002168 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002169 getLexer().isNot(AsmToken::Real) &&
2170 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002171 return TokError("unexpected token in directive");
2172
2173 // Convert to an APFloat.
2174 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002175 StringRef IDVal = getTok().getString();
2176 if (getLexer().is(AsmToken::Identifier)) {
2177 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2178 Value = APFloat::getInf(Semantics);
2179 else if (!IDVal.compare_lower("nan"))
2180 Value = APFloat::getNaN(Semantics, false, ~0);
2181 else
2182 return TokError("invalid floating point literal");
2183 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002184 APFloat::opInvalidOp)
2185 return TokError("invalid floating point literal");
2186 if (IsNeg)
2187 Value.changeSign();
2188
2189 // Consume the numeric token.
2190 Lex();
2191
2192 // Emit the value as an integer.
2193 APInt AsInt = Value.bitcastToAPInt();
2194 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2195 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2196
2197 if (getLexer().is(AsmToken::EndOfStatement))
2198 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002199
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002200 if (getLexer().isNot(AsmToken::Comma))
2201 return TokError("unexpected token in directive");
2202 Lex();
2203 }
2204 }
2205
2206 Lex();
2207 return false;
2208}
2209
Daniel Dunbara0d14262009-06-24 23:30:00 +00002210/// ParseDirectiveSpace
2211/// ::= .space expression [ , expression ]
2212bool AsmParser::ParseDirectiveSpace() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002213 CheckForValidSection();
2214
Daniel Dunbara0d14262009-06-24 23:30:00 +00002215 int64_t NumBytes;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002216 if (ParseAbsoluteExpression(NumBytes))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002217 return true;
2218
2219 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002220 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2221 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002222 return TokError("unexpected token in '.space' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002223 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002224
Daniel Dunbar475839e2009-06-29 20:37:27 +00002225 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002226 return true;
2227
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002228 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002229 return TokError("unexpected token in '.space' directive");
2230 }
2231
Sean Callanan79ed1a82010-01-19 20:22:31 +00002232 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002233
2234 if (NumBytes <= 0)
2235 return TokError("invalid number of bytes in '.space' directive");
2236
2237 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002238 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002239
2240 return false;
2241}
2242
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002243/// ParseDirectiveZero
2244/// ::= .zero expression
2245bool AsmParser::ParseDirectiveZero() {
2246 CheckForValidSection();
2247
2248 int64_t NumBytes;
2249 if (ParseAbsoluteExpression(NumBytes))
2250 return true;
2251
Rafael Espindolae452b172010-10-05 19:42:57 +00002252 int64_t Val = 0;
2253 if (getLexer().is(AsmToken::Comma)) {
2254 Lex();
2255 if (ParseAbsoluteExpression(Val))
2256 return true;
2257 }
2258
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002259 if (getLexer().isNot(AsmToken::EndOfStatement))
2260 return TokError("unexpected token in '.zero' directive");
2261
2262 Lex();
2263
Rafael Espindolae452b172010-10-05 19:42:57 +00002264 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002265
2266 return false;
2267}
2268
Daniel Dunbara0d14262009-06-24 23:30:00 +00002269/// ParseDirectiveFill
2270/// ::= .fill expression , expression , expression
2271bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002272 CheckForValidSection();
2273
Daniel Dunbara0d14262009-06-24 23:30:00 +00002274 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002275 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002276 return true;
2277
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002278 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002279 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002280 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002281
Daniel Dunbara0d14262009-06-24 23:30:00 +00002282 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002283 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002284 return true;
2285
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002286 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002287 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002288 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002289
Daniel Dunbara0d14262009-06-24 23:30:00 +00002290 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002291 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002292 return true;
2293
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002294 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002295 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002296
Sean Callanan79ed1a82010-01-19 20:22:31 +00002297 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002298
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002299 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2300 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002301
2302 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002303 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002304
2305 return false;
2306}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002307
2308/// ParseDirectiveOrg
2309/// ::= .org expression [ , expression ]
2310bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002311 CheckForValidSection();
2312
Daniel Dunbar821e3332009-08-31 08:09:28 +00002313 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002314 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002315 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002316 return true;
2317
2318 // Parse optional fill expression.
2319 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002320 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2321 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002322 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002323 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002324
Daniel Dunbar475839e2009-06-29 20:37:27 +00002325 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002326 return true;
2327
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002328 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002329 return TokError("unexpected token in '.org' directive");
2330 }
2331
Sean Callanan79ed1a82010-01-19 20:22:31 +00002332 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002333
Jim Grosbachebd4c052012-01-27 00:37:08 +00002334 // Only limited forms of relocatable expressions are accepted here, it
2335 // has to be relative to the current section. The streamer will return
2336 // 'true' if the expression wasn't evaluatable.
2337 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2338 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002339
2340 return false;
2341}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002342
2343/// ParseDirectiveAlign
2344/// ::= {.align, ...} expression [ , expression [ , expression ]]
2345bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002346 CheckForValidSection();
2347
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002348 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002349 int64_t Alignment;
2350 if (ParseAbsoluteExpression(Alignment))
2351 return true;
2352
2353 SMLoc MaxBytesLoc;
2354 bool HasFillExpr = false;
2355 int64_t FillExpr = 0;
2356 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002357 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2358 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002359 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002360 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002361
2362 // The fill expression can be omitted while specifying a maximum number of
2363 // alignment bytes, e.g:
2364 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002365 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002366 HasFillExpr = true;
2367 if (ParseAbsoluteExpression(FillExpr))
2368 return true;
2369 }
2370
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002371 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2372 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002373 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002374 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002375
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002376 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002377 if (ParseAbsoluteExpression(MaxBytesToFill))
2378 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002379
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002380 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002381 return TokError("unexpected token in directive");
2382 }
2383 }
2384
Sean Callanan79ed1a82010-01-19 20:22:31 +00002385 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002386
Daniel Dunbar648ac512010-05-17 21:54:30 +00002387 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002388 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002389
2390 // Compute alignment in bytes.
2391 if (IsPow2) {
2392 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002393 if (Alignment >= 32) {
2394 Error(AlignmentLoc, "invalid alignment value");
2395 Alignment = 31;
2396 }
2397
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002398 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002399 }
2400
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002401 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002402 if (MaxBytesLoc.isValid()) {
2403 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002404 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2405 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002406 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002407 }
2408
2409 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002410 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2411 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002412 MaxBytesToFill = 0;
2413 }
2414 }
2415
Daniel Dunbar648ac512010-05-17 21:54:30 +00002416 // Check whether we should use optimal code alignment for this .align
2417 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002418 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002419 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2420 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002421 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002422 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002423 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002424 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2425 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002426 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002427
2428 return false;
2429}
2430
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002431/// ParseDirectiveSymbolAttribute
2432/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00002433bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002434 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002435 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002436 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00002437 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002438
2439 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00002440 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002441
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002442 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002443
Jim Grosbach10ec6502011-09-15 17:56:49 +00002444 // Assembler local symbols don't make any sense here. Complain loudly.
2445 if (Sym->isTemporary())
2446 return Error(Loc, "non-local symbol required in directive");
2447
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002448 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002449
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002450 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002451 break;
2452
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002453 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002454 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002455 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002456 }
2457 }
2458
Sean Callanan79ed1a82010-01-19 20:22:31 +00002459 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00002460 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002461}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002462
2463/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00002464/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2465bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002466 CheckForValidSection();
2467
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002468 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002469 StringRef Name;
2470 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002471 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002472
Daniel Dunbar76c4d762009-07-31 21:55:09 +00002473 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002474 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002475
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002476 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002477 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002478 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002479
2480 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002481 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002482 if (ParseAbsoluteExpression(Size))
2483 return true;
2484
2485 int64_t Pow2Alignment = 0;
2486 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002487 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00002488 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002489 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002490 if (ParseAbsoluteExpression(Pow2Alignment))
2491 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002492
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002493 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2494 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00002495 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2496
Chris Lattner258281d2010-01-19 06:22:22 +00002497 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002498 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2499 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00002500 if (!isPowerOf2_64(Pow2Alignment))
2501 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2502 Pow2Alignment = Log2_64(Pow2Alignment);
2503 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002504 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002505
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002506 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00002507 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002508
Sean Callanan79ed1a82010-01-19 20:22:31 +00002509 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002510
Chris Lattner1fc3d752009-07-09 17:25:12 +00002511 // NOTE: a size of zero for a .comm should create a undefined symbol
2512 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002513 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002514 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2515 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002516
Eric Christopherc260a3e2010-05-14 01:38:54 +00002517 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002518 // may internally end up wanting an alignment in bytes.
2519 // FIXME: Diagnose overflow.
2520 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002521 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2522 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002523
Daniel Dunbar8906ff12009-08-22 07:22:36 +00002524 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002525 return Error(IDLoc, "invalid symbol redefinition");
2526
Chris Lattner1fc3d752009-07-09 17:25:12 +00002527 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002528 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00002529 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002530 return false;
2531 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002532
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002533 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002534 return false;
2535}
Chris Lattner9be3fee2009-07-10 22:20:30 +00002536
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002537/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002538/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002539bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002540 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002541 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002542
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002543 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002544 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002545 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002546
Sean Callanan79ed1a82010-01-19 20:22:31 +00002547 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002548
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002549 if (Str.empty())
2550 Error(Loc, ".abort detected. Assembly stopping.");
2551 else
2552 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002553 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002554
2555 return false;
2556}
Kevin Enderby71148242009-07-14 21:35:03 +00002557
Kevin Enderby1f049b22009-07-14 23:21:55 +00002558/// ParseDirectiveInclude
2559/// ::= .include "filename"
2560bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002561 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002562 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002563
Sean Callanan18b83232010-01-19 21:44:56 +00002564 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002565 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002566 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00002567
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002568 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002569 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002570
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002571 // Strip the quotes.
2572 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002573
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002574 // Attempt to switch the lexer to the included file before consuming the end
2575 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00002576 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00002577 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002578 return true;
2579 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00002580
2581 return false;
2582}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00002583
Kevin Enderbyc55acca2011-12-14 21:47:48 +00002584/// ParseDirectiveIncbin
2585/// ::= .incbin "filename"
2586bool AsmParser::ParseDirectiveIncbin() {
2587 if (getLexer().isNot(AsmToken::String))
2588 return TokError("expected string in '.incbin' directive");
2589
2590 std::string Filename = getTok().getString();
2591 SMLoc IncbinLoc = getLexer().getLoc();
2592 Lex();
2593
2594 if (getLexer().isNot(AsmToken::EndOfStatement))
2595 return TokError("unexpected token in '.incbin' directive");
2596
2597 // Strip the quotes.
2598 Filename = Filename.substr(1, Filename.size()-2);
2599
2600 // Attempt to process the included file.
2601 if (ProcessIncbinFile(Filename)) {
2602 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2603 return true;
2604 }
2605
2606 return false;
2607}
2608
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002609/// ParseDirectiveIf
2610/// ::= .if expression
2611bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002612 TheCondStack.push_back(TheCondState);
2613 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00002614 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002615 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00002616 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002617 int64_t ExprValue;
2618 if (ParseAbsoluteExpression(ExprValue))
2619 return true;
2620
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002621 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002622 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002623
Sean Callanan79ed1a82010-01-19 20:22:31 +00002624 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002625
2626 TheCondState.CondMet = ExprValue;
2627 TheCondState.Ignore = !TheCondState.CondMet;
2628 }
2629
2630 return false;
2631}
2632
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002633/// ParseDirectiveIfb
2634/// ::= .ifb string
2635bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2636 TheCondStack.push_back(TheCondState);
2637 TheCondState.TheCond = AsmCond::IfCond;
2638
Benjamin Kramer29739e72012-05-12 16:52:21 +00002639 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002640 EatToEndOfStatement();
2641 } else {
2642 StringRef Str = ParseStringToEndOfStatement();
2643
2644 if (getLexer().isNot(AsmToken::EndOfStatement))
2645 return TokError("unexpected token in '.ifb' directive");
2646
2647 Lex();
2648
2649 TheCondState.CondMet = ExpectBlank == Str.empty();
2650 TheCondState.Ignore = !TheCondState.CondMet;
2651 }
2652
2653 return false;
2654}
2655
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002656/// ParseDirectiveIfc
2657/// ::= .ifc string1, string2
2658bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2659 TheCondStack.push_back(TheCondState);
2660 TheCondState.TheCond = AsmCond::IfCond;
2661
Benjamin Kramer29739e72012-05-12 16:52:21 +00002662 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002663 EatToEndOfStatement();
2664 } else {
2665 StringRef Str1 = ParseStringToComma();
2666
2667 if (getLexer().isNot(AsmToken::Comma))
2668 return TokError("unexpected token in '.ifc' directive");
2669
2670 Lex();
2671
2672 StringRef Str2 = ParseStringToEndOfStatement();
2673
2674 if (getLexer().isNot(AsmToken::EndOfStatement))
2675 return TokError("unexpected token in '.ifc' directive");
2676
2677 Lex();
2678
2679 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2680 TheCondState.Ignore = !TheCondState.CondMet;
2681 }
2682
2683 return false;
2684}
2685
2686/// ParseDirectiveIfdef
2687/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00002688bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2689 StringRef Name;
2690 TheCondStack.push_back(TheCondState);
2691 TheCondState.TheCond = AsmCond::IfCond;
2692
2693 if (TheCondState.Ignore) {
2694 EatToEndOfStatement();
2695 } else {
2696 if (ParseIdentifier(Name))
2697 return TokError("expected identifier after '.ifdef'");
2698
2699 Lex();
2700
2701 MCSymbol *Sym = getContext().LookupSymbol(Name);
2702
2703 if (expect_defined)
2704 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2705 else
2706 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2707 TheCondState.Ignore = !TheCondState.CondMet;
2708 }
2709
2710 return false;
2711}
2712
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002713/// ParseDirectiveElseIf
2714/// ::= .elseif expression
2715bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2716 if (TheCondState.TheCond != AsmCond::IfCond &&
2717 TheCondState.TheCond != AsmCond::ElseIfCond)
2718 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2719 " an .elseif");
2720 TheCondState.TheCond = AsmCond::ElseIfCond;
2721
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002722 bool LastIgnoreState = false;
2723 if (!TheCondStack.empty())
2724 LastIgnoreState = TheCondStack.back().Ignore;
2725 if (LastIgnoreState || TheCondState.CondMet) {
2726 TheCondState.Ignore = true;
2727 EatToEndOfStatement();
2728 }
2729 else {
2730 int64_t ExprValue;
2731 if (ParseAbsoluteExpression(ExprValue))
2732 return true;
2733
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002734 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002735 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002736
Sean Callanan79ed1a82010-01-19 20:22:31 +00002737 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002738 TheCondState.CondMet = ExprValue;
2739 TheCondState.Ignore = !TheCondState.CondMet;
2740 }
2741
2742 return false;
2743}
2744
2745/// ParseDirectiveElse
2746/// ::= .else
2747bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002748 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002749 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002750
Sean Callanan79ed1a82010-01-19 20:22:31 +00002751 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002752
2753 if (TheCondState.TheCond != AsmCond::IfCond &&
2754 TheCondState.TheCond != AsmCond::ElseIfCond)
2755 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2756 ".elseif");
2757 TheCondState.TheCond = AsmCond::ElseCond;
2758 bool LastIgnoreState = false;
2759 if (!TheCondStack.empty())
2760 LastIgnoreState = TheCondStack.back().Ignore;
2761 if (LastIgnoreState || TheCondState.CondMet)
2762 TheCondState.Ignore = true;
2763 else
2764 TheCondState.Ignore = false;
2765
2766 return false;
2767}
2768
2769/// ParseDirectiveEndIf
2770/// ::= .endif
2771bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002772 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002773 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002774
Sean Callanan79ed1a82010-01-19 20:22:31 +00002775 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002776
2777 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2778 TheCondStack.empty())
2779 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2780 ".else");
2781 if (!TheCondStack.empty()) {
2782 TheCondState = TheCondStack.back();
2783 TheCondStack.pop_back();
2784 }
2785
2786 return false;
2787}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002788
2789/// ParseDirectiveFile
Nick Lewycky44d798d2011-10-17 23:05:28 +00002790/// ::= .file [number] filename
2791/// ::= .file number directory filename
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002792bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002793 // FIXME: I'm not sure what this is.
2794 int64_t FileNumber = -1;
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002795 SMLoc FileNumberLoc = getLexer().getLoc();
Daniel Dunbareceec052010-07-12 17:45:27 +00002796 if (getLexer().is(AsmToken::Integer)) {
Sean Callanan18b83232010-01-19 21:44:56 +00002797 FileNumber = getTok().getIntVal();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002798 Lex();
Daniel Dunbareceec052010-07-12 17:45:27 +00002799
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002800 if (FileNumber < 1)
2801 return TokError("file number less than one");
2802 }
2803
Daniel Dunbareceec052010-07-12 17:45:27 +00002804 if (getLexer().isNot(AsmToken::String))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002805 return TokError("unexpected token in '.file' directive");
Daniel Dunbareceec052010-07-12 17:45:27 +00002806
Nick Lewycky44d798d2011-10-17 23:05:28 +00002807 // Usually the directory and filename together, otherwise just the directory.
2808 StringRef Path = getTok().getString();
2809 Path = Path.substr(1, Path.size()-2);
Sean Callanan79ed1a82010-01-19 20:22:31 +00002810 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002811
Nick Lewycky44d798d2011-10-17 23:05:28 +00002812 StringRef Directory;
2813 StringRef Filename;
2814 if (getLexer().is(AsmToken::String)) {
2815 if (FileNumber == -1)
2816 return TokError("explicit path specified, but no file number");
2817 Filename = getTok().getString();
2818 Filename = Filename.substr(1, Filename.size()-2);
2819 Directory = Path;
2820 Lex();
2821 } else {
2822 Filename = Path;
2823 }
2824
Daniel Dunbareceec052010-07-12 17:45:27 +00002825 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002826 return TokError("unexpected token in '.file' directive");
2827
Chris Lattnerd32e8032010-01-25 19:02:58 +00002828 if (FileNumber == -1)
Daniel Dunbareceec052010-07-12 17:45:27 +00002829 getStreamer().EmitFileDirective(Filename);
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002830 else {
Kevin Enderby8704b782012-01-11 18:04:47 +00002831 if (getContext().getGenDwarfForAssembly() == true)
2832 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2833 "used to generate dwarf debug info for assembly code");
2834
Nick Lewycky44d798d2011-10-17 23:05:28 +00002835 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002836 Error(FileNumberLoc, "file number already allocated");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002837 }
Daniel Dunbareceec052010-07-12 17:45:27 +00002838
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002839 return false;
2840}
2841
2842/// ParseDirectiveLine
2843/// ::= .line [number]
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002844bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbareceec052010-07-12 17:45:27 +00002845 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2846 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002847 return TokError("unexpected token in '.line' directive");
2848
Sean Callanan18b83232010-01-19 21:44:56 +00002849 int64_t LineNumber = getTok().getIntVal();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002850 (void) LineNumber;
Sean Callanan79ed1a82010-01-19 20:22:31 +00002851 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002852
2853 // FIXME: Do something with the .line.
2854 }
2855
Daniel Dunbareceec052010-07-12 17:45:27 +00002856 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar839348a2010-07-01 20:20:01 +00002857 return TokError("unexpected token in '.line' directive");
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002858
2859 return false;
2860}
2861
2862
2863/// ParseDirectiveLoc
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002864/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002865/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2866/// The first number is a file number, must have been previously assigned with
2867/// a .file directive, the second number is the line number and optionally the
2868/// third number is a column position (zero if not specified). The remaining
2869/// optional items are .loc sub-directives.
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002870bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002871
Daniel Dunbareceec052010-07-12 17:45:27 +00002872 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002873 return TokError("unexpected token in '.loc' directive");
Sean Callanan18b83232010-01-19 21:44:56 +00002874 int64_t FileNumber = getTok().getIntVal();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002875 if (FileNumber < 1)
2876 return TokError("file number less than one in '.loc' directive");
Kevin Enderby3f55c242010-10-04 20:17:24 +00002877 if (!getContext().isValidDwarfFileNumber(FileNumber))
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002878 return TokError("unassigned file number in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002879 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002880
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002881 int64_t LineNumber = 0;
2882 if (getLexer().is(AsmToken::Integer)) {
2883 LineNumber = getTok().getIntVal();
2884 if (LineNumber < 1)
2885 return TokError("line number less than one in '.loc' directive");
2886 Lex();
2887 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002888
2889 int64_t ColumnPos = 0;
2890 if (getLexer().is(AsmToken::Integer)) {
2891 ColumnPos = getTok().getIntVal();
2892 if (ColumnPos < 0)
2893 return TokError("column position less than zero in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002894 Lex();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002895 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002896
Kevin Enderbyc0957932010-09-30 16:52:03 +00002897 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002898 unsigned Isa = 0;
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002899 int64_t Discriminator = 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002900 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2901 for (;;) {
2902 if (getLexer().is(AsmToken::EndOfStatement))
2903 break;
2904
2905 StringRef Name;
2906 SMLoc Loc = getTok().getLoc();
2907 if (getParser().ParseIdentifier(Name))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002908 return TokError("unexpected token in '.loc' directive");
2909
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002910 if (Name == "basic_block")
2911 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2912 else if (Name == "prologue_end")
2913 Flags |= DWARF2_FLAG_PROLOGUE_END;
2914 else if (Name == "epilogue_begin")
2915 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2916 else if (Name == "is_stmt") {
2917 SMLoc Loc = getTok().getLoc();
2918 const MCExpr *Value;
2919 if (getParser().ParseExpression(Value))
2920 return true;
2921 // The expression must be the constant 0 or 1.
2922 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2923 int Value = MCE->getValue();
2924 if (Value == 0)
2925 Flags &= ~DWARF2_FLAG_IS_STMT;
2926 else if (Value == 1)
2927 Flags |= DWARF2_FLAG_IS_STMT;
2928 else
2929 return Error(Loc, "is_stmt value not 0 or 1");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002930 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002931 else {
2932 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2933 }
2934 }
2935 else if (Name == "isa") {
2936 SMLoc Loc = getTok().getLoc();
2937 const MCExpr *Value;
2938 if (getParser().ParseExpression(Value))
2939 return true;
2940 // The expression must be a constant greater or equal to 0.
2941 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2942 int Value = MCE->getValue();
2943 if (Value < 0)
2944 return Error(Loc, "isa number less than zero");
2945 Isa = Value;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002946 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002947 else {
2948 return Error(Loc, "isa number not a constant value");
2949 }
2950 }
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002951 else if (Name == "discriminator") {
2952 if (getParser().ParseAbsoluteExpression(Discriminator))
2953 return true;
2954 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002955 else {
2956 return Error(Loc, "unknown sub-directive in '.loc' directive");
2957 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002958
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002959 if (getLexer().is(AsmToken::EndOfStatement))
2960 break;
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002961 }
2962 }
2963
Rafael Espindolaaf6b58082010-11-16 21:20:32 +00002964 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
Devang Patel3f3bf932011-04-18 20:26:49 +00002965 Isa, Discriminator, StringRef());
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002966
2967 return false;
2968}
2969
Daniel Dunbar138abae2010-10-16 04:56:42 +00002970/// ParseDirectiveStabs
2971/// ::= .stabs string, number, number, number
2972bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2973 SMLoc DirectiveLoc) {
2974 return TokError("unsupported directive '" + Directive + "'");
2975}
2976
Rafael Espindolaf9efd832011-05-10 01:10:18 +00002977/// ParseDirectiveCFISections
2978/// ::= .cfi_sections section [, section]
2979bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2980 SMLoc DirectiveLoc) {
2981 StringRef Name;
2982 bool EH = false;
2983 bool Debug = false;
2984
2985 if (getParser().ParseIdentifier(Name))
2986 return TokError("Expected an identifier");
2987
2988 if (Name == ".eh_frame")
2989 EH = true;
2990 else if (Name == ".debug_frame")
2991 Debug = true;
2992
2993 if (getLexer().is(AsmToken::Comma)) {
2994 Lex();
2995
2996 if (getParser().ParseIdentifier(Name))
2997 return TokError("Expected an identifier");
2998
2999 if (Name == ".eh_frame")
3000 EH = true;
3001 else if (Name == ".debug_frame")
3002 Debug = true;
3003 }
3004
3005 getStreamer().EmitCFISections(EH, Debug);
3006
3007 return false;
3008}
3009
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003010/// ParseDirectiveCFIStartProc
3011/// ::= .cfi_startproc
3012bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
3013 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003014 getStreamer().EmitCFIStartProc();
3015 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003016}
3017
3018/// ParseDirectiveCFIEndProc
3019/// ::= .cfi_endproc
3020bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003021 getStreamer().EmitCFIEndProc();
3022 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003023}
3024
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003025/// ParseRegisterOrRegisterNumber - parse register name or number.
3026bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
3027 SMLoc DirectiveLoc) {
3028 unsigned RegNo;
3029
Jim Grosbach6f888a82011-06-02 17:14:04 +00003030 if (getLexer().isNot(AsmToken::Integer)) {
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003031 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
3032 DirectiveLoc))
3033 return true;
Evan Cheng0e6a0522011-07-18 20:57:22 +00003034 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003035 } else
3036 return getParser().ParseAbsoluteExpression(Register);
Jim Grosbachde2f5f42011-02-11 19:05:56 +00003037
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003038 return false;
3039}
3040
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003041/// ParseDirectiveCFIDefCfa
3042/// ::= .cfi_def_cfa register, offset
3043bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
3044 SMLoc DirectiveLoc) {
3045 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003046 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003047 return true;
3048
3049 if (getLexer().isNot(AsmToken::Comma))
3050 return TokError("unexpected token in directive");
3051 Lex();
3052
3053 int64_t Offset = 0;
3054 if (getParser().ParseAbsoluteExpression(Offset))
3055 return true;
3056
Rafael Espindola066c2f42011-04-12 23:59:07 +00003057 getStreamer().EmitCFIDefCfa(Register, Offset);
3058 return false;
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003059}
3060
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003061/// ParseDirectiveCFIDefCfaOffset
3062/// ::= .cfi_def_cfa_offset offset
3063bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3064 SMLoc DirectiveLoc) {
3065 int64_t Offset = 0;
3066 if (getParser().ParseAbsoluteExpression(Offset))
3067 return true;
3068
Rafael Espindola066c2f42011-04-12 23:59:07 +00003069 getStreamer().EmitCFIDefCfaOffset(Offset);
3070 return false;
Rafael Espindola53abbe52011-04-11 20:29:16 +00003071}
3072
3073/// ParseDirectiveCFIAdjustCfaOffset
3074/// ::= .cfi_adjust_cfa_offset adjustment
3075bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3076 SMLoc DirectiveLoc) {
3077 int64_t Adjustment = 0;
3078 if (getParser().ParseAbsoluteExpression(Adjustment))
3079 return true;
3080
Rafael Espindola5d7dcd32011-04-12 18:53:30 +00003081 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3082 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003083}
3084
3085/// ParseDirectiveCFIDefCfaRegister
3086/// ::= .cfi_def_cfa_register register
3087bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3088 SMLoc DirectiveLoc) {
3089 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003090 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003091 return true;
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003092
Rafael Espindola066c2f42011-04-12 23:59:07 +00003093 getStreamer().EmitCFIDefCfaRegister(Register);
3094 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003095}
3096
3097/// ParseDirectiveCFIOffset
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003098/// ::= .cfi_offset register, offset
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003099bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3100 int64_t Register = 0;
3101 int64_t Offset = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003102
3103 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003104 return true;
3105
3106 if (getLexer().isNot(AsmToken::Comma))
3107 return TokError("unexpected token in directive");
3108 Lex();
3109
3110 if (getParser().ParseAbsoluteExpression(Offset))
3111 return true;
3112
Rafael Espindola066c2f42011-04-12 23:59:07 +00003113 getStreamer().EmitCFIOffset(Register, Offset);
3114 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003115}
3116
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003117/// ParseDirectiveCFIRelOffset
3118/// ::= .cfi_rel_offset register, offset
3119bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3120 SMLoc DirectiveLoc) {
3121 int64_t Register = 0;
3122
3123 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3124 return true;
3125
3126 if (getLexer().isNot(AsmToken::Comma))
3127 return TokError("unexpected token in directive");
3128 Lex();
3129
3130 int64_t Offset = 0;
3131 if (getParser().ParseAbsoluteExpression(Offset))
3132 return true;
3133
Rafael Espindola25f492e2011-04-12 16:12:03 +00003134 getStreamer().EmitCFIRelOffset(Register, Offset);
3135 return false;
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003136}
3137
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003138static bool isValidEncoding(int64_t Encoding) {
3139 if (Encoding & ~0xff)
3140 return false;
3141
3142 if (Encoding == dwarf::DW_EH_PE_omit)
3143 return true;
3144
3145 const unsigned Format = Encoding & 0xf;
3146 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3147 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3148 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3149 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3150 return false;
3151
Rafael Espindolacaf11582010-12-29 04:31:26 +00003152 const unsigned Application = Encoding & 0x70;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003153 if (Application != dwarf::DW_EH_PE_absptr &&
Rafael Espindolacaf11582010-12-29 04:31:26 +00003154 Application != dwarf::DW_EH_PE_pcrel)
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003155 return false;
3156
3157 return true;
3158}
3159
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003160/// ParseDirectiveCFIPersonalityOrLsda
3161/// ::= .cfi_personality encoding, [symbol_name]
3162/// ::= .cfi_lsda encoding, [symbol_name]
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003163bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003164 SMLoc DirectiveLoc) {
3165 int64_t Encoding = 0;
3166 if (getParser().ParseAbsoluteExpression(Encoding))
3167 return true;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003168 if (Encoding == dwarf::DW_EH_PE_omit)
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003169 return false;
3170
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003171 if (!isValidEncoding(Encoding))
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003172 return TokError("unsupported encoding.");
3173
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003174 if (getLexer().isNot(AsmToken::Comma))
3175 return TokError("unexpected token in directive");
3176 Lex();
3177
3178 StringRef Name;
3179 if (getParser().ParseIdentifier(Name))
3180 return TokError("expected identifier in directive");
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003181
3182 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3183
3184 if (IDVal == ".cfi_personality")
Rafael Espindola066c2f42011-04-12 23:59:07 +00003185 getStreamer().EmitCFIPersonality(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003186 else {
3187 assert(IDVal == ".cfi_lsda");
Rafael Espindola066c2f42011-04-12 23:59:07 +00003188 getStreamer().EmitCFILsda(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003189 }
Rafael Espindola066c2f42011-04-12 23:59:07 +00003190 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003191}
3192
Rafael Espindolafe024d02010-12-28 18:36:23 +00003193/// ParseDirectiveCFIRememberState
3194/// ::= .cfi_remember_state
3195bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3196 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003197 getStreamer().EmitCFIRememberState();
3198 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003199}
3200
3201/// ParseDirectiveCFIRestoreState
3202/// ::= .cfi_remember_state
3203bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3204 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003205 getStreamer().EmitCFIRestoreState();
3206 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003207}
3208
Rafael Espindolac5754392011-04-12 15:31:05 +00003209/// ParseDirectiveCFISameValue
3210/// ::= .cfi_same_value register
3211bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3212 SMLoc DirectiveLoc) {
3213 int64_t Register = 0;
3214
3215 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3216 return true;
3217
3218 getStreamer().EmitCFISameValue(Register);
3219
3220 return false;
3221}
3222
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003223/// ParseDirectiveCFIRestore
3224/// ::= .cfi_restore register
3225bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003226 SMLoc DirectiveLoc) {
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003227 int64_t Register = 0;
3228 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3229 return true;
3230
3231 getStreamer().EmitCFIRestore(Register);
3232
3233 return false;
3234}
3235
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003236/// ParseDirectiveCFIEscape
3237/// ::= .cfi_escape expression[,...]
3238bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003239 SMLoc DirectiveLoc) {
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003240 std::string Values;
3241 int64_t CurrValue;
3242 if (getParser().ParseAbsoluteExpression(CurrValue))
3243 return true;
3244
3245 Values.push_back((uint8_t)CurrValue);
3246
3247 while (getLexer().is(AsmToken::Comma)) {
3248 Lex();
3249
3250 if (getParser().ParseAbsoluteExpression(CurrValue))
3251 return true;
3252
3253 Values.push_back((uint8_t)CurrValue);
3254 }
3255
3256 getStreamer().EmitCFIEscape(Values);
3257 return false;
3258}
3259
Rafael Espindola16d7d432012-01-23 21:51:52 +00003260/// ParseDirectiveCFISignalFrame
3261/// ::= .cfi_signal_frame
3262bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3263 SMLoc DirectiveLoc) {
3264 if (getLexer().isNot(AsmToken::EndOfStatement))
3265 return Error(getLexer().getLoc(),
3266 "unexpected token in '" + Directive + "' directive");
3267
3268 getStreamer().EmitCFISignalFrame();
3269
3270 return false;
3271}
3272
Rafael Espindolac8fec7e2012-11-23 16:59:41 +00003273/// ParseDirectiveCFIUndefined
3274/// ::= .cfi_undefined register
3275bool GenericAsmParser::ParseDirectiveCFIUndefined(StringRef Directive,
3276 SMLoc DirectiveLoc) {
3277 int64_t Register = 0;
3278
3279 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3280 return true;
3281
3282 getStreamer().EmitCFIUndefined(Register);
3283
3284 return false;
3285}
3286
Rafael Espindolaf4f14f62012-11-25 15:14:49 +00003287/// ParseDirectiveCFIRegister
3288/// ::= .cfi_register register, register
3289bool GenericAsmParser::ParseDirectiveCFIRegister(StringRef Directive,
3290 SMLoc DirectiveLoc) {
3291 int64_t Register1 = 0;
3292
3293 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3294 return true;
3295
3296 if (getLexer().isNot(AsmToken::Comma))
3297 return TokError("unexpected token in directive");
3298 Lex();
3299
3300 int64_t Register2 = 0;
3301
3302 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3303 return true;
3304
3305 getStreamer().EmitCFIRegister(Register1, Register2);
3306
3307 return false;
3308}
3309
Daniel Dunbar3c802de2010-07-18 18:38:02 +00003310/// ParseDirectiveMacrosOnOff
3311/// ::= .macros_on
3312/// ::= .macros_off
3313bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3314 SMLoc DirectiveLoc) {
3315 if (getLexer().isNot(AsmToken::EndOfStatement))
3316 return Error(getLexer().getLoc(),
3317 "unexpected token in '" + Directive + "' directive");
3318
3319 getParser().MacrosEnabled = Directive == ".macros_on";
3320
3321 return false;
3322}
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003323
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003324/// ParseDirectiveMacro
Rafael Espindola65366442011-06-05 02:43:45 +00003325/// ::= .macro name [parameters]
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003326bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3327 SMLoc DirectiveLoc) {
3328 StringRef Name;
3329 if (getParser().ParseIdentifier(Name))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003330 return TokError("expected identifier in '.macro' directive");
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003331
Rafael Espindola8a403d32012-08-08 14:51:03 +00003332 MacroParameters Parameters;
Preston Gurd7b6f2032012-09-19 20:36:12 +00003333 // Argument delimiter is initially unknown. It will be set by
3334 // ParseMacroArgument()
3335 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindola65366442011-06-05 02:43:45 +00003336 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Rafael Espindola7996d042012-08-21 16:06:48 +00003337 for (;;) {
3338 MacroParameter Parameter;
Preston Gurd6c9176a2012-09-19 20:29:04 +00003339 if (getParser().ParseIdentifier(Parameter.first))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003340 return TokError("expected identifier in '.macro' directive");
Preston Gurd6c9176a2012-09-19 20:29:04 +00003341
3342 if (getLexer().is(AsmToken::Equal)) {
3343 Lex();
Preston Gurd7b6f2032012-09-19 20:36:12 +00003344 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
Preston Gurd6c9176a2012-09-19 20:29:04 +00003345 return true;
3346 }
3347
Rafael Espindola65366442011-06-05 02:43:45 +00003348 Parameters.push_back(Parameter);
3349
Preston Gurd7b6f2032012-09-19 20:36:12 +00003350 if (getLexer().is(AsmToken::Comma))
3351 Lex();
3352 else if (getLexer().is(AsmToken::EndOfStatement))
Rafael Espindola65366442011-06-05 02:43:45 +00003353 break;
Rafael Espindola65366442011-06-05 02:43:45 +00003354 }
3355 }
3356
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003357 // Eat the end of statement.
3358 Lex();
3359
3360 AsmToken EndToken, StartToken = getTok();
3361
3362 // Lex the macro definition.
3363 for (;;) {
3364 // Check whether we have reached the end of the file.
3365 if (getLexer().is(AsmToken::Eof))
3366 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3367
3368 // Otherwise, check whether we have reach the .endmacro.
3369 if (getLexer().is(AsmToken::Identifier) &&
3370 (getTok().getIdentifier() == ".endm" ||
3371 getTok().getIdentifier() == ".endmacro")) {
3372 EndToken = getTok();
3373 Lex();
3374 if (getLexer().isNot(AsmToken::EndOfStatement))
3375 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3376 "' directive");
3377 break;
3378 }
3379
3380 // Otherwise, scan til the end of the statement.
3381 getParser().EatToEndOfStatement();
3382 }
3383
3384 if (getParser().MacroMap.lookup(Name)) {
3385 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3386 }
3387
3388 const char *BodyStart = StartToken.getLoc().getPointer();
3389 const char *BodyEnd = EndToken.getLoc().getPointer();
3390 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Rafael Espindola65366442011-06-05 02:43:45 +00003391 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003392 return false;
3393}
3394
3395/// ParseDirectiveEndMacro
3396/// ::= .endm
3397/// ::= .endmacro
3398bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
Rafael Espindola8a403d32012-08-08 14:51:03 +00003399 SMLoc DirectiveLoc) {
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003400 if (getLexer().isNot(AsmToken::EndOfStatement))
3401 return TokError("unexpected token in '" + Directive + "' directive");
3402
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00003403 // If we are inside a macro instantiation, terminate the current
3404 // instantiation.
3405 if (!getParser().ActiveMacros.empty()) {
3406 getParser().HandleMacroExit();
3407 return false;
3408 }
3409
3410 // Otherwise, this .endmacro is a stray entry in the file; well formed
3411 // .endmacro directives are handled during the macro definition parsing.
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003412 return TokError("unexpected '" + Directive + "' in file, "
3413 "no current macro definition");
3414}
3415
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +00003416/// ParseDirectivePurgeMacro
3417/// ::= .purgem
3418bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3419 SMLoc DirectiveLoc) {
3420 StringRef Name;
3421 if (getParser().ParseIdentifier(Name))
3422 return TokError("expected identifier in '.purgem' directive");
3423
3424 if (getLexer().isNot(AsmToken::EndOfStatement))
3425 return TokError("unexpected token in '.purgem' directive");
3426
3427 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3428 if (I == getParser().MacroMap.end())
3429 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3430
3431 // Undefine the macro.
3432 delete I->getValue();
3433 getParser().MacroMap.erase(I);
3434 return false;
3435}
3436
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003437bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
Rafael Espindola3ff57092010-11-02 17:22:24 +00003438 getParser().CheckForValidSection();
3439
3440 const MCExpr *Value;
3441
3442 if (getParser().ParseExpression(Value))
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003443 return true;
3444
3445 if (getLexer().isNot(AsmToken::EndOfStatement))
3446 return TokError("unexpected token in directive");
3447
3448 if (DirName[1] == 's')
Rafael Espindola3ff57092010-11-02 17:22:24 +00003449 getStreamer().EmitSLEB128Value(Value);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003450 else
Rafael Espindola3ff57092010-11-02 17:22:24 +00003451 getStreamer().EmitULEB128Value(Value);
3452
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003453 return false;
3454}
3455
Rafael Espindola761cb062012-06-03 23:57:14 +00003456Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003457 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003458
Rafael Espindola761cb062012-06-03 23:57:14 +00003459 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003460 for (;;) {
3461 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003462 if (getLexer().is(AsmToken::Eof)) {
3463 Error(DirectiveLoc, "no matching '.endr' in definition");
3464 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003465 }
3466
Rafael Espindola761cb062012-06-03 23:57:14 +00003467 if (Lexer.is(AsmToken::Identifier) &&
3468 (getTok().getIdentifier() == ".rept")) {
3469 ++NestLevel;
3470 }
3471
3472 // Otherwise, check whether we have reached the .endr.
3473 if (Lexer.is(AsmToken::Identifier) &&
3474 getTok().getIdentifier() == ".endr") {
3475 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003476 EndToken = getTok();
3477 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003478 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3479 TokError("unexpected token in '.endr' directive");
3480 return 0;
3481 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003482 break;
3483 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003484 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003485 }
3486
Rafael Espindola761cb062012-06-03 23:57:14 +00003487 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003488 EatToEndOfStatement();
3489 }
3490
3491 const char *BodyStart = StartToken.getLoc().getPointer();
3492 const char *BodyEnd = EndToken.getLoc().getPointer();
3493 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3494
Rafael Espindola761cb062012-06-03 23:57:14 +00003495 // We Are Anonymous.
3496 StringRef Name;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003497 MacroParameters Parameters;
Rafael Espindola761cb062012-06-03 23:57:14 +00003498 return new Macro(Name, Body, Parameters);
3499}
3500
3501void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3502 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003503 OS << ".endr\n";
3504
3505 MemoryBuffer *Instantiation =
3506 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3507
Rafael Espindola761cb062012-06-03 23:57:14 +00003508 // Create the macro instantiation object and add to the current macro
3509 // instantiation stack.
3510 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003511 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003512 getTok().getLoc(),
3513 Instantiation);
3514 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003515
Rafael Espindola761cb062012-06-03 23:57:14 +00003516 // Jump to the macro instantiation and prime the lexer.
3517 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3518 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3519 Lex();
3520}
3521
3522bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3523 int64_t Count;
3524 if (ParseAbsoluteExpression(Count))
3525 return TokError("unexpected token in '.rept' directive");
3526
3527 if (Count < 0)
3528 return TokError("Count is negative");
3529
3530 if (Lexer.isNot(AsmToken::EndOfStatement))
3531 return TokError("unexpected token in '.rept' directive");
3532
3533 // Eat the end of statement.
3534 Lex();
3535
3536 // Lex the rept definition.
3537 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3538 if (!M)
3539 return true;
3540
3541 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3542 // to hold the macro body with substitutions.
3543 SmallString<256> Buf;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003544 MacroParameters Parameters;
3545 MacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003546 raw_svector_ostream OS(Buf);
3547 while (Count--) {
3548 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3549 return true;
3550 }
3551 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003552
3553 return false;
3554}
3555
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003556/// ParseDirectiveIrp
3557/// ::= .irp symbol,values
3558bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003559 MacroParameters Parameters;
3560 MacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003561
Preston Gurd6c9176a2012-09-19 20:29:04 +00003562 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003563 return TokError("expected identifier in '.irp' directive");
3564
3565 Parameters.push_back(Parameter);
3566
3567 if (Lexer.isNot(AsmToken::Comma))
3568 return TokError("expected comma in '.irp' directive");
3569
3570 Lex();
3571
Rafael Espindola8a403d32012-08-08 14:51:03 +00003572 MacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003573 if (ParseMacroArguments(0, A))
3574 return true;
3575
3576 // Eat the end of statement.
3577 Lex();
3578
3579 // Lex the irp definition.
3580 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3581 if (!M)
3582 return true;
3583
3584 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3585 // to hold the macro body with substitutions.
3586 SmallString<256> Buf;
3587 raw_svector_ostream OS(Buf);
3588
Rafael Espindola7996d042012-08-21 16:06:48 +00003589 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3590 MacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003591 Args.push_back(*i);
3592
3593 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3594 return true;
3595 }
3596
3597 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3598
3599 return false;
3600}
3601
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003602/// ParseDirectiveIrpc
3603/// ::= .irpc symbol,values
3604bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003605 MacroParameters Parameters;
3606 MacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003607
Preston Gurd6c9176a2012-09-19 20:29:04 +00003608 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003609 return TokError("expected identifier in '.irpc' directive");
3610
3611 Parameters.push_back(Parameter);
3612
3613 if (Lexer.isNot(AsmToken::Comma))
3614 return TokError("expected comma in '.irpc' directive");
3615
3616 Lex();
3617
Rafael Espindola8a403d32012-08-08 14:51:03 +00003618 MacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003619 if (ParseMacroArguments(0, A))
3620 return true;
3621
3622 if (A.size() != 1 || A.front().size() != 1)
3623 return TokError("unexpected token in '.irpc' directive");
3624
3625 // Eat the end of statement.
3626 Lex();
3627
3628 // Lex the irpc definition.
3629 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3630 if (!M)
3631 return true;
3632
3633 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3634 // to hold the macro body with substitutions.
3635 SmallString<256> Buf;
3636 raw_svector_ostream OS(Buf);
3637
3638 StringRef Values = A.front().front().getString();
3639 std::size_t I, End = Values.size();
3640 for (I = 0; I < End; ++I) {
3641 MacroArgument Arg;
3642 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3643
Rafael Espindola8a403d32012-08-08 14:51:03 +00003644 MacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003645 Args.push_back(Arg);
3646
3647 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3648 return true;
3649 }
3650
3651 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3652
3653 return false;
3654}
3655
Rafael Espindola761cb062012-06-03 23:57:14 +00003656bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3657 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003658 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003659
3660 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003661 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003662 assert(getLexer().is(AsmToken::EndOfStatement));
3663
Rafael Espindola761cb062012-06-03 23:57:14 +00003664 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003665 return false;
3666}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003667
Eli Friedman2128aae2012-10-22 23:58:19 +00003668bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3669 const MCExpr *Value;
3670 SMLoc ExprLoc = getLexer().getLoc();
3671 if (ParseExpression(Value))
3672 return true;
3673 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3674 if (!MCE)
3675 return Error(ExprLoc, "unexpected expression in _emit");
3676 uint64_t IntValue = MCE->getValue();
3677 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3678 return Error(ExprLoc, "literal value out of range for directive");
3679
3680 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3681 return false;
3682}
3683
Chad Rosierb1f8c132012-10-18 15:49:34 +00003684bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3685 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003686 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003687 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003688 SmallVectorImpl<std::string> &Clobbers,
3689 const MCInstrInfo *MII,
3690 const MCInstPrinter *IP,
3691 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003692 SmallVector<void *, 4> InputDecls;
3693 SmallVector<void *, 4> OutputDecls;
3694 SmallVector<bool, 4> InputDeclsOffsetOf;
3695 SmallVector<bool, 4> OutputDeclsOffsetOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003696 SmallVector<std::string, 4> InputConstraints;
3697 SmallVector<std::string, 4> OutputConstraints;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003698 std::set<std::string> ClobberRegs;
3699
Chad Rosier4e472d22012-10-20 01:02:45 +00003700 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003701
3702 // Prime the lexer.
3703 Lex();
3704
3705 // While we have input, parse each statement.
3706 unsigned InputIdx = 0;
3707 unsigned OutputIdx = 0;
3708 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00003709 ParseStatementInfo Info(&AsmStrRewrites);
3710 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00003711 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003712
Chad Rosier57498012012-12-12 22:45:52 +00003713 if (Info.ParseError)
3714 return true;
3715
Eli Friedman2128aae2012-10-22 23:58:19 +00003716 if (Info.Opcode != ~0U) {
3717 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003718
3719 // Build the list of clobbers, outputs and inputs.
Eli Friedman2128aae2012-10-22 23:58:19 +00003720 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3721 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003722
3723 // Immediate.
3724 if (Operand->isImm()) {
Chad Rosierefcb3d92012-10-26 18:04:20 +00003725 if (Operand->needAsmRewrite())
3726 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3727 Operand->getStartLoc()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003728 continue;
3729 }
3730
3731 // Register operand.
Chad Rosierc0a14b82012-10-24 17:22:29 +00003732 if (Operand->isReg() && !Operand->isOffsetOf()) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003733 unsigned NumDefs = Desc.getNumDefs();
3734 // Clobber.
3735 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3736 std::string Reg;
3737 raw_string_ostream OS(Reg);
3738 IP->printRegName(OS, Operand->getReg());
3739 ClobberRegs.insert(StringRef(OS.str()));
3740 }
3741 continue;
3742 }
3743
3744 // Expr/Input or Output.
Chad Rosier32989592012-10-18 20:27:15 +00003745 unsigned Size;
3746 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3747 Size);
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003748 if (OpDecl) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003749 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierc0a14b82012-10-24 17:22:29 +00003750 if (!Operand->isOffsetOf() && Operand->needSizeDirective())
Chad Rosier4e472d22012-10-20 01:02:45 +00003751 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
Chad Rosierefcb3d92012-10-26 18:04:20 +00003752 Operand->getStartLoc(),
3753 /*Len*/0,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003754 Operand->getMemSize()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003755 if (isOutput) {
3756 std::string Constraint = "=";
3757 ++InputIdx;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003758 OutputDecls.push_back(OpDecl);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003759 OutputDeclsOffsetOf.push_back(Operand->isOffsetOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003760 Constraint += Operand->getConstraint().str();
3761 OutputConstraints.push_back(Constraint);
Chad Rosier4e472d22012-10-20 01:02:45 +00003762 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003763 Operand->getStartLoc(),
3764 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003765 } else {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003766 InputDecls.push_back(OpDecl);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003767 InputDeclsOffsetOf.push_back(Operand->isOffsetOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003768 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosier4e472d22012-10-20 01:02:45 +00003769 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003770 Operand->getStartLoc(),
3771 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003772 }
3773 }
3774 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00003775 }
3776 }
3777
3778 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003779 NumOutputs = OutputDecls.size();
3780 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00003781
3782 // Set the unique clobbers.
3783 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3784 E = ClobberRegs.end(); I != E; ++I)
3785 Clobbers.push_back(*I);
3786
3787 // Merge the various outputs and inputs. Output are expected first.
3788 if (NumOutputs || NumInputs) {
3789 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003790 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003791 Constraints.resize(NumExprs);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003792 // FIXME: Constraints are hard coded to 'm', but we need an 'r'
3793 // constraint for offsetof. This needs to be cleaned up!
Chad Rosierb1f8c132012-10-18 15:49:34 +00003794 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003795 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsOffsetOf[i]);
3796 Constraints[i] = OutputDeclsOffsetOf[i] ? "=r" : OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003797 }
3798 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003799 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsOffsetOf[i]);
3800 Constraints[j] = InputDeclsOffsetOf[i] ? "r" : InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003801 }
3802 }
3803
3804 // Build the IR assembly string.
3805 std::string AsmStringIR;
Chad Rosier4e472d22012-10-20 01:02:45 +00003806 AsmRewriteKind PrevKind = AOK_Imm;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003807 raw_string_ostream OS(AsmStringIR);
3808 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
Chad Rosier4e472d22012-10-20 01:02:45 +00003809 for (SmallVectorImpl<struct AsmRewrite>::iterator
Chad Rosierb1f8c132012-10-18 15:49:34 +00003810 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3811 const char *Loc = (*I).Loc.getPointer();
Chad Rosier96d58e62012-10-19 20:57:14 +00003812
Chad Rosier4e472d22012-10-20 01:02:45 +00003813 AsmRewriteKind Kind = (*I).Kind;
Chad Rosier96d58e62012-10-19 20:57:14 +00003814
3815 // Emit everything up to the immediate/expression. If the previous rewrite
3816 // was a size directive, then this has already been done.
3817 if (PrevKind != AOK_SizeDirective)
3818 OS << StringRef(Start, Loc - Start);
3819 PrevKind = Kind;
3820
Chad Rosier5a719fc2012-10-23 17:43:43 +00003821 // Skip the original expression.
3822 if (Kind == AOK_Skip) {
3823 Start = Loc + (*I).Len;
3824 continue;
3825 }
3826
Chad Rosierb1f8c132012-10-18 15:49:34 +00003827 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00003828 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003829 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003830 case AOK_Imm:
Chad Rosierefcb3d92012-10-26 18:04:20 +00003831 OS << Twine("$$");
3832 OS << (*I).Val;
3833 break;
3834 case AOK_ImmPrefix:
3835 OS << Twine("$$");
Chad Rosierb1f8c132012-10-18 15:49:34 +00003836 break;
3837 case AOK_Input:
3838 OS << '$';
3839 OS << InputIdx++;
3840 break;
3841 case AOK_Output:
3842 OS << '$';
3843 OS << OutputIdx++;
3844 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00003845 case AOK_SizeDirective:
Chad Rosier6a020a72012-10-25 20:41:34 +00003846 switch((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00003847 default: break;
3848 case 8: OS << "byte ptr "; break;
3849 case 16: OS << "word ptr "; break;
3850 case 32: OS << "dword ptr "; break;
3851 case 64: OS << "qword ptr "; break;
3852 case 80: OS << "xword ptr "; break;
3853 case 128: OS << "xmmword ptr "; break;
3854 case 256: OS << "ymmword ptr "; break;
3855 }
Eli Friedman2128aae2012-10-22 23:58:19 +00003856 break;
3857 case AOK_Emit:
3858 OS << ".byte";
3859 break;
Chad Rosier6a020a72012-10-25 20:41:34 +00003860 case AOK_DotOperator:
3861 OS << (*I).Val;
3862 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003863 }
Chad Rosier96d58e62012-10-19 20:57:14 +00003864
Chad Rosierb1f8c132012-10-18 15:49:34 +00003865 // Skip the original expression.
Chad Rosier96d58e62012-10-19 20:57:14 +00003866 if (Kind != AOK_SizeDirective)
3867 Start = Loc + (*I).Len;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003868 }
3869
3870 // Emit the remainder of the asm string.
3871 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
3872 if (Start != AsmEnd)
3873 OS << StringRef(Start, AsmEnd - Start);
3874
3875 AsmString = OS.str();
3876 return false;
3877}
3878
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003879/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003880MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003881 MCContext &C, MCStreamer &Out,
3882 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003883 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003884}