blob: 85d31872a7394ac8a9b9b86cd7d2ff782cd2d4ca [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(),
Eric Christopher6c583142012-12-18 00:31:01 +0000616 StringRef(),
617 getContext().getMainFileName());
Kevin Enderby613b7572011-11-01 22:27:22 +0000618 }
619
Chris Lattnerb717fb02009-07-02 21:53:43 +0000620 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000621 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000622 ParseStatementInfo Info;
623 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000624
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000625 // We had an error, validate that one was emitted and recover by skipping to
626 // the next line.
627 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000628 EatToEndOfStatement();
629 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000630
631 if (TheCondState.TheCond != StartingCondState.TheCond ||
632 TheCondState.Ignore != StartingCondState.Ignore)
633 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000634
635 // Check to see there are no empty DwarfFile slots.
636 const std::vector<MCDwarfFile *> &MCDwarfFiles =
637 getContext().getMCDwarfFiles();
638 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000639 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000640 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000641 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000642
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000643 // Check to see that all assembler local symbols were actually defined.
644 // Targets that don't do subsections via symbols may not want this, though,
645 // so conservatively exclude them. Only do this if we're finalizing, though,
646 // as otherwise we won't necessarilly have seen everything yet.
647 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
648 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
649 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
650 e = Symbols.end();
651 i != e; ++i) {
652 MCSymbol *Sym = i->getValue();
653 // Variable symbols may not be marked as defined, so check those
654 // explicitly. If we know it's a variable, we have a definition for
655 // the purposes of this check.
656 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
657 // FIXME: We would really like to refer back to where the symbol was
658 // first referenced for a source location. We need to add something
659 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000660 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
661 "assembler local symbol '" + Sym->getName() +
662 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000663 }
664 }
665
666
Chris Lattner79180e22010-04-05 23:15:42 +0000667 // Finalize the output stream if there are no errors and if the client wants
668 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000669 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000670 Out.Finish();
671
Chris Lattnerb717fb02009-07-02 21:53:43 +0000672 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000673}
674
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000675void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000676 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000677 TokError("expected section directive before assembly directive");
678 Out.SwitchSection(Ctx.getMachOSection(
679 "__TEXT", "__text",
680 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
681 0, SectionKind::getText()));
682 }
683}
684
Chris Lattner2cf5f142009-06-22 01:29:09 +0000685/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
686void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000687 while (Lexer.isNot(AsmToken::EndOfStatement) &&
688 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000689 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000690
Chris Lattner2cf5f142009-06-22 01:29:09 +0000691 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000692 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000693 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000694}
695
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000696StringRef AsmParser::ParseStringToEndOfStatement() {
697 const char *Start = getTok().getLoc().getPointer();
698
699 while (Lexer.isNot(AsmToken::EndOfStatement) &&
700 Lexer.isNot(AsmToken::Eof))
701 Lex();
702
703 const char *End = getTok().getLoc().getPointer();
704 return StringRef(Start, End - Start);
705}
Chris Lattnerc4193832009-06-22 05:51:26 +0000706
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000707StringRef AsmParser::ParseStringToComma() {
708 const char *Start = getTok().getLoc().getPointer();
709
710 while (Lexer.isNot(AsmToken::EndOfStatement) &&
711 Lexer.isNot(AsmToken::Comma) &&
712 Lexer.isNot(AsmToken::Eof))
713 Lex();
714
715 const char *End = getTok().getLoc().getPointer();
716 return StringRef(Start, End - Start);
717}
718
Chris Lattner74ec1a32009-06-22 06:32:03 +0000719/// ParseParenExpr - Parse a paren expression and return it.
720/// NOTE: This assumes the leading '(' has already been consumed.
721///
722/// parenexpr ::= expr)
723///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000724bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000725 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000726 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000727 return TokError("expected ')' in parentheses expression");
Chris Lattnerb4307b32010-01-15 19:28:38 +0000728 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000729 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000730 return false;
731}
Chris Lattnerc4193832009-06-22 05:51:26 +0000732
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000733/// ParseBracketExpr - Parse a bracket expression and return it.
734/// NOTE: This assumes the leading '[' has already been consumed.
735///
736/// bracketexpr ::= expr]
737///
738bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
739 if (ParseExpression(Res)) return true;
740 if (Lexer.isNot(AsmToken::RBrac))
741 return TokError("expected ']' in brackets expression");
742 EndLoc = Lexer.getLoc();
743 Lex();
744 return false;
745}
746
Chris Lattner74ec1a32009-06-22 06:32:03 +0000747/// ParsePrimaryExpr - Parse a primary expression and return it.
748/// primaryexpr ::= (parenexpr
749/// primaryexpr ::= symbol
750/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000751/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000752/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000753bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000754 switch (Lexer.getKind()) {
755 default:
756 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000757 // If we have an error assume that we've already handled it.
758 case AsmToken::Error:
759 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000760 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000761 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000762 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000763 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000764 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000765 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000766 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000767 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000768 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000769 EndLoc = Lexer.getLoc();
770
771 StringRef Identifier;
772 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000773 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000774
Daniel Dunbarfffff912009-10-16 01:34:54 +0000775 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000776 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000777 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000778
779 // Lookup the symbol variant if used.
780 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000781 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000782 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000783 if (Variant == MCSymbolRefExpr::VK_Invalid) {
784 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000785 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000786 }
787 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000788
Daniel Dunbarfffff912009-10-16 01:34:54 +0000789 // If this is an absolute variable reference, substitute it now to preserve
790 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000791 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000792 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000793 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000794
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000795 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000796 return false;
797 }
798
799 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000800 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000801 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000802 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000803 case AsmToken::Integer: {
804 SMLoc Loc = getTok().getLoc();
805 int64_t IntVal = getTok().getIntVal();
806 Res = MCConstantExpr::Create(IntVal, getContext());
Chris Lattnerb4307b32010-01-15 19:28:38 +0000807 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000808 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000809 // Look for 'b' or 'f' following an Integer as a directional label
810 if (Lexer.getKind() == AsmToken::Identifier) {
811 StringRef IDVal = getTok().getString();
812 if (IDVal == "f" || IDVal == "b"){
813 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
814 IDVal == "f" ? 1 : 0);
815 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
816 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000817 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000818 return Error(Loc, "invalid reference to undefined symbol");
819 EndLoc = Lexer.getLoc();
820 Lex(); // Eat identifier.
821 }
822 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000823 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000824 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000825 case AsmToken::Real: {
826 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000827 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000828 Res = MCConstantExpr::Create(IntVal, getContext());
829 Lex(); // Eat token.
830 return false;
831 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000832 case AsmToken::Dot: {
833 // This is a '.' reference, which references the current PC. Emit a
834 // temporary label to the streamer and refer to it.
835 MCSymbol *Sym = Ctx.CreateTempSymbol();
836 Out.EmitLabel(Sym);
837 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
838 EndLoc = Lexer.getLoc();
839 Lex(); // Eat identifier.
840 return false;
841 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000842 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000843 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000844 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000845 case AsmToken::LBrac:
846 if (!PlatformParser->HasBracketExpressions())
847 return TokError("brackets expression not supported on this target");
848 Lex(); // Eat the '['.
849 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000850 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000851 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000852 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000853 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000854 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000855 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000856 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000857 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000858 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000859 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000860 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000861 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000862 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000863 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000864 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000865 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000866 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000867 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000868 }
869}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000870
Chris Lattnerb4307b32010-01-15 19:28:38 +0000871bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000872 SMLoc EndLoc;
873 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000874}
875
Daniel Dunbarcceba832010-09-17 02:47:07 +0000876const MCExpr *
877AsmParser::ApplyModifierToExpr(const MCExpr *E,
878 MCSymbolRefExpr::VariantKind Variant) {
879 // Recurse over the given expression, rebuilding it to apply the given variant
880 // if there is exactly one symbol.
881 switch (E->getKind()) {
882 case MCExpr::Target:
883 case MCExpr::Constant:
884 return 0;
885
886 case MCExpr::SymbolRef: {
887 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
888
889 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
890 TokError("invalid variant on expression '" +
891 getTok().getIdentifier() + "' (already modified)");
892 return E;
893 }
894
895 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
896 }
897
898 case MCExpr::Unary: {
899 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
900 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
901 if (!Sub)
902 return 0;
903 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
904 }
905
906 case MCExpr::Binary: {
907 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
908 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
909 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
910
911 if (!LHS && !RHS)
912 return 0;
913
914 if (!LHS) LHS = BE->getLHS();
915 if (!RHS) RHS = BE->getRHS();
916
917 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
918 }
919 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000920
Craig Topper85814382012-02-07 05:05:23 +0000921 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000922}
923
Chris Lattner74ec1a32009-06-22 06:32:03 +0000924/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000925///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000926/// expr ::= expr &&,|| expr -> lowest.
927/// expr ::= expr |,^,&,! expr
928/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
929/// expr ::= expr <<,>> expr
930/// expr ::= expr +,- expr
931/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000932/// expr ::= primaryexpr
933///
Chris Lattner54482b42010-01-15 19:39:23 +0000934bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000935 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000936 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000937 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
938 return true;
939
Daniel Dunbarcceba832010-09-17 02:47:07 +0000940 // As a special case, we support 'a op b @ modifier' by rewriting the
941 // expression to include the modifier. This is inefficient, but in general we
942 // expect users to use 'a@modifier op b'.
943 if (Lexer.getKind() == AsmToken::At) {
944 Lex();
945
946 if (Lexer.isNot(AsmToken::Identifier))
947 return TokError("unexpected symbol modifier following '@'");
948
949 MCSymbolRefExpr::VariantKind Variant =
950 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
951 if (Variant == MCSymbolRefExpr::VK_Invalid)
952 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
953
954 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
955 if (!ModifiedRes) {
956 return TokError("invalid modifier '" + getTok().getIdentifier() +
957 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000958 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000959
Daniel Dunbarcceba832010-09-17 02:47:07 +0000960 Res = ModifiedRes;
961 Lex();
962 }
963
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000964 // Try to constant fold it up front, if possible.
965 int64_t Value;
966 if (Res->EvaluateAsAbsolute(Value))
967 Res = MCConstantExpr::Create(Value, getContext());
968
969 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000970}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000971
Chris Lattnerb4307b32010-01-15 19:28:38 +0000972bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000973 Res = 0;
974 return ParseParenExpr(Res, EndLoc) ||
975 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000976}
977
Daniel Dunbar475839e2009-06-29 20:37:27 +0000978bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000979 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000980
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000981 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000982 if (ParseExpression(Expr))
983 return true;
984
Daniel Dunbare00b0112009-10-16 01:57:52 +0000985 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000986 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000987
988 return false;
989}
990
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000991static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000992 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000993 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000994 default:
995 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000996
Jim Grosbachfbe16812011-08-20 16:24:13 +0000997 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000998 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000999 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001000 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001001 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001002 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001003 return 1;
1004
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001005
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001006 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +00001007 //
1008 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +00001009 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001010 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001011 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001012 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001013 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001014 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001015 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001016 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001017 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001018
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001019 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001020 case AsmToken::EqualEqual:
1021 Kind = MCBinaryExpr::EQ;
1022 return 3;
1023 case AsmToken::ExclaimEqual:
1024 case AsmToken::LessGreater:
1025 Kind = MCBinaryExpr::NE;
1026 return 3;
1027 case AsmToken::Less:
1028 Kind = MCBinaryExpr::LT;
1029 return 3;
1030 case AsmToken::LessEqual:
1031 Kind = MCBinaryExpr::LTE;
1032 return 3;
1033 case AsmToken::Greater:
1034 Kind = MCBinaryExpr::GT;
1035 return 3;
1036 case AsmToken::GreaterEqual:
1037 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001038 return 3;
1039
Jim Grosbachfbe16812011-08-20 16:24:13 +00001040 // Intermediate Precedence: <<, >>
1041 case AsmToken::LessLess:
1042 Kind = MCBinaryExpr::Shl;
1043 return 4;
1044 case AsmToken::GreaterGreater:
1045 Kind = MCBinaryExpr::Shr;
1046 return 4;
1047
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001048 // High Intermediate Precedence: +, -
1049 case AsmToken::Plus:
1050 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001051 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001052 case AsmToken::Minus:
1053 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001054 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001055
Jim Grosbachfbe16812011-08-20 16:24:13 +00001056 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001057 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001058 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001059 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001060 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001061 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001062 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001063 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001064 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001065 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001066 }
1067}
1068
1069
1070/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1071/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001072bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1073 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001074 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001075 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001076 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001077
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001078 // If the next token is lower precedence than we are allowed to eat, return
1079 // successfully with what we ate already.
1080 if (TokPrec < Precedence)
1081 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001082
Sean Callanan79ed1a82010-01-19 20:22:31 +00001083 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001084
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001085 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001086 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001087 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001088
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001089 // If BinOp binds less tightly with RHS than the operator after RHS, let
1090 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001091 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001092 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001093 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001094 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001095 }
1096
Daniel Dunbar475839e2009-06-29 20:37:27 +00001097 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001098 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001099 }
1100}
1101
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001102/// ParseStatement:
1103/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001104/// ::= Label* Directive ...Operands... EndOfStatement
1105/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001106bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001107 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001108 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001109 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001110 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001111 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001112
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001113 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001114 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001115 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001116 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001117 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001118 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001119 if (Lexer.is(AsmToken::Hash))
1120 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001121
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001122 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001123 if (Lexer.is(AsmToken::Integer)) {
1124 LocalLabelVal = getTok().getIntVal();
1125 if (LocalLabelVal < 0) {
1126 if (!TheCondState.Ignore)
1127 return TokError("unexpected token at start of statement");
1128 IDVal = "";
1129 }
1130 else {
1131 IDVal = getTok().getString();
1132 Lex(); // Consume the integer token to be used as an identifier token.
1133 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001134 if (!TheCondState.Ignore)
1135 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001136 }
1137 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001138
1139 } else if (Lexer.is(AsmToken::Dot)) {
1140 // Treat '.' as a valid identifier in this context.
1141 Lex();
1142 IDVal = ".";
1143
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001144 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001145 if (!TheCondState.Ignore)
1146 return TokError("unexpected token at start of statement");
1147 IDVal = "";
1148 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001149
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001150
Chris Lattner7834fac2010-04-17 18:14:27 +00001151 // Handle conditional assembly here before checking for skipping. We
1152 // have to do this so that .endif isn't skipped in a ".if 0" block for
1153 // example.
1154 if (IDVal == ".if")
1155 return ParseDirectiveIf(IDLoc);
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00001156 if (IDVal == ".ifb")
1157 return ParseDirectiveIfb(IDLoc, true);
1158 if (IDVal == ".ifnb")
1159 return ParseDirectiveIfb(IDLoc, false);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00001160 if (IDVal == ".ifc")
1161 return ParseDirectiveIfc(IDLoc, true);
1162 if (IDVal == ".ifnc")
1163 return ParseDirectiveIfc(IDLoc, false);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00001164 if (IDVal == ".ifdef")
1165 return ParseDirectiveIfdef(IDLoc, true);
1166 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1167 return ParseDirectiveIfdef(IDLoc, false);
Chris Lattner7834fac2010-04-17 18:14:27 +00001168 if (IDVal == ".elseif")
1169 return ParseDirectiveElseIf(IDLoc);
1170 if (IDVal == ".else")
1171 return ParseDirectiveElse(IDLoc);
1172 if (IDVal == ".endif")
1173 return ParseDirectiveEndIf(IDLoc);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001174
Chris Lattner7834fac2010-04-17 18:14:27 +00001175 // If we are in a ".if 0" block, ignore this statement.
Chad Rosier17feeec2012-10-20 00:47:08 +00001176 if (TheCondState.Ignore) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001177 EatToEndOfStatement();
1178 return false;
1179 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001180
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001181 // FIXME: Recurse on local labels?
1182
1183 // See what kind of statement we have.
1184 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001185 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001186 CheckForValidSection();
1187
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001188 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001189 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001190
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001191 // Diagnose attempt to use '.' as a label.
1192 if (IDVal == ".")
1193 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1194
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001195 // Diagnose attempt to use a variable as a label.
1196 //
1197 // FIXME: Diagnostics. Note the location of the definition as a label.
1198 // FIXME: This doesn't diagnose assignment to a symbol which has been
1199 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001200 MCSymbol *Sym;
1201 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001202 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001203 else
1204 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001205 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001206 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001207
Daniel Dunbar959fd882009-08-26 22:13:22 +00001208 // Emit the label.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001209 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001210
Kevin Enderby94c2e852011-12-09 18:09:40 +00001211 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001212 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001213 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001214 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1215 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001216
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001217 // Consume any end of statement token, if present, to avoid spurious
1218 // AddBlankLine calls().
1219 if (Lexer.is(AsmToken::EndOfStatement)) {
1220 Lex();
1221 if (Lexer.is(AsmToken::Eof))
1222 return false;
1223 }
1224
Eli Friedman2128aae2012-10-22 23:58:19 +00001225 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001226 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001227
Daniel Dunbar3f872332009-07-28 16:08:33 +00001228 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001229 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001230 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001231
Nico Weber4c4c7322011-01-28 03:04:41 +00001232 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001233
1234 default: // Normal instruction or directive.
1235 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001236 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001237
1238 // If macros are enabled, check to see if this is a macro instantiation.
1239 if (MacrosEnabled)
1240 if (const Macro *M = MacroMap.lookup(IDVal))
1241 return HandleMacroEntry(IDVal, IDLoc, M);
1242
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001243 // Otherwise, we have a normal instruction or directive.
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001244 if (IDVal[0] == '.' && IDVal != ".") {
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001245
1246 // Target hook for parsing target specific directives.
1247 if (!getTargetParser().ParseDirective(ID))
1248 return false;
1249
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001250 // Assembler features
Roman Divacky50e7a782010-10-28 16:22:58 +00001251 if (IDVal == ".set" || IDVal == ".equ")
Nico Weber4c4c7322011-01-28 03:04:41 +00001252 return ParseDirectiveSet(IDVal, true);
1253 if (IDVal == ".equiv")
1254 return ParseDirectiveSet(IDVal, false);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001255
Daniel Dunbara0d14262009-06-24 23:30:00 +00001256 // Data directives
1257
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001258 if (IDVal == ".ascii")
Rafael Espindola787c3372010-10-28 20:02:27 +00001259 return ParseDirectiveAscii(IDVal, false);
1260 if (IDVal == ".asciz" || IDVal == ".string")
1261 return ParseDirectiveAscii(IDVal, true);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001262
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001263 if (IDVal == ".byte")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001264 return ParseDirectiveValue(1);
Kevin Enderby9c656452009-09-10 20:51:44 +00001265 if (IDVal == ".short")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001266 return ParseDirectiveValue(2);
Rafael Espindolacc3acee2010-11-01 15:29:07 +00001267 if (IDVal == ".value")
1268 return ParseDirectiveValue(2);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001269 if (IDVal == ".2byte")
1270 return ParseDirectiveValue(2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001271 if (IDVal == ".long")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001272 return ParseDirectiveValue(4);
Rafael Espindola435279b2010-11-17 16:24:40 +00001273 if (IDVal == ".int")
1274 return ParseDirectiveValue(4);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001275 if (IDVal == ".4byte")
1276 return ParseDirectiveValue(4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001277 if (IDVal == ".quad")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001278 return ParseDirectiveValue(8);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001279 if (IDVal == ".8byte")
1280 return ParseDirectiveValue(8);
Roman Divacky14e66552011-01-28 14:20:32 +00001281 if (IDVal == ".single" || IDVal == ".float")
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001282 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1283 if (IDVal == ".double")
1284 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001285
Eli Friedman5d68ec22010-07-19 04:17:25 +00001286 if (IDVal == ".align") {
1287 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1288 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1289 }
1290 if (IDVal == ".align32") {
1291 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1292 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1293 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001294 if (IDVal == ".balign")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001295 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001296 if (IDVal == ".balignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001297 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001298 if (IDVal == ".balignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001299 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001300 if (IDVal == ".p2align")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001301 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001302 if (IDVal == ".p2alignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001303 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001304 if (IDVal == ".p2alignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001305 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1306
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001307 if (IDVal == ".org")
Daniel Dunbarc238b582009-06-25 22:44:51 +00001308 return ParseDirectiveOrg();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001309
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001310 if (IDVal == ".fill")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001311 return ParseDirectiveFill();
Rafael Espindolace8463f2011-04-07 20:26:23 +00001312 if (IDVal == ".space" || IDVal == ".skip")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001313 return ParseDirectiveSpace();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001314 if (IDVal == ".zero")
1315 return ParseDirectiveZero();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001316
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001317 // Symbol attribute directives
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001318
Benjamin Kramere14a3c52012-05-12 11:18:59 +00001319 if (IDVal == ".extern") {
1320 EatToEndOfStatement(); // .extern is the default, ignore it.
1321 return false;
1322 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001323 if (IDVal == ".globl" || IDVal == ".global")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001324 return ParseDirectiveSymbolAttribute(MCSA_Global);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001325 if (IDVal == ".indirect_symbol")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001326 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001327 if (IDVal == ".lazy_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001328 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001329 if (IDVal == ".no_dead_strip")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001330 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Kevin Enderbye8e98d72010-11-19 18:39:33 +00001331 if (IDVal == ".symbol_resolver")
1332 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001333 if (IDVal == ".private_extern")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001334 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001335 if (IDVal == ".reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001336 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001337 if (IDVal == ".weak_definition")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001338 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001339 if (IDVal == ".weak_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001340 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Kevin Enderbyf59cac52010-07-08 17:22:42 +00001341 if (IDVal == ".weak_def_can_be_hidden")
1342 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001343
Hans Wennborg5cc64912011-06-18 13:51:54 +00001344 if (IDVal == ".comm" || IDVal == ".common")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001345 return ParseDirectiveComm(/*IsLocal=*/false);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001346 if (IDVal == ".lcomm")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001347 return ParseDirectiveComm(/*IsLocal=*/true);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001348
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001349 if (IDVal == ".abort")
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001350 return ParseDirectiveAbort();
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001351 if (IDVal == ".include")
Kevin Enderby1f049b22009-07-14 23:21:55 +00001352 return ParseDirectiveInclude();
Kevin Enderbyc55acca2011-12-14 21:47:48 +00001353 if (IDVal == ".incbin")
1354 return ParseDirectiveIncbin();
Kevin Enderbya5c78322009-07-13 21:03:15 +00001355
Benjamin Kramer5cdf0ad2012-05-12 11:19:04 +00001356 if (IDVal == ".code16" || IDVal == ".code16gcc")
Roman Divackyf6fbd842011-01-31 20:56:49 +00001357 return TokError(Twine(IDVal) + " not supported yet");
Roman Divackycb727802011-01-28 19:29:48 +00001358
Rafael Espindola761cb062012-06-03 23:57:14 +00001359 // Macro-like directives
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001360 if (IDVal == ".rept")
1361 return ParseDirectiveRept(IDLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001362 if (IDVal == ".irp")
1363 return ParseDirectiveIrp(IDLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00001364 if (IDVal == ".irpc")
1365 return ParseDirectiveIrpc(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001366 if (IDVal == ".endr")
Rafael Espindola761cb062012-06-03 23:57:14 +00001367 return ParseDirectiveEndr(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001368
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001369 // Look up the handler in the handler table.
1370 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1371 DirectiveMap.lookup(IDVal);
1372 if (Handler.first)
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +00001373 return (*Handler.second)(Handler.first, IDVal, IDLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001374
Kevin Enderby9c656452009-09-10 20:51:44 +00001375
Jim Grosbach686c0182012-05-01 18:38:27 +00001376 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001377 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001378
Eli Friedman2128aae2012-10-22 23:58:19 +00001379 // _emit
1380 if (ParsingInlineAsm && IDVal == "_emit")
1381 return ParseDirectiveEmit(IDLoc, Info);
1382
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001383 CheckForValidSection();
1384
Chris Lattnera7f13542010-05-19 23:34:33 +00001385 // Canonicalize the opcode to lower case.
Chad Rosier8f138d12012-10-15 17:19:13 +00001386 SmallString<128> OpcodeStr;
Chris Lattnera7f13542010-05-19 23:34:33 +00001387 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
Chad Rosier8f138d12012-10-15 17:19:13 +00001388 OpcodeStr.push_back(tolower(IDVal[i]));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001389
Chad Rosier6a020a72012-10-25 20:41:34 +00001390 ParseInstructionInfo IInfo(Info.AsmRewrites);
1391 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1392 IDLoc,Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001393 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001394
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001395 // Dump the parsed representation, if requested.
1396 if (getShowParsedOperands()) {
1397 SmallString<256> Str;
1398 raw_svector_ostream OS(Str);
1399 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001400 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001401 if (i != 0)
1402 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001403 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001404 }
1405 OS << "]";
1406
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001407 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001408 }
1409
Kevin Enderby613b7572011-11-01 22:27:22 +00001410 // If we are generating dwarf for assembly source files and the current
1411 // section is the initial text section then generate a .loc directive for
1412 // the instruction.
1413 if (!HadError && getContext().getGenDwarfForAssembly() &&
Eric Christopher2318ba12012-12-18 00:30:54 +00001414 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001415
1416 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1417
1418 // If we previously parsed a cpp hash file line comment then make sure the
1419 // current Dwarf File is for the CppHashFilename if not then emit the
1420 // Dwarf File table for it and adjust the line number for the .loc.
1421 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1422 getContext().getMCDwarfFiles();
1423 if (CppHashFilename.size() != 0) {
1424 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1425 CppHashFilename)
Eric Christopher2318ba12012-12-18 00:30:54 +00001426 getStreamer().EmitDwarfFileDirective(
1427 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001428
Kevin Enderby32c1a822012-11-05 21:55:41 +00001429 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
Kevin Enderby938482f2012-11-01 17:31:35 +00001430 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1431 }
1432
Kevin Enderby613b7572011-11-01 22:27:22 +00001433 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001434 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001435 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001436 StringRef());
1437 }
1438
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001439 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001440 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001441 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001442 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1443 Info.ParsedOperands,
1444 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001445 ParsingInlineAsm);
1446 }
Chris Lattner98986712010-01-14 22:21:20 +00001447
Chris Lattnercbf8a982010-09-11 16:18:25 +00001448 // Don't skip the rest of the line, the instruction parser is responsible for
1449 // that.
1450 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001451}
Chris Lattner9a023f72009-06-24 04:43:34 +00001452
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001453/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1454/// since they may not be able to be tokenized to get to the end of line token.
1455void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001456 if (!Lexer.is(AsmToken::EndOfStatement))
1457 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001458 // Eat EOL.
1459 Lex();
1460}
1461
1462/// ParseCppHashLineFilenameComment as this:
1463/// ::= # number "filename"
1464/// or just as a full line comment if it doesn't have a number and a string.
1465bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1466 Lex(); // Eat the hash token.
1467
1468 if (getLexer().isNot(AsmToken::Integer)) {
1469 // Consume the line since in cases it is not a well-formed line directive,
1470 // as if were simply a full line comment.
1471 EatToEndOfLine();
1472 return false;
1473 }
1474
1475 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001476 Lex();
1477
1478 if (getLexer().isNot(AsmToken::String)) {
1479 EatToEndOfLine();
1480 return false;
1481 }
1482
1483 StringRef Filename = getTok().getString();
1484 // Get rid of the enclosing quotes.
1485 Filename = Filename.substr(1, Filename.size()-2);
1486
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001487 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1488 CppHashLoc = L;
1489 CppHashFilename = Filename;
1490 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001491 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001492
1493 // Ignore any trailing characters, they're just comment.
1494 EatToEndOfLine();
1495 return false;
1496}
1497
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001498/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001499/// for the Filename and LineNo if any in the diagnostic.
1500void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1501 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1502 raw_ostream &OS = errs();
1503
1504 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1505 const SMLoc &DiagLoc = Diag.getLoc();
1506 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1507 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1508
1509 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1510 // before printing the message.
1511 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001512 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001513 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1514 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1515 }
1516
Eric Christopher2318ba12012-12-18 00:30:54 +00001517 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001518 // manager changed or buffer changed (like in a nested include) then just
1519 // print the normal diagnostic using its Filename and LineNo.
1520 if (!Parser->CppHashLineNumber ||
1521 &DiagSrcMgr != &Parser->SrcMgr ||
1522 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001523 if (Parser->SavedDiagHandler)
1524 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1525 else
1526 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001527 return;
1528 }
1529
Eric Christopher2318ba12012-12-18 00:30:54 +00001530 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001531 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1532 // the diagnostic.
1533 const std::string Filename = Parser->CppHashFilename;
1534
1535 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1536 int CppHashLocLineNo =
1537 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1538 int LineNo = Parser->CppHashLineNumber - 1 +
1539 (DiagLocLineNo - CppHashLocLineNo);
1540
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001541 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1542 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001543 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001544 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001545
Benjamin Kramer04a04262011-10-16 10:48:29 +00001546 if (Parser->SavedDiagHandler)
1547 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1548 else
1549 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001550}
1551
Rafael Espindola799aacf2012-08-21 18:29:30 +00001552// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1553// difference being that that function accepts '@' as part of identifiers and
1554// we can't do that. AsmLexer.cpp should probably be changed to handle
1555// '@' as a special case when needed.
1556static bool isIdentifierChar(char c) {
1557 return isalnum(c) || c == '_' || c == '$' || c == '.';
1558}
1559
Rafael Espindola761cb062012-06-03 23:57:14 +00001560bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +00001561 const MacroParameters &Parameters,
1562 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001563 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001564 unsigned NParameters = Parameters.size();
1565 if (NParameters != 0 && NParameters != A.size())
1566 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001567
Preston Gurd7b6f2032012-09-19 20:36:12 +00001568 // A macro without parameters is handled differently on Darwin:
1569 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001570 while (!Body.empty()) {
1571 // Scan for the next substitution.
1572 std::size_t End = Body.size(), Pos = 0;
1573 for (; Pos != End; ++Pos) {
1574 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001575 if (!NParameters) {
1576 // This macro has no parameters, look for $0, $1, etc.
1577 if (Body[Pos] != '$' || Pos + 1 == End)
1578 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001579
Rafael Espindola65366442011-06-05 02:43:45 +00001580 char Next = Body[Pos + 1];
1581 if (Next == '$' || Next == 'n' || isdigit(Next))
1582 break;
1583 } else {
1584 // This macro has parameters, look for \foo, \bar, etc.
1585 if (Body[Pos] == '\\' && Pos + 1 != End)
1586 break;
1587 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001588 }
1589
1590 // Add the prefix.
1591 OS << Body.slice(0, Pos);
1592
1593 // Check if we reached the end.
1594 if (Pos == End)
1595 break;
1596
Rafael Espindola65366442011-06-05 02:43:45 +00001597 if (!NParameters) {
1598 switch (Body[Pos+1]) {
1599 // $$ => $
1600 case '$':
1601 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001602 break;
1603
Rafael Espindola65366442011-06-05 02:43:45 +00001604 // $n => number of arguments
1605 case 'n':
1606 OS << A.size();
1607 break;
1608
1609 // $[0-9] => argument
1610 default: {
1611 // Missing arguments are ignored.
1612 unsigned Index = Body[Pos+1] - '0';
1613 if (Index >= A.size())
1614 break;
1615
1616 // Otherwise substitute with the token values, with spaces eliminated.
Rafael Espindola28c1f6662012-06-03 22:41:23 +00001617 for (MacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001618 ie = A[Index].end(); it != ie; ++it)
1619 OS << it->getString();
1620 break;
1621 }
1622 }
1623 Pos += 2;
1624 } else {
1625 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001626 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001627 ++I;
1628
1629 const char *Begin = Body.data() + Pos +1;
1630 StringRef Argument(Begin, I - (Pos +1));
1631 unsigned Index = 0;
1632 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001633 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001634 break;
1635
Preston Gurd7b6f2032012-09-19 20:36:12 +00001636 if (Index == NParameters) {
1637 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1638 Pos += 3;
1639 else {
1640 OS << '\\' << Argument;
1641 Pos = I;
1642 }
1643 } else {
1644 for (MacroArgument::const_iterator it = A[Index].begin(),
1645 ie = A[Index].end(); it != ie; ++it)
1646 if (it->getKind() == AsmToken::String)
1647 OS << it->getStringContents();
1648 else
1649 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001650
Preston Gurd7b6f2032012-09-19 20:36:12 +00001651 Pos += 1 + Argument.size();
1652 }
Rafael Espindola65366442011-06-05 02:43:45 +00001653 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001654 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001655 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001656 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001657
Rafael Espindola65366442011-06-05 02:43:45 +00001658 return false;
1659}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001660
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001661MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL,
1662 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001663 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001664 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1665 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001666{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001667}
1668
Preston Gurd7b6f2032012-09-19 20:36:12 +00001669static bool IsOperator(AsmToken::TokenKind kind)
1670{
1671 switch (kind)
1672 {
1673 default:
1674 return false;
1675 case AsmToken::Plus:
1676 case AsmToken::Minus:
1677 case AsmToken::Tilde:
1678 case AsmToken::Slash:
1679 case AsmToken::Star:
1680 case AsmToken::Dot:
1681 case AsmToken::Equal:
1682 case AsmToken::EqualEqual:
1683 case AsmToken::Pipe:
1684 case AsmToken::PipePipe:
1685 case AsmToken::Caret:
1686 case AsmToken::Amp:
1687 case AsmToken::AmpAmp:
1688 case AsmToken::Exclaim:
1689 case AsmToken::ExclaimEqual:
1690 case AsmToken::Percent:
1691 case AsmToken::Less:
1692 case AsmToken::LessEqual:
1693 case AsmToken::LessLess:
1694 case AsmToken::LessGreater:
1695 case AsmToken::Greater:
1696 case AsmToken::GreaterEqual:
1697 case AsmToken::GreaterGreater:
1698 return true;
1699 }
1700}
1701
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001702/// ParseMacroArgument - Extract AsmTokens for a macro argument.
1703/// This is used for both default macro parameter values and the
1704/// arguments in macro invocations
Preston Gurd7b6f2032012-09-19 20:36:12 +00001705bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1706 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001707 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001708 unsigned AddTokens = 0;
1709
1710 // gas accepts arguments separated by whitespace, except on Darwin
1711 if (!IsDarwin)
1712 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001713
1714 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001715 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1716 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001717 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001718 }
1719
1720 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1721 // Spaces and commas cannot be mixed to delimit parameters
1722 if (ArgumentDelimiter == AsmToken::Eof)
1723 ArgumentDelimiter = AsmToken::Comma;
1724 else if (ArgumentDelimiter != AsmToken::Comma) {
1725 Lexer.setSkipSpace(true);
1726 return TokError("expected ' ' for macro argument separator");
1727 }
1728 break;
1729 }
1730
1731 if (Lexer.is(AsmToken::Space)) {
1732 Lex(); // Eat spaces
1733
1734 // Spaces can delimit parameters, but could also be part an expression.
1735 // If the token after a space is an operator, add the token and the next
1736 // one into this argument
1737 if (ArgumentDelimiter == AsmToken::Space ||
1738 ArgumentDelimiter == AsmToken::Eof) {
1739 if (IsOperator(Lexer.getKind())) {
1740 // Check to see whether the token is used as an operator,
1741 // or part of an identifier
1742 const char *NextChar = getTok().getEndLoc().getPointer() + 1;
1743 if (*NextChar == ' ')
1744 AddTokens = 2;
1745 }
1746
1747 if (!AddTokens && ParenLevel == 0) {
1748 if (ArgumentDelimiter == AsmToken::Eof &&
1749 !IsOperator(Lexer.getKind()))
1750 ArgumentDelimiter = AsmToken::Space;
1751 break;
1752 }
1753 }
1754 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001755
1756 // HandleMacroEntry relies on not advancing the lexer here
1757 // to be able to fill in the remaining default parameter values
1758 if (Lexer.is(AsmToken::EndOfStatement))
1759 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001760
1761 // Adjust the current parentheses level.
1762 if (Lexer.is(AsmToken::LParen))
1763 ++ParenLevel;
1764 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1765 --ParenLevel;
1766
1767 // Append the token to the current argument list.
1768 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001769 if (AddTokens)
1770 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001771 Lex();
1772 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001773
1774 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001775 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001776 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001777 return false;
1778}
1779
1780// Parse the macro instantiation arguments.
Rafael Espindola8a403d32012-08-08 14:51:03 +00001781bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001782 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001783 // Argument delimiter is initially unknown. It will be set by
1784 // ParseMacroArgument()
1785 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001786
1787 // Parse two kinds of macro invocations:
1788 // - macros defined without any parameters accept an arbitrary number of them
1789 // - macros defined with parameters accept at most that many of them
1790 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1791 ++Parameter) {
1792 MacroArgument MA;
1793
Preston Gurd7b6f2032012-09-19 20:36:12 +00001794 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001795 return true;
1796
Preston Gurd6c9176a2012-09-19 20:29:04 +00001797 if (!MA.empty() || !NParameters)
1798 A.push_back(MA);
1799 else if (NParameters) {
1800 if (!M->Parameters[Parameter].second.empty())
1801 A.push_back(M->Parameters[Parameter].second);
1802 }
Jim Grosbach97146442012-07-30 22:44:17 +00001803
Preston Gurd6c9176a2012-09-19 20:29:04 +00001804 // At the end of the statement, fill in remaining arguments that have
1805 // default values. If there aren't any, then the next argument is
1806 // required but missing
1807 if (Lexer.is(AsmToken::EndOfStatement)) {
1808 if (NParameters && Parameter < NParameters - 1) {
1809 if (M->Parameters[Parameter + 1].second.empty())
1810 return TokError("macro argument '" +
1811 Twine(M->Parameters[Parameter + 1].first) +
1812 "' is missing");
1813 else
1814 continue;
1815 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001816 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001817 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001818
1819 if (Lexer.is(AsmToken::Comma))
1820 Lex();
1821 }
1822 return TokError("Too many arguments");
1823}
1824
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001825bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1826 const Macro *M) {
1827 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1828 // this, although we should protect against infinite loops.
1829 if (ActiveMacros.size() == 20)
1830 return TokError("macros cannot be nested more than 20 levels deep");
1831
Rafael Espindola8a403d32012-08-08 14:51:03 +00001832 MacroArguments A;
1833 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001834 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001835
Jim Grosbach97146442012-07-30 22:44:17 +00001836 // Remove any trailing empty arguments. Do this after-the-fact as we have
1837 // to keep empty arguments in the middle of the list or positionality
1838 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001839 while (!A.empty() && A.back().empty())
1840 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001841
Rafael Espindola65366442011-06-05 02:43:45 +00001842 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1843 // to hold the macro body with substitutions.
1844 SmallString<256> Buf;
1845 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001846 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001847
Rafael Espindola8a403d32012-08-08 14:51:03 +00001848 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001849 return true;
1850
Rafael Espindola761cb062012-06-03 23:57:14 +00001851 // We include the .endmacro in the buffer as our queue to exit the macro
1852 // instantiation.
1853 OS << ".endmacro\n";
1854
Rafael Espindola65366442011-06-05 02:43:45 +00001855 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001856 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001857
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001858 // Create the macro instantiation object and add to the current macro
1859 // instantiation stack.
1860 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001861 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001862 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001863 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001864 ActiveMacros.push_back(MI);
1865
1866 // Jump to the macro instantiation and prime the lexer.
1867 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1868 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1869 Lex();
1870
1871 return false;
1872}
1873
1874void AsmParser::HandleMacroExit() {
1875 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001876 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001877 Lex();
1878
1879 // Pop the instantiation entry.
1880 delete ActiveMacros.back();
1881 ActiveMacros.pop_back();
1882}
1883
Rafael Espindolae71cc862012-01-28 05:57:00 +00001884static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001885 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001886 case MCExpr::Binary: {
1887 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1888 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001889 break;
1890 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001891 case MCExpr::Target:
1892 case MCExpr::Constant:
1893 return false;
1894 case MCExpr::SymbolRef: {
1895 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001896 if (S.isVariable())
1897 return IsUsedIn(Sym, S.getVariableValue());
1898 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001899 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001900 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001901 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001902 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001903
1904 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001905}
1906
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001907bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1908 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001909 // FIXME: Use better location, we should use proper tokens.
1910 SMLoc EqualLoc = Lexer.getLoc();
1911
Daniel Dunbar821e3332009-08-31 08:09:28 +00001912 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001913 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001914 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001915
Rafael Espindolae71cc862012-01-28 05:57:00 +00001916 // Note: we don't count b as used in "a = b". This is to allow
1917 // a = b
1918 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001919
Daniel Dunbar3f872332009-07-28 16:08:33 +00001920 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001921 return TokError("unexpected token in assignment");
1922
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001923 // Error on assignment to '.'.
1924 if (Name == ".") {
1925 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1926 "(use '.space' or '.org').)"));
1927 }
1928
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001929 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001930 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001931
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001932 // Validate that the LHS is allowed to be a variable (either it has not been
1933 // used as a symbol, or it is an absolute symbol).
1934 MCSymbol *Sym = getContext().LookupSymbol(Name);
1935 if (Sym) {
1936 // Diagnose assignment to a label.
1937 //
1938 // FIXME: Diagnostics. Note the location of the definition as a label.
1939 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00001940 if (IsUsedIn(Sym, Value))
1941 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1942 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001943 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00001944 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1945 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00001946 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001947 return Error(EqualLoc, "redefinition of '" + Name + "'");
1948 else if (!Sym->isVariable())
1949 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00001950 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001951 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1952 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001953
1954 // Don't count these checks as uses.
1955 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001956 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001957 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001958
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001959 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001960
1961 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00001962 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001963 if (NoDeadStrip)
1964 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1965
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001966
1967 return false;
1968}
1969
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001970/// ParseIdentifier:
1971/// ::= identifier
1972/// ::= string
1973bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00001974 // The assembler has relaxed rules for accepting identifiers, in particular we
1975 // allow things like '.globl $foo', which would normally be separate
1976 // tokens. At this level, we have already lexed so we cannot (currently)
1977 // handle this as a context dependent token, instead we detect adjacent tokens
1978 // and return the combined identifier.
1979 if (Lexer.is(AsmToken::Dollar)) {
1980 SMLoc DollarLoc = getLexer().getLoc();
1981
1982 // Consume the dollar sign, and check for a following identifier.
1983 Lex();
1984 if (Lexer.isNot(AsmToken::Identifier))
1985 return true;
1986
1987 // We have a '$' followed by an identifier, make sure they are adjacent.
1988 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
1989 return true;
1990
1991 // Construct the joined identifier and consume the token.
1992 Res = StringRef(DollarLoc.getPointer(),
1993 getTok().getIdentifier().size() + 1);
1994 Lex();
1995 return false;
1996 }
1997
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001998 if (Lexer.isNot(AsmToken::Identifier) &&
1999 Lexer.isNot(AsmToken::String))
2000 return true;
2001
Sean Callanan18b83232010-01-19 21:44:56 +00002002 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002003
Sean Callanan79ed1a82010-01-19 20:22:31 +00002004 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002005
2006 return false;
2007}
2008
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002009/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002010/// ::= .equ identifier ',' expression
2011/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002012/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002013bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002014 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002015
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002016 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002017 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002018
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002019 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002020 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002021 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002022
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002023 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002024}
2025
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002026bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002027 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002028
2029 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002030 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002031 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2032 if (Str[i] != '\\') {
2033 Data += Str[i];
2034 continue;
2035 }
2036
2037 // Recognize escaped characters. Note that this escape semantics currently
2038 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2039 ++i;
2040 if (i == e)
2041 return TokError("unexpected backslash at end of string");
2042
2043 // Recognize octal sequences.
2044 if ((unsigned) (Str[i] - '0') <= 7) {
2045 // Consume up to three octal characters.
2046 unsigned Value = Str[i] - '0';
2047
2048 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2049 ++i;
2050 Value = Value * 8 + (Str[i] - '0');
2051
2052 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2053 ++i;
2054 Value = Value * 8 + (Str[i] - '0');
2055 }
2056 }
2057
2058 if (Value > 255)
2059 return TokError("invalid octal escape sequence (out of range)");
2060
2061 Data += (unsigned char) Value;
2062 continue;
2063 }
2064
2065 // Otherwise recognize individual escapes.
2066 switch (Str[i]) {
2067 default:
2068 // Just reject invalid escape sequences for now.
2069 return TokError("invalid escape sequence (unrecognized character)");
2070
2071 case 'b': Data += '\b'; break;
2072 case 'f': Data += '\f'; break;
2073 case 'n': Data += '\n'; break;
2074 case 'r': Data += '\r'; break;
2075 case 't': Data += '\t'; break;
2076 case '"': Data += '"'; break;
2077 case '\\': Data += '\\'; break;
2078 }
2079 }
2080
2081 return false;
2082}
2083
Daniel Dunbara0d14262009-06-24 23:30:00 +00002084/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002085/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2086bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002087 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002088 CheckForValidSection();
2089
Daniel Dunbara0d14262009-06-24 23:30:00 +00002090 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002091 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002092 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002093
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002094 std::string Data;
2095 if (ParseEscapedString(Data))
2096 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002097
2098 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002099 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002100 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2101
Sean Callanan79ed1a82010-01-19 20:22:31 +00002102 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002103
2104 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002105 break;
2106
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002107 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002108 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002109 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002110 }
2111 }
2112
Sean Callanan79ed1a82010-01-19 20:22:31 +00002113 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002114 return false;
2115}
2116
2117/// ParseDirectiveValue
2118/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2119bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002120 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002121 CheckForValidSection();
2122
Daniel Dunbara0d14262009-06-24 23:30:00 +00002123 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002124 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002125 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002126 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002127 return true;
2128
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002129 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002130 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2131 assert(Size <= 8 && "Invalid size");
2132 uint64_t IntValue = MCE->getValue();
2133 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2134 return Error(ExprLoc, "literal value out of range for directive");
2135 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2136 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002137 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002138
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002139 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002140 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002141
Daniel Dunbara0d14262009-06-24 23:30:00 +00002142 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002143 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002144 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002145 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002146 }
2147 }
2148
Sean Callanan79ed1a82010-01-19 20:22:31 +00002149 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002150 return false;
2151}
2152
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002153/// ParseDirectiveRealValue
2154/// ::= (.single | .double) [ expression (, expression)* ]
2155bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2156 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2157 CheckForValidSection();
2158
2159 for (;;) {
2160 // We don't truly support arithmetic on floating point expressions, so we
2161 // have to manually parse unary prefixes.
2162 bool IsNeg = false;
2163 if (getLexer().is(AsmToken::Minus)) {
2164 Lex();
2165 IsNeg = true;
2166 } else if (getLexer().is(AsmToken::Plus))
2167 Lex();
2168
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002169 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002170 getLexer().isNot(AsmToken::Real) &&
2171 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002172 return TokError("unexpected token in directive");
2173
2174 // Convert to an APFloat.
2175 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002176 StringRef IDVal = getTok().getString();
2177 if (getLexer().is(AsmToken::Identifier)) {
2178 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2179 Value = APFloat::getInf(Semantics);
2180 else if (!IDVal.compare_lower("nan"))
2181 Value = APFloat::getNaN(Semantics, false, ~0);
2182 else
2183 return TokError("invalid floating point literal");
2184 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002185 APFloat::opInvalidOp)
2186 return TokError("invalid floating point literal");
2187 if (IsNeg)
2188 Value.changeSign();
2189
2190 // Consume the numeric token.
2191 Lex();
2192
2193 // Emit the value as an integer.
2194 APInt AsInt = Value.bitcastToAPInt();
2195 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2196 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2197
2198 if (getLexer().is(AsmToken::EndOfStatement))
2199 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002200
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002201 if (getLexer().isNot(AsmToken::Comma))
2202 return TokError("unexpected token in directive");
2203 Lex();
2204 }
2205 }
2206
2207 Lex();
2208 return false;
2209}
2210
Daniel Dunbara0d14262009-06-24 23:30:00 +00002211/// ParseDirectiveSpace
2212/// ::= .space expression [ , expression ]
2213bool AsmParser::ParseDirectiveSpace() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002214 CheckForValidSection();
2215
Daniel Dunbara0d14262009-06-24 23:30:00 +00002216 int64_t NumBytes;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002217 if (ParseAbsoluteExpression(NumBytes))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002218 return true;
2219
2220 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002221 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2222 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002223 return TokError("unexpected token in '.space' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002224 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002225
Daniel Dunbar475839e2009-06-29 20:37:27 +00002226 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002227 return true;
2228
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002229 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002230 return TokError("unexpected token in '.space' directive");
2231 }
2232
Sean Callanan79ed1a82010-01-19 20:22:31 +00002233 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002234
2235 if (NumBytes <= 0)
2236 return TokError("invalid number of bytes in '.space' directive");
2237
2238 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002239 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002240
2241 return false;
2242}
2243
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002244/// ParseDirectiveZero
2245/// ::= .zero expression
2246bool AsmParser::ParseDirectiveZero() {
2247 CheckForValidSection();
2248
2249 int64_t NumBytes;
2250 if (ParseAbsoluteExpression(NumBytes))
2251 return true;
2252
Rafael Espindolae452b172010-10-05 19:42:57 +00002253 int64_t Val = 0;
2254 if (getLexer().is(AsmToken::Comma)) {
2255 Lex();
2256 if (ParseAbsoluteExpression(Val))
2257 return true;
2258 }
2259
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002260 if (getLexer().isNot(AsmToken::EndOfStatement))
2261 return TokError("unexpected token in '.zero' directive");
2262
2263 Lex();
2264
Rafael Espindolae452b172010-10-05 19:42:57 +00002265 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002266
2267 return false;
2268}
2269
Daniel Dunbara0d14262009-06-24 23:30:00 +00002270/// ParseDirectiveFill
2271/// ::= .fill expression , expression , expression
2272bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002273 CheckForValidSection();
2274
Daniel Dunbara0d14262009-06-24 23:30:00 +00002275 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002276 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002277 return true;
2278
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002279 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002280 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002281 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002282
Daniel Dunbara0d14262009-06-24 23:30:00 +00002283 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002284 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002285 return true;
2286
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002287 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002288 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002289 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002290
Daniel Dunbara0d14262009-06-24 23:30:00 +00002291 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002292 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002293 return true;
2294
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002295 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002296 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002297
Sean Callanan79ed1a82010-01-19 20:22:31 +00002298 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002299
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002300 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2301 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002302
2303 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002304 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002305
2306 return false;
2307}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002308
2309/// ParseDirectiveOrg
2310/// ::= .org expression [ , expression ]
2311bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002312 CheckForValidSection();
2313
Daniel Dunbar821e3332009-08-31 08:09:28 +00002314 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002315 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002316 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002317 return true;
2318
2319 // Parse optional fill expression.
2320 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002321 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2322 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002323 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002324 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002325
Daniel Dunbar475839e2009-06-29 20:37:27 +00002326 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002327 return true;
2328
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002329 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002330 return TokError("unexpected token in '.org' directive");
2331 }
2332
Sean Callanan79ed1a82010-01-19 20:22:31 +00002333 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002334
Jim Grosbachebd4c052012-01-27 00:37:08 +00002335 // Only limited forms of relocatable expressions are accepted here, it
2336 // has to be relative to the current section. The streamer will return
2337 // 'true' if the expression wasn't evaluatable.
2338 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2339 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002340
2341 return false;
2342}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002343
2344/// ParseDirectiveAlign
2345/// ::= {.align, ...} expression [ , expression [ , expression ]]
2346bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002347 CheckForValidSection();
2348
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002349 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002350 int64_t Alignment;
2351 if (ParseAbsoluteExpression(Alignment))
2352 return true;
2353
2354 SMLoc MaxBytesLoc;
2355 bool HasFillExpr = false;
2356 int64_t FillExpr = 0;
2357 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002358 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2359 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002360 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002361 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002362
2363 // The fill expression can be omitted while specifying a maximum number of
2364 // alignment bytes, e.g:
2365 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002366 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002367 HasFillExpr = true;
2368 if (ParseAbsoluteExpression(FillExpr))
2369 return true;
2370 }
2371
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002372 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2373 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002374 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002375 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002376
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002377 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002378 if (ParseAbsoluteExpression(MaxBytesToFill))
2379 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002380
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002381 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002382 return TokError("unexpected token in directive");
2383 }
2384 }
2385
Sean Callanan79ed1a82010-01-19 20:22:31 +00002386 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002387
Daniel Dunbar648ac512010-05-17 21:54:30 +00002388 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002389 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002390
2391 // Compute alignment in bytes.
2392 if (IsPow2) {
2393 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002394 if (Alignment >= 32) {
2395 Error(AlignmentLoc, "invalid alignment value");
2396 Alignment = 31;
2397 }
2398
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002399 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002400 }
2401
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002402 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002403 if (MaxBytesLoc.isValid()) {
2404 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002405 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2406 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002407 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002408 }
2409
2410 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002411 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2412 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002413 MaxBytesToFill = 0;
2414 }
2415 }
2416
Daniel Dunbar648ac512010-05-17 21:54:30 +00002417 // Check whether we should use optimal code alignment for this .align
2418 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002419 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002420 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2421 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002422 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002423 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002424 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002425 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2426 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002427 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002428
2429 return false;
2430}
2431
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002432/// ParseDirectiveSymbolAttribute
2433/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00002434bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002435 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002436 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002437 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00002438 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002439
2440 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00002441 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002442
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002443 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002444
Jim Grosbach10ec6502011-09-15 17:56:49 +00002445 // Assembler local symbols don't make any sense here. Complain loudly.
2446 if (Sym->isTemporary())
2447 return Error(Loc, "non-local symbol required in directive");
2448
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002449 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002450
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002451 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002452 break;
2453
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002454 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002455 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002456 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002457 }
2458 }
2459
Sean Callanan79ed1a82010-01-19 20:22:31 +00002460 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00002461 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002462}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002463
2464/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00002465/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2466bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002467 CheckForValidSection();
2468
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002469 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002470 StringRef Name;
2471 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002472 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002473
Daniel Dunbar76c4d762009-07-31 21:55:09 +00002474 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002475 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002476
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002477 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002478 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002479 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002480
2481 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002482 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002483 if (ParseAbsoluteExpression(Size))
2484 return true;
2485
2486 int64_t Pow2Alignment = 0;
2487 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002488 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00002489 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002490 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002491 if (ParseAbsoluteExpression(Pow2Alignment))
2492 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002493
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002494 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2495 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00002496 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2497
Chris Lattner258281d2010-01-19 06:22:22 +00002498 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002499 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2500 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00002501 if (!isPowerOf2_64(Pow2Alignment))
2502 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2503 Pow2Alignment = Log2_64(Pow2Alignment);
2504 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002505 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002506
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002507 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00002508 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002509
Sean Callanan79ed1a82010-01-19 20:22:31 +00002510 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002511
Chris Lattner1fc3d752009-07-09 17:25:12 +00002512 // NOTE: a size of zero for a .comm should create a undefined symbol
2513 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002514 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002515 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2516 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002517
Eric Christopherc260a3e2010-05-14 01:38:54 +00002518 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002519 // may internally end up wanting an alignment in bytes.
2520 // FIXME: Diagnose overflow.
2521 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002522 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2523 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002524
Daniel Dunbar8906ff12009-08-22 07:22:36 +00002525 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002526 return Error(IDLoc, "invalid symbol redefinition");
2527
Chris Lattner1fc3d752009-07-09 17:25:12 +00002528 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002529 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00002530 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002531 return false;
2532 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002533
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002534 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002535 return false;
2536}
Chris Lattner9be3fee2009-07-10 22:20:30 +00002537
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002538/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002539/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002540bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002541 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002542 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002543
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002544 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002545 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002546 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002547
Sean Callanan79ed1a82010-01-19 20:22:31 +00002548 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002549
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002550 if (Str.empty())
2551 Error(Loc, ".abort detected. Assembly stopping.");
2552 else
2553 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002554 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002555
2556 return false;
2557}
Kevin Enderby71148242009-07-14 21:35:03 +00002558
Kevin Enderby1f049b22009-07-14 23:21:55 +00002559/// ParseDirectiveInclude
2560/// ::= .include "filename"
2561bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002562 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002563 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002564
Sean Callanan18b83232010-01-19 21:44:56 +00002565 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002566 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002567 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00002568
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002569 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002570 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002571
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002572 // Strip the quotes.
2573 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002574
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002575 // Attempt to switch the lexer to the included file before consuming the end
2576 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00002577 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00002578 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002579 return true;
2580 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00002581
2582 return false;
2583}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00002584
Kevin Enderbyc55acca2011-12-14 21:47:48 +00002585/// ParseDirectiveIncbin
2586/// ::= .incbin "filename"
2587bool AsmParser::ParseDirectiveIncbin() {
2588 if (getLexer().isNot(AsmToken::String))
2589 return TokError("expected string in '.incbin' directive");
2590
2591 std::string Filename = getTok().getString();
2592 SMLoc IncbinLoc = getLexer().getLoc();
2593 Lex();
2594
2595 if (getLexer().isNot(AsmToken::EndOfStatement))
2596 return TokError("unexpected token in '.incbin' directive");
2597
2598 // Strip the quotes.
2599 Filename = Filename.substr(1, Filename.size()-2);
2600
2601 // Attempt to process the included file.
2602 if (ProcessIncbinFile(Filename)) {
2603 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2604 return true;
2605 }
2606
2607 return false;
2608}
2609
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002610/// ParseDirectiveIf
2611/// ::= .if expression
2612bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002613 TheCondStack.push_back(TheCondState);
2614 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00002615 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002616 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00002617 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002618 int64_t ExprValue;
2619 if (ParseAbsoluteExpression(ExprValue))
2620 return true;
2621
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002622 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002623 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002624
Sean Callanan79ed1a82010-01-19 20:22:31 +00002625 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002626
2627 TheCondState.CondMet = ExprValue;
2628 TheCondState.Ignore = !TheCondState.CondMet;
2629 }
2630
2631 return false;
2632}
2633
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002634/// ParseDirectiveIfb
2635/// ::= .ifb string
2636bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2637 TheCondStack.push_back(TheCondState);
2638 TheCondState.TheCond = AsmCond::IfCond;
2639
Benjamin Kramer29739e72012-05-12 16:52:21 +00002640 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002641 EatToEndOfStatement();
2642 } else {
2643 StringRef Str = ParseStringToEndOfStatement();
2644
2645 if (getLexer().isNot(AsmToken::EndOfStatement))
2646 return TokError("unexpected token in '.ifb' directive");
2647
2648 Lex();
2649
2650 TheCondState.CondMet = ExpectBlank == Str.empty();
2651 TheCondState.Ignore = !TheCondState.CondMet;
2652 }
2653
2654 return false;
2655}
2656
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002657/// ParseDirectiveIfc
2658/// ::= .ifc string1, string2
2659bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2660 TheCondStack.push_back(TheCondState);
2661 TheCondState.TheCond = AsmCond::IfCond;
2662
Benjamin Kramer29739e72012-05-12 16:52:21 +00002663 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002664 EatToEndOfStatement();
2665 } else {
2666 StringRef Str1 = ParseStringToComma();
2667
2668 if (getLexer().isNot(AsmToken::Comma))
2669 return TokError("unexpected token in '.ifc' directive");
2670
2671 Lex();
2672
2673 StringRef Str2 = ParseStringToEndOfStatement();
2674
2675 if (getLexer().isNot(AsmToken::EndOfStatement))
2676 return TokError("unexpected token in '.ifc' directive");
2677
2678 Lex();
2679
2680 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2681 TheCondState.Ignore = !TheCondState.CondMet;
2682 }
2683
2684 return false;
2685}
2686
2687/// ParseDirectiveIfdef
2688/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00002689bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2690 StringRef Name;
2691 TheCondStack.push_back(TheCondState);
2692 TheCondState.TheCond = AsmCond::IfCond;
2693
2694 if (TheCondState.Ignore) {
2695 EatToEndOfStatement();
2696 } else {
2697 if (ParseIdentifier(Name))
2698 return TokError("expected identifier after '.ifdef'");
2699
2700 Lex();
2701
2702 MCSymbol *Sym = getContext().LookupSymbol(Name);
2703
2704 if (expect_defined)
2705 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2706 else
2707 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2708 TheCondState.Ignore = !TheCondState.CondMet;
2709 }
2710
2711 return false;
2712}
2713
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002714/// ParseDirectiveElseIf
2715/// ::= .elseif expression
2716bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2717 if (TheCondState.TheCond != AsmCond::IfCond &&
2718 TheCondState.TheCond != AsmCond::ElseIfCond)
2719 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2720 " an .elseif");
2721 TheCondState.TheCond = AsmCond::ElseIfCond;
2722
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002723 bool LastIgnoreState = false;
2724 if (!TheCondStack.empty())
2725 LastIgnoreState = TheCondStack.back().Ignore;
2726 if (LastIgnoreState || TheCondState.CondMet) {
2727 TheCondState.Ignore = true;
2728 EatToEndOfStatement();
2729 }
2730 else {
2731 int64_t ExprValue;
2732 if (ParseAbsoluteExpression(ExprValue))
2733 return true;
2734
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002735 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002736 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002737
Sean Callanan79ed1a82010-01-19 20:22:31 +00002738 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002739 TheCondState.CondMet = ExprValue;
2740 TheCondState.Ignore = !TheCondState.CondMet;
2741 }
2742
2743 return false;
2744}
2745
2746/// ParseDirectiveElse
2747/// ::= .else
2748bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002749 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002750 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002751
Sean Callanan79ed1a82010-01-19 20:22:31 +00002752 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002753
2754 if (TheCondState.TheCond != AsmCond::IfCond &&
2755 TheCondState.TheCond != AsmCond::ElseIfCond)
2756 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2757 ".elseif");
2758 TheCondState.TheCond = AsmCond::ElseCond;
2759 bool LastIgnoreState = false;
2760 if (!TheCondStack.empty())
2761 LastIgnoreState = TheCondStack.back().Ignore;
2762 if (LastIgnoreState || TheCondState.CondMet)
2763 TheCondState.Ignore = true;
2764 else
2765 TheCondState.Ignore = false;
2766
2767 return false;
2768}
2769
2770/// ParseDirectiveEndIf
2771/// ::= .endif
2772bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002773 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002774 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002775
Sean Callanan79ed1a82010-01-19 20:22:31 +00002776 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002777
2778 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2779 TheCondStack.empty())
2780 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2781 ".else");
2782 if (!TheCondStack.empty()) {
2783 TheCondState = TheCondStack.back();
2784 TheCondStack.pop_back();
2785 }
2786
2787 return false;
2788}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002789
2790/// ParseDirectiveFile
Nick Lewycky44d798d2011-10-17 23:05:28 +00002791/// ::= .file [number] filename
2792/// ::= .file number directory filename
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002793bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002794 // FIXME: I'm not sure what this is.
2795 int64_t FileNumber = -1;
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002796 SMLoc FileNumberLoc = getLexer().getLoc();
Daniel Dunbareceec052010-07-12 17:45:27 +00002797 if (getLexer().is(AsmToken::Integer)) {
Sean Callanan18b83232010-01-19 21:44:56 +00002798 FileNumber = getTok().getIntVal();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002799 Lex();
Daniel Dunbareceec052010-07-12 17:45:27 +00002800
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002801 if (FileNumber < 1)
2802 return TokError("file number less than one");
2803 }
2804
Daniel Dunbareceec052010-07-12 17:45:27 +00002805 if (getLexer().isNot(AsmToken::String))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002806 return TokError("unexpected token in '.file' directive");
Daniel Dunbareceec052010-07-12 17:45:27 +00002807
Nick Lewycky44d798d2011-10-17 23:05:28 +00002808 // Usually the directory and filename together, otherwise just the directory.
2809 StringRef Path = getTok().getString();
2810 Path = Path.substr(1, Path.size()-2);
Sean Callanan79ed1a82010-01-19 20:22:31 +00002811 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002812
Nick Lewycky44d798d2011-10-17 23:05:28 +00002813 StringRef Directory;
2814 StringRef Filename;
2815 if (getLexer().is(AsmToken::String)) {
2816 if (FileNumber == -1)
2817 return TokError("explicit path specified, but no file number");
2818 Filename = getTok().getString();
2819 Filename = Filename.substr(1, Filename.size()-2);
2820 Directory = Path;
2821 Lex();
2822 } else {
2823 Filename = Path;
2824 }
2825
Daniel Dunbareceec052010-07-12 17:45:27 +00002826 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002827 return TokError("unexpected token in '.file' directive");
2828
Chris Lattnerd32e8032010-01-25 19:02:58 +00002829 if (FileNumber == -1)
Daniel Dunbareceec052010-07-12 17:45:27 +00002830 getStreamer().EmitFileDirective(Filename);
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002831 else {
Kevin Enderby8704b782012-01-11 18:04:47 +00002832 if (getContext().getGenDwarfForAssembly() == true)
2833 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2834 "used to generate dwarf debug info for assembly code");
2835
Nick Lewycky44d798d2011-10-17 23:05:28 +00002836 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002837 Error(FileNumberLoc, "file number already allocated");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002838 }
Daniel Dunbareceec052010-07-12 17:45:27 +00002839
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002840 return false;
2841}
2842
2843/// ParseDirectiveLine
2844/// ::= .line [number]
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002845bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbareceec052010-07-12 17:45:27 +00002846 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2847 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002848 return TokError("unexpected token in '.line' directive");
2849
Sean Callanan18b83232010-01-19 21:44:56 +00002850 int64_t LineNumber = getTok().getIntVal();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002851 (void) LineNumber;
Sean Callanan79ed1a82010-01-19 20:22:31 +00002852 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002853
2854 // FIXME: Do something with the .line.
2855 }
2856
Daniel Dunbareceec052010-07-12 17:45:27 +00002857 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar839348a2010-07-01 20:20:01 +00002858 return TokError("unexpected token in '.line' directive");
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002859
2860 return false;
2861}
2862
2863
2864/// ParseDirectiveLoc
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002865/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002866/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2867/// The first number is a file number, must have been previously assigned with
2868/// a .file directive, the second number is the line number and optionally the
2869/// third number is a column position (zero if not specified). The remaining
2870/// optional items are .loc sub-directives.
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002871bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002872
Daniel Dunbareceec052010-07-12 17:45:27 +00002873 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002874 return TokError("unexpected token in '.loc' directive");
Sean Callanan18b83232010-01-19 21:44:56 +00002875 int64_t FileNumber = getTok().getIntVal();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002876 if (FileNumber < 1)
2877 return TokError("file number less than one in '.loc' directive");
Kevin Enderby3f55c242010-10-04 20:17:24 +00002878 if (!getContext().isValidDwarfFileNumber(FileNumber))
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002879 return TokError("unassigned file number in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002880 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002881
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002882 int64_t LineNumber = 0;
2883 if (getLexer().is(AsmToken::Integer)) {
2884 LineNumber = getTok().getIntVal();
2885 if (LineNumber < 1)
2886 return TokError("line number less than one in '.loc' directive");
2887 Lex();
2888 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002889
2890 int64_t ColumnPos = 0;
2891 if (getLexer().is(AsmToken::Integer)) {
2892 ColumnPos = getTok().getIntVal();
2893 if (ColumnPos < 0)
2894 return TokError("column position less than zero in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002895 Lex();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002896 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002897
Kevin Enderbyc0957932010-09-30 16:52:03 +00002898 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002899 unsigned Isa = 0;
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002900 int64_t Discriminator = 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002901 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2902 for (;;) {
2903 if (getLexer().is(AsmToken::EndOfStatement))
2904 break;
2905
2906 StringRef Name;
2907 SMLoc Loc = getTok().getLoc();
2908 if (getParser().ParseIdentifier(Name))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002909 return TokError("unexpected token in '.loc' directive");
2910
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002911 if (Name == "basic_block")
2912 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2913 else if (Name == "prologue_end")
2914 Flags |= DWARF2_FLAG_PROLOGUE_END;
2915 else if (Name == "epilogue_begin")
2916 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2917 else if (Name == "is_stmt") {
2918 SMLoc Loc = getTok().getLoc();
2919 const MCExpr *Value;
2920 if (getParser().ParseExpression(Value))
2921 return true;
2922 // The expression must be the constant 0 or 1.
2923 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2924 int Value = MCE->getValue();
2925 if (Value == 0)
2926 Flags &= ~DWARF2_FLAG_IS_STMT;
2927 else if (Value == 1)
2928 Flags |= DWARF2_FLAG_IS_STMT;
2929 else
2930 return Error(Loc, "is_stmt value not 0 or 1");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002931 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002932 else {
2933 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2934 }
2935 }
2936 else if (Name == "isa") {
2937 SMLoc Loc = getTok().getLoc();
2938 const MCExpr *Value;
2939 if (getParser().ParseExpression(Value))
2940 return true;
2941 // The expression must be a constant greater or equal to 0.
2942 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2943 int Value = MCE->getValue();
2944 if (Value < 0)
2945 return Error(Loc, "isa number less than zero");
2946 Isa = Value;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002947 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002948 else {
2949 return Error(Loc, "isa number not a constant value");
2950 }
2951 }
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002952 else if (Name == "discriminator") {
2953 if (getParser().ParseAbsoluteExpression(Discriminator))
2954 return true;
2955 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002956 else {
2957 return Error(Loc, "unknown sub-directive in '.loc' directive");
2958 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002959
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002960 if (getLexer().is(AsmToken::EndOfStatement))
2961 break;
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002962 }
2963 }
2964
Rafael Espindolaaf6b58082010-11-16 21:20:32 +00002965 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
Devang Patel3f3bf932011-04-18 20:26:49 +00002966 Isa, Discriminator, StringRef());
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002967
2968 return false;
2969}
2970
Daniel Dunbar138abae2010-10-16 04:56:42 +00002971/// ParseDirectiveStabs
2972/// ::= .stabs string, number, number, number
2973bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
2974 SMLoc DirectiveLoc) {
2975 return TokError("unsupported directive '" + Directive + "'");
2976}
2977
Rafael Espindolaf9efd832011-05-10 01:10:18 +00002978/// ParseDirectiveCFISections
2979/// ::= .cfi_sections section [, section]
2980bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
2981 SMLoc DirectiveLoc) {
2982 StringRef Name;
2983 bool EH = false;
2984 bool Debug = false;
2985
2986 if (getParser().ParseIdentifier(Name))
2987 return TokError("Expected an identifier");
2988
2989 if (Name == ".eh_frame")
2990 EH = true;
2991 else if (Name == ".debug_frame")
2992 Debug = true;
2993
2994 if (getLexer().is(AsmToken::Comma)) {
2995 Lex();
2996
2997 if (getParser().ParseIdentifier(Name))
2998 return TokError("Expected an identifier");
2999
3000 if (Name == ".eh_frame")
3001 EH = true;
3002 else if (Name == ".debug_frame")
3003 Debug = true;
3004 }
3005
3006 getStreamer().EmitCFISections(EH, Debug);
3007
3008 return false;
3009}
3010
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003011/// ParseDirectiveCFIStartProc
3012/// ::= .cfi_startproc
3013bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
3014 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003015 getStreamer().EmitCFIStartProc();
3016 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003017}
3018
3019/// ParseDirectiveCFIEndProc
3020/// ::= .cfi_endproc
3021bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003022 getStreamer().EmitCFIEndProc();
3023 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003024}
3025
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003026/// ParseRegisterOrRegisterNumber - parse register name or number.
3027bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
3028 SMLoc DirectiveLoc) {
3029 unsigned RegNo;
3030
Jim Grosbach6f888a82011-06-02 17:14:04 +00003031 if (getLexer().isNot(AsmToken::Integer)) {
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003032 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
3033 DirectiveLoc))
3034 return true;
Evan Cheng0e6a0522011-07-18 20:57:22 +00003035 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003036 } else
3037 return getParser().ParseAbsoluteExpression(Register);
Jim Grosbachde2f5f42011-02-11 19:05:56 +00003038
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003039 return false;
3040}
3041
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003042/// ParseDirectiveCFIDefCfa
3043/// ::= .cfi_def_cfa register, offset
3044bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
3045 SMLoc DirectiveLoc) {
3046 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003047 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003048 return true;
3049
3050 if (getLexer().isNot(AsmToken::Comma))
3051 return TokError("unexpected token in directive");
3052 Lex();
3053
3054 int64_t Offset = 0;
3055 if (getParser().ParseAbsoluteExpression(Offset))
3056 return true;
3057
Rafael Espindola066c2f42011-04-12 23:59:07 +00003058 getStreamer().EmitCFIDefCfa(Register, Offset);
3059 return false;
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003060}
3061
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003062/// ParseDirectiveCFIDefCfaOffset
3063/// ::= .cfi_def_cfa_offset offset
3064bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3065 SMLoc DirectiveLoc) {
3066 int64_t Offset = 0;
3067 if (getParser().ParseAbsoluteExpression(Offset))
3068 return true;
3069
Rafael Espindola066c2f42011-04-12 23:59:07 +00003070 getStreamer().EmitCFIDefCfaOffset(Offset);
3071 return false;
Rafael Espindola53abbe52011-04-11 20:29:16 +00003072}
3073
3074/// ParseDirectiveCFIAdjustCfaOffset
3075/// ::= .cfi_adjust_cfa_offset adjustment
3076bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3077 SMLoc DirectiveLoc) {
3078 int64_t Adjustment = 0;
3079 if (getParser().ParseAbsoluteExpression(Adjustment))
3080 return true;
3081
Rafael Espindola5d7dcd32011-04-12 18:53:30 +00003082 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3083 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003084}
3085
3086/// ParseDirectiveCFIDefCfaRegister
3087/// ::= .cfi_def_cfa_register register
3088bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3089 SMLoc DirectiveLoc) {
3090 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003091 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003092 return true;
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003093
Rafael Espindola066c2f42011-04-12 23:59:07 +00003094 getStreamer().EmitCFIDefCfaRegister(Register);
3095 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003096}
3097
3098/// ParseDirectiveCFIOffset
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003099/// ::= .cfi_offset register, offset
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003100bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3101 int64_t Register = 0;
3102 int64_t Offset = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003103
3104 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003105 return true;
3106
3107 if (getLexer().isNot(AsmToken::Comma))
3108 return TokError("unexpected token in directive");
3109 Lex();
3110
3111 if (getParser().ParseAbsoluteExpression(Offset))
3112 return true;
3113
Rafael Espindola066c2f42011-04-12 23:59:07 +00003114 getStreamer().EmitCFIOffset(Register, Offset);
3115 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003116}
3117
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003118/// ParseDirectiveCFIRelOffset
3119/// ::= .cfi_rel_offset register, offset
3120bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3121 SMLoc DirectiveLoc) {
3122 int64_t Register = 0;
3123
3124 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3125 return true;
3126
3127 if (getLexer().isNot(AsmToken::Comma))
3128 return TokError("unexpected token in directive");
3129 Lex();
3130
3131 int64_t Offset = 0;
3132 if (getParser().ParseAbsoluteExpression(Offset))
3133 return true;
3134
Rafael Espindola25f492e2011-04-12 16:12:03 +00003135 getStreamer().EmitCFIRelOffset(Register, Offset);
3136 return false;
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003137}
3138
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003139static bool isValidEncoding(int64_t Encoding) {
3140 if (Encoding & ~0xff)
3141 return false;
3142
3143 if (Encoding == dwarf::DW_EH_PE_omit)
3144 return true;
3145
3146 const unsigned Format = Encoding & 0xf;
3147 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3148 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3149 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3150 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3151 return false;
3152
Rafael Espindolacaf11582010-12-29 04:31:26 +00003153 const unsigned Application = Encoding & 0x70;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003154 if (Application != dwarf::DW_EH_PE_absptr &&
Rafael Espindolacaf11582010-12-29 04:31:26 +00003155 Application != dwarf::DW_EH_PE_pcrel)
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003156 return false;
3157
3158 return true;
3159}
3160
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003161/// ParseDirectiveCFIPersonalityOrLsda
3162/// ::= .cfi_personality encoding, [symbol_name]
3163/// ::= .cfi_lsda encoding, [symbol_name]
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003164bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003165 SMLoc DirectiveLoc) {
3166 int64_t Encoding = 0;
3167 if (getParser().ParseAbsoluteExpression(Encoding))
3168 return true;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003169 if (Encoding == dwarf::DW_EH_PE_omit)
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003170 return false;
3171
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003172 if (!isValidEncoding(Encoding))
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003173 return TokError("unsupported encoding.");
3174
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003175 if (getLexer().isNot(AsmToken::Comma))
3176 return TokError("unexpected token in directive");
3177 Lex();
3178
3179 StringRef Name;
3180 if (getParser().ParseIdentifier(Name))
3181 return TokError("expected identifier in directive");
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003182
3183 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3184
3185 if (IDVal == ".cfi_personality")
Rafael Espindola066c2f42011-04-12 23:59:07 +00003186 getStreamer().EmitCFIPersonality(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003187 else {
3188 assert(IDVal == ".cfi_lsda");
Rafael Espindola066c2f42011-04-12 23:59:07 +00003189 getStreamer().EmitCFILsda(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003190 }
Rafael Espindola066c2f42011-04-12 23:59:07 +00003191 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003192}
3193
Rafael Espindolafe024d02010-12-28 18:36:23 +00003194/// ParseDirectiveCFIRememberState
3195/// ::= .cfi_remember_state
3196bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3197 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003198 getStreamer().EmitCFIRememberState();
3199 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003200}
3201
3202/// ParseDirectiveCFIRestoreState
3203/// ::= .cfi_remember_state
3204bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3205 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003206 getStreamer().EmitCFIRestoreState();
3207 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003208}
3209
Rafael Espindolac5754392011-04-12 15:31:05 +00003210/// ParseDirectiveCFISameValue
3211/// ::= .cfi_same_value register
3212bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3213 SMLoc DirectiveLoc) {
3214 int64_t Register = 0;
3215
3216 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3217 return true;
3218
3219 getStreamer().EmitCFISameValue(Register);
3220
3221 return false;
3222}
3223
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003224/// ParseDirectiveCFIRestore
3225/// ::= .cfi_restore register
3226bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003227 SMLoc DirectiveLoc) {
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003228 int64_t Register = 0;
3229 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3230 return true;
3231
3232 getStreamer().EmitCFIRestore(Register);
3233
3234 return false;
3235}
3236
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003237/// ParseDirectiveCFIEscape
3238/// ::= .cfi_escape expression[,...]
3239bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003240 SMLoc DirectiveLoc) {
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003241 std::string Values;
3242 int64_t CurrValue;
3243 if (getParser().ParseAbsoluteExpression(CurrValue))
3244 return true;
3245
3246 Values.push_back((uint8_t)CurrValue);
3247
3248 while (getLexer().is(AsmToken::Comma)) {
3249 Lex();
3250
3251 if (getParser().ParseAbsoluteExpression(CurrValue))
3252 return true;
3253
3254 Values.push_back((uint8_t)CurrValue);
3255 }
3256
3257 getStreamer().EmitCFIEscape(Values);
3258 return false;
3259}
3260
Rafael Espindola16d7d432012-01-23 21:51:52 +00003261/// ParseDirectiveCFISignalFrame
3262/// ::= .cfi_signal_frame
3263bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3264 SMLoc DirectiveLoc) {
3265 if (getLexer().isNot(AsmToken::EndOfStatement))
3266 return Error(getLexer().getLoc(),
3267 "unexpected token in '" + Directive + "' directive");
3268
3269 getStreamer().EmitCFISignalFrame();
3270
3271 return false;
3272}
3273
Rafael Espindolac8fec7e2012-11-23 16:59:41 +00003274/// ParseDirectiveCFIUndefined
3275/// ::= .cfi_undefined register
3276bool GenericAsmParser::ParseDirectiveCFIUndefined(StringRef Directive,
3277 SMLoc DirectiveLoc) {
3278 int64_t Register = 0;
3279
3280 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3281 return true;
3282
3283 getStreamer().EmitCFIUndefined(Register);
3284
3285 return false;
3286}
3287
Rafael Espindolaf4f14f62012-11-25 15:14:49 +00003288/// ParseDirectiveCFIRegister
3289/// ::= .cfi_register register, register
3290bool GenericAsmParser::ParseDirectiveCFIRegister(StringRef Directive,
3291 SMLoc DirectiveLoc) {
3292 int64_t Register1 = 0;
3293
3294 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3295 return true;
3296
3297 if (getLexer().isNot(AsmToken::Comma))
3298 return TokError("unexpected token in directive");
3299 Lex();
3300
3301 int64_t Register2 = 0;
3302
3303 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3304 return true;
3305
3306 getStreamer().EmitCFIRegister(Register1, Register2);
3307
3308 return false;
3309}
3310
Daniel Dunbar3c802de2010-07-18 18:38:02 +00003311/// ParseDirectiveMacrosOnOff
3312/// ::= .macros_on
3313/// ::= .macros_off
3314bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3315 SMLoc DirectiveLoc) {
3316 if (getLexer().isNot(AsmToken::EndOfStatement))
3317 return Error(getLexer().getLoc(),
3318 "unexpected token in '" + Directive + "' directive");
3319
3320 getParser().MacrosEnabled = Directive == ".macros_on";
3321
3322 return false;
3323}
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003324
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003325/// ParseDirectiveMacro
Rafael Espindola65366442011-06-05 02:43:45 +00003326/// ::= .macro name [parameters]
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003327bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3328 SMLoc DirectiveLoc) {
3329 StringRef Name;
3330 if (getParser().ParseIdentifier(Name))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003331 return TokError("expected identifier in '.macro' directive");
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003332
Rafael Espindola8a403d32012-08-08 14:51:03 +00003333 MacroParameters Parameters;
Preston Gurd7b6f2032012-09-19 20:36:12 +00003334 // Argument delimiter is initially unknown. It will be set by
3335 // ParseMacroArgument()
3336 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindola65366442011-06-05 02:43:45 +00003337 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Rafael Espindola7996d042012-08-21 16:06:48 +00003338 for (;;) {
3339 MacroParameter Parameter;
Preston Gurd6c9176a2012-09-19 20:29:04 +00003340 if (getParser().ParseIdentifier(Parameter.first))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003341 return TokError("expected identifier in '.macro' directive");
Preston Gurd6c9176a2012-09-19 20:29:04 +00003342
3343 if (getLexer().is(AsmToken::Equal)) {
3344 Lex();
Preston Gurd7b6f2032012-09-19 20:36:12 +00003345 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
Preston Gurd6c9176a2012-09-19 20:29:04 +00003346 return true;
3347 }
3348
Rafael Espindola65366442011-06-05 02:43:45 +00003349 Parameters.push_back(Parameter);
3350
Preston Gurd7b6f2032012-09-19 20:36:12 +00003351 if (getLexer().is(AsmToken::Comma))
3352 Lex();
3353 else if (getLexer().is(AsmToken::EndOfStatement))
Rafael Espindola65366442011-06-05 02:43:45 +00003354 break;
Rafael Espindola65366442011-06-05 02:43:45 +00003355 }
3356 }
3357
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003358 // Eat the end of statement.
3359 Lex();
3360
3361 AsmToken EndToken, StartToken = getTok();
3362
3363 // Lex the macro definition.
3364 for (;;) {
3365 // Check whether we have reached the end of the file.
3366 if (getLexer().is(AsmToken::Eof))
3367 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3368
3369 // Otherwise, check whether we have reach the .endmacro.
3370 if (getLexer().is(AsmToken::Identifier) &&
3371 (getTok().getIdentifier() == ".endm" ||
3372 getTok().getIdentifier() == ".endmacro")) {
3373 EndToken = getTok();
3374 Lex();
3375 if (getLexer().isNot(AsmToken::EndOfStatement))
3376 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3377 "' directive");
3378 break;
3379 }
3380
3381 // Otherwise, scan til the end of the statement.
3382 getParser().EatToEndOfStatement();
3383 }
3384
3385 if (getParser().MacroMap.lookup(Name)) {
3386 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3387 }
3388
3389 const char *BodyStart = StartToken.getLoc().getPointer();
3390 const char *BodyEnd = EndToken.getLoc().getPointer();
3391 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Rafael Espindola65366442011-06-05 02:43:45 +00003392 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003393 return false;
3394}
3395
3396/// ParseDirectiveEndMacro
3397/// ::= .endm
3398/// ::= .endmacro
3399bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
Rafael Espindola8a403d32012-08-08 14:51:03 +00003400 SMLoc DirectiveLoc) {
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003401 if (getLexer().isNot(AsmToken::EndOfStatement))
3402 return TokError("unexpected token in '" + Directive + "' directive");
3403
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00003404 // If we are inside a macro instantiation, terminate the current
3405 // instantiation.
3406 if (!getParser().ActiveMacros.empty()) {
3407 getParser().HandleMacroExit();
3408 return false;
3409 }
3410
3411 // Otherwise, this .endmacro is a stray entry in the file; well formed
3412 // .endmacro directives are handled during the macro definition parsing.
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003413 return TokError("unexpected '" + Directive + "' in file, "
3414 "no current macro definition");
3415}
3416
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +00003417/// ParseDirectivePurgeMacro
3418/// ::= .purgem
3419bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3420 SMLoc DirectiveLoc) {
3421 StringRef Name;
3422 if (getParser().ParseIdentifier(Name))
3423 return TokError("expected identifier in '.purgem' directive");
3424
3425 if (getLexer().isNot(AsmToken::EndOfStatement))
3426 return TokError("unexpected token in '.purgem' directive");
3427
3428 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3429 if (I == getParser().MacroMap.end())
3430 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3431
3432 // Undefine the macro.
3433 delete I->getValue();
3434 getParser().MacroMap.erase(I);
3435 return false;
3436}
3437
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003438bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
Rafael Espindola3ff57092010-11-02 17:22:24 +00003439 getParser().CheckForValidSection();
3440
3441 const MCExpr *Value;
3442
3443 if (getParser().ParseExpression(Value))
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003444 return true;
3445
3446 if (getLexer().isNot(AsmToken::EndOfStatement))
3447 return TokError("unexpected token in directive");
3448
3449 if (DirName[1] == 's')
Rafael Espindola3ff57092010-11-02 17:22:24 +00003450 getStreamer().EmitSLEB128Value(Value);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003451 else
Rafael Espindola3ff57092010-11-02 17:22:24 +00003452 getStreamer().EmitULEB128Value(Value);
3453
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003454 return false;
3455}
3456
Rafael Espindola761cb062012-06-03 23:57:14 +00003457Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003458 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003459
Rafael Espindola761cb062012-06-03 23:57:14 +00003460 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003461 for (;;) {
3462 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003463 if (getLexer().is(AsmToken::Eof)) {
3464 Error(DirectiveLoc, "no matching '.endr' in definition");
3465 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003466 }
3467
Rafael Espindola761cb062012-06-03 23:57:14 +00003468 if (Lexer.is(AsmToken::Identifier) &&
3469 (getTok().getIdentifier() == ".rept")) {
3470 ++NestLevel;
3471 }
3472
3473 // Otherwise, check whether we have reached the .endr.
3474 if (Lexer.is(AsmToken::Identifier) &&
3475 getTok().getIdentifier() == ".endr") {
3476 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003477 EndToken = getTok();
3478 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003479 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3480 TokError("unexpected token in '.endr' directive");
3481 return 0;
3482 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003483 break;
3484 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003485 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003486 }
3487
Rafael Espindola761cb062012-06-03 23:57:14 +00003488 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003489 EatToEndOfStatement();
3490 }
3491
3492 const char *BodyStart = StartToken.getLoc().getPointer();
3493 const char *BodyEnd = EndToken.getLoc().getPointer();
3494 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3495
Rafael Espindola761cb062012-06-03 23:57:14 +00003496 // We Are Anonymous.
3497 StringRef Name;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003498 MacroParameters Parameters;
Rafael Espindola761cb062012-06-03 23:57:14 +00003499 return new Macro(Name, Body, Parameters);
3500}
3501
3502void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3503 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003504 OS << ".endr\n";
3505
3506 MemoryBuffer *Instantiation =
3507 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3508
Rafael Espindola761cb062012-06-03 23:57:14 +00003509 // Create the macro instantiation object and add to the current macro
3510 // instantiation stack.
3511 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003512 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003513 getTok().getLoc(),
3514 Instantiation);
3515 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003516
Rafael Espindola761cb062012-06-03 23:57:14 +00003517 // Jump to the macro instantiation and prime the lexer.
3518 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3519 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3520 Lex();
3521}
3522
3523bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3524 int64_t Count;
3525 if (ParseAbsoluteExpression(Count))
3526 return TokError("unexpected token in '.rept' directive");
3527
3528 if (Count < 0)
3529 return TokError("Count is negative");
3530
3531 if (Lexer.isNot(AsmToken::EndOfStatement))
3532 return TokError("unexpected token in '.rept' directive");
3533
3534 // Eat the end of statement.
3535 Lex();
3536
3537 // Lex the rept definition.
3538 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3539 if (!M)
3540 return true;
3541
3542 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3543 // to hold the macro body with substitutions.
3544 SmallString<256> Buf;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003545 MacroParameters Parameters;
3546 MacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003547 raw_svector_ostream OS(Buf);
3548 while (Count--) {
3549 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3550 return true;
3551 }
3552 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003553
3554 return false;
3555}
3556
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003557/// ParseDirectiveIrp
3558/// ::= .irp symbol,values
3559bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003560 MacroParameters Parameters;
3561 MacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003562
Preston Gurd6c9176a2012-09-19 20:29:04 +00003563 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003564 return TokError("expected identifier in '.irp' directive");
3565
3566 Parameters.push_back(Parameter);
3567
3568 if (Lexer.isNot(AsmToken::Comma))
3569 return TokError("expected comma in '.irp' directive");
3570
3571 Lex();
3572
Rafael Espindola8a403d32012-08-08 14:51:03 +00003573 MacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003574 if (ParseMacroArguments(0, A))
3575 return true;
3576
3577 // Eat the end of statement.
3578 Lex();
3579
3580 // Lex the irp definition.
3581 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3582 if (!M)
3583 return true;
3584
3585 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3586 // to hold the macro body with substitutions.
3587 SmallString<256> Buf;
3588 raw_svector_ostream OS(Buf);
3589
Rafael Espindola7996d042012-08-21 16:06:48 +00003590 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3591 MacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003592 Args.push_back(*i);
3593
3594 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3595 return true;
3596 }
3597
3598 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3599
3600 return false;
3601}
3602
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003603/// ParseDirectiveIrpc
3604/// ::= .irpc symbol,values
3605bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003606 MacroParameters Parameters;
3607 MacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003608
Preston Gurd6c9176a2012-09-19 20:29:04 +00003609 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003610 return TokError("expected identifier in '.irpc' directive");
3611
3612 Parameters.push_back(Parameter);
3613
3614 if (Lexer.isNot(AsmToken::Comma))
3615 return TokError("expected comma in '.irpc' directive");
3616
3617 Lex();
3618
Rafael Espindola8a403d32012-08-08 14:51:03 +00003619 MacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003620 if (ParseMacroArguments(0, A))
3621 return true;
3622
3623 if (A.size() != 1 || A.front().size() != 1)
3624 return TokError("unexpected token in '.irpc' directive");
3625
3626 // Eat the end of statement.
3627 Lex();
3628
3629 // Lex the irpc definition.
3630 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3631 if (!M)
3632 return true;
3633
3634 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3635 // to hold the macro body with substitutions.
3636 SmallString<256> Buf;
3637 raw_svector_ostream OS(Buf);
3638
3639 StringRef Values = A.front().front().getString();
3640 std::size_t I, End = Values.size();
3641 for (I = 0; I < End; ++I) {
3642 MacroArgument Arg;
3643 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3644
Rafael Espindola8a403d32012-08-08 14:51:03 +00003645 MacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003646 Args.push_back(Arg);
3647
3648 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3649 return true;
3650 }
3651
3652 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3653
3654 return false;
3655}
3656
Rafael Espindola761cb062012-06-03 23:57:14 +00003657bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3658 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003659 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003660
3661 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003662 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003663 assert(getLexer().is(AsmToken::EndOfStatement));
3664
Rafael Espindola761cb062012-06-03 23:57:14 +00003665 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003666 return false;
3667}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003668
Eli Friedman2128aae2012-10-22 23:58:19 +00003669bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3670 const MCExpr *Value;
3671 SMLoc ExprLoc = getLexer().getLoc();
3672 if (ParseExpression(Value))
3673 return true;
3674 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3675 if (!MCE)
3676 return Error(ExprLoc, "unexpected expression in _emit");
3677 uint64_t IntValue = MCE->getValue();
3678 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3679 return Error(ExprLoc, "literal value out of range for directive");
3680
3681 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3682 return false;
3683}
3684
Chad Rosierb1f8c132012-10-18 15:49:34 +00003685bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3686 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003687 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003688 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003689 SmallVectorImpl<std::string> &Clobbers,
3690 const MCInstrInfo *MII,
3691 const MCInstPrinter *IP,
3692 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003693 SmallVector<void *, 4> InputDecls;
3694 SmallVector<void *, 4> OutputDecls;
3695 SmallVector<bool, 4> InputDeclsOffsetOf;
3696 SmallVector<bool, 4> OutputDeclsOffsetOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003697 SmallVector<std::string, 4> InputConstraints;
3698 SmallVector<std::string, 4> OutputConstraints;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003699 std::set<std::string> ClobberRegs;
3700
Chad Rosier4e472d22012-10-20 01:02:45 +00003701 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003702
3703 // Prime the lexer.
3704 Lex();
3705
3706 // While we have input, parse each statement.
3707 unsigned InputIdx = 0;
3708 unsigned OutputIdx = 0;
3709 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00003710 ParseStatementInfo Info(&AsmStrRewrites);
3711 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00003712 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003713
Chad Rosier57498012012-12-12 22:45:52 +00003714 if (Info.ParseError)
3715 return true;
3716
Eli Friedman2128aae2012-10-22 23:58:19 +00003717 if (Info.Opcode != ~0U) {
3718 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003719
3720 // Build the list of clobbers, outputs and inputs.
Eli Friedman2128aae2012-10-22 23:58:19 +00003721 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3722 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003723
3724 // Immediate.
3725 if (Operand->isImm()) {
Chad Rosierefcb3d92012-10-26 18:04:20 +00003726 if (Operand->needAsmRewrite())
3727 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3728 Operand->getStartLoc()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003729 continue;
3730 }
3731
3732 // Register operand.
Chad Rosierc0a14b82012-10-24 17:22:29 +00003733 if (Operand->isReg() && !Operand->isOffsetOf()) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003734 unsigned NumDefs = Desc.getNumDefs();
3735 // Clobber.
3736 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3737 std::string Reg;
3738 raw_string_ostream OS(Reg);
3739 IP->printRegName(OS, Operand->getReg());
3740 ClobberRegs.insert(StringRef(OS.str()));
3741 }
3742 continue;
3743 }
3744
3745 // Expr/Input or Output.
Chad Rosier32989592012-10-18 20:27:15 +00003746 unsigned Size;
3747 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3748 Size);
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003749 if (OpDecl) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003750 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierc0a14b82012-10-24 17:22:29 +00003751 if (!Operand->isOffsetOf() && Operand->needSizeDirective())
Chad Rosier4e472d22012-10-20 01:02:45 +00003752 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
Chad Rosierefcb3d92012-10-26 18:04:20 +00003753 Operand->getStartLoc(),
3754 /*Len*/0,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003755 Operand->getMemSize()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003756 if (isOutput) {
3757 std::string Constraint = "=";
3758 ++InputIdx;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003759 OutputDecls.push_back(OpDecl);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003760 OutputDeclsOffsetOf.push_back(Operand->isOffsetOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003761 Constraint += Operand->getConstraint().str();
3762 OutputConstraints.push_back(Constraint);
Chad Rosier4e472d22012-10-20 01:02:45 +00003763 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003764 Operand->getStartLoc(),
3765 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003766 } else {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003767 InputDecls.push_back(OpDecl);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003768 InputDeclsOffsetOf.push_back(Operand->isOffsetOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003769 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosier4e472d22012-10-20 01:02:45 +00003770 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003771 Operand->getStartLoc(),
3772 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003773 }
3774 }
3775 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00003776 }
3777 }
3778
3779 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003780 NumOutputs = OutputDecls.size();
3781 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00003782
3783 // Set the unique clobbers.
3784 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3785 E = ClobberRegs.end(); I != E; ++I)
3786 Clobbers.push_back(*I);
3787
3788 // Merge the various outputs and inputs. Output are expected first.
3789 if (NumOutputs || NumInputs) {
3790 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003791 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003792 Constraints.resize(NumExprs);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003793 // FIXME: Constraints are hard coded to 'm', but we need an 'r'
3794 // constraint for offsetof. This needs to be cleaned up!
Chad Rosierb1f8c132012-10-18 15:49:34 +00003795 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003796 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsOffsetOf[i]);
3797 Constraints[i] = OutputDeclsOffsetOf[i] ? "=r" : OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003798 }
3799 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003800 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsOffsetOf[i]);
3801 Constraints[j] = InputDeclsOffsetOf[i] ? "r" : InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003802 }
3803 }
3804
3805 // Build the IR assembly string.
3806 std::string AsmStringIR;
Chad Rosier4e472d22012-10-20 01:02:45 +00003807 AsmRewriteKind PrevKind = AOK_Imm;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003808 raw_string_ostream OS(AsmStringIR);
3809 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
Chad Rosier4e472d22012-10-20 01:02:45 +00003810 for (SmallVectorImpl<struct AsmRewrite>::iterator
Chad Rosierb1f8c132012-10-18 15:49:34 +00003811 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3812 const char *Loc = (*I).Loc.getPointer();
Chad Rosier96d58e62012-10-19 20:57:14 +00003813
Chad Rosier4e472d22012-10-20 01:02:45 +00003814 AsmRewriteKind Kind = (*I).Kind;
Chad Rosier96d58e62012-10-19 20:57:14 +00003815
3816 // Emit everything up to the immediate/expression. If the previous rewrite
3817 // was a size directive, then this has already been done.
3818 if (PrevKind != AOK_SizeDirective)
3819 OS << StringRef(Start, Loc - Start);
3820 PrevKind = Kind;
3821
Chad Rosier5a719fc2012-10-23 17:43:43 +00003822 // Skip the original expression.
3823 if (Kind == AOK_Skip) {
3824 Start = Loc + (*I).Len;
3825 continue;
3826 }
3827
Chad Rosierb1f8c132012-10-18 15:49:34 +00003828 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00003829 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003830 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003831 case AOK_Imm:
Chad Rosierefcb3d92012-10-26 18:04:20 +00003832 OS << Twine("$$");
3833 OS << (*I).Val;
3834 break;
3835 case AOK_ImmPrefix:
3836 OS << Twine("$$");
Chad Rosierb1f8c132012-10-18 15:49:34 +00003837 break;
3838 case AOK_Input:
3839 OS << '$';
3840 OS << InputIdx++;
3841 break;
3842 case AOK_Output:
3843 OS << '$';
3844 OS << OutputIdx++;
3845 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00003846 case AOK_SizeDirective:
Chad Rosier6a020a72012-10-25 20:41:34 +00003847 switch((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00003848 default: break;
3849 case 8: OS << "byte ptr "; break;
3850 case 16: OS << "word ptr "; break;
3851 case 32: OS << "dword ptr "; break;
3852 case 64: OS << "qword ptr "; break;
3853 case 80: OS << "xword ptr "; break;
3854 case 128: OS << "xmmword ptr "; break;
3855 case 256: OS << "ymmword ptr "; break;
3856 }
Eli Friedman2128aae2012-10-22 23:58:19 +00003857 break;
3858 case AOK_Emit:
3859 OS << ".byte";
3860 break;
Chad Rosier6a020a72012-10-25 20:41:34 +00003861 case AOK_DotOperator:
3862 OS << (*I).Val;
3863 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003864 }
Chad Rosier96d58e62012-10-19 20:57:14 +00003865
Chad Rosierb1f8c132012-10-18 15:49:34 +00003866 // Skip the original expression.
Chad Rosier96d58e62012-10-19 20:57:14 +00003867 if (Kind != AOK_SizeDirective)
3868 Start = Loc + (*I).Len;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003869 }
3870
3871 // Emit the remainder of the asm string.
3872 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
3873 if (Start != AsmEnd)
3874 OS << StringRef(Start, AsmEnd - Start);
3875
3876 AsmString = OS.str();
3877 return false;
3878}
3879
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003880/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003881MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003882 MCContext &C, MCStreamer &Out,
3883 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003884 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003885}