blob: ab1210302dd186d23c2c8b4530dc49ca11fbd7e9 [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
Eli Bendersky4766ef42012-12-20 19:05:53 +0000308 // ".bundle_align_mode"
309 bool ParseDirectiveBundleAlignMode();
310 // ".bundle_lock"
311 bool ParseDirectiveBundleLock();
312 // ".bundle_unlock"
313 bool ParseDirectiveBundleUnlock();
314
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000315 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
316 /// accepts a single symbol (which should be a label or an external).
317 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000318
319 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
320
321 bool ParseDirectiveAbort(); // ".abort"
322 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000323 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000324
325 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000326 // ".ifb" or ".ifnb", depending on ExpectBlank.
327 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000328 // ".ifc" or ".ifnc", depending on ExpectEqual.
329 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000330 // ".ifdef" or ".ifndef", depending on expect_defined
331 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000332 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
333 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
334 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
335
336 /// ParseEscapedString - Parse the current token as a string which may include
337 /// escaped characters and return the string contents.
338 bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000339
340 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
341 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000342
Rafael Espindola761cb062012-06-03 23:57:14 +0000343 // Macro-like directives
344 Macro *ParseMacroLikeBody(SMLoc DirectiveLoc);
345 void InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
346 raw_svector_ostream &OS);
347 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000348 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000349 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000350 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000351
Eli Friedman2128aae2012-10-22 23:58:19 +0000352 // "_emit"
353 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000354};
355
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000356/// \brief Generic implementations of directive handling, etc. which is shared
357/// (or the default, at least) for all assembler parser.
358class GenericAsmParser : public MCAsmParserExtension {
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000359 template<bool (GenericAsmParser::*Handler)(StringRef, SMLoc)>
360 void AddDirectiveHandler(StringRef Directive) {
361 getParser().AddDirectiveHandler(this, Directive,
362 HandleDirective<GenericAsmParser, Handler>);
363 }
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000364public:
365 GenericAsmParser() {}
366
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000367 AsmParser &getParser() {
368 return (AsmParser&) this->MCAsmParserExtension::getParser();
369 }
370
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000371 virtual void Initialize(MCAsmParser &Parser) {
372 // Call the base implementation.
373 this->MCAsmParserExtension::Initialize(Parser);
374
375 // Debugging directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000376 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveFile>(".file");
377 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLine>(".line");
378 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLoc>(".loc");
Daniel Dunbar138abae2010-10-16 04:56:42 +0000379 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveStabs>(".stabs");
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000380
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000381 // CFI directives.
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000382 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFISections>(
383 ".cfi_sections");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000384 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIStartProc>(
385 ".cfi_startproc");
386 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIEndProc>(
387 ".cfi_endproc");
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000388 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfa>(
389 ".cfi_def_cfa");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000390 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaOffset>(
391 ".cfi_def_cfa_offset");
Rafael Espindola53abbe52011-04-11 20:29:16 +0000392 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset>(
393 ".cfi_adjust_cfa_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000394 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIDefCfaRegister>(
395 ".cfi_def_cfa_register");
396 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIOffset>(
397 ".cfi_offset");
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000398 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveCFIRelOffset>(
399 ".cfi_rel_offset");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000400 AddDirectiveHandler<
401 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_personality");
402 AddDirectiveHandler<
403 &GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda>(".cfi_lsda");
Rafael Espindolafe024d02010-12-28 18:36:23 +0000404 AddDirectiveHandler<
405 &GenericAsmParser::ParseDirectiveCFIRememberState>(".cfi_remember_state");
406 AddDirectiveHandler<
407 &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_state");
Rafael Espindolac5754392011-04-12 15:31:05 +0000408 AddDirectiveHandler<
409 &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000410 AddDirectiveHandler<
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000411 &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
412 AddDirectiveHandler<
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000413 &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
Rafael Espindola16d7d432012-01-23 21:51:52 +0000414 AddDirectiveHandler<
415 &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame");
Rafael Espindolac8fec7e2012-11-23 16:59:41 +0000416 AddDirectiveHandler<
417 &GenericAsmParser::ParseDirectiveCFIUndefined>(".cfi_undefined");
Rafael Espindolaf4f14f62012-11-25 15:14:49 +0000418 AddDirectiveHandler<
419 &GenericAsmParser::ParseDirectiveCFIRegister>(".cfi_register");
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000420
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000421 // Macro directives.
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +0000422 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
423 ".macros_on");
424 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
425 ".macros_off");
426 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacro>(".macro");
427 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endm");
428 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveEndMacro>(".endmacro");
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000429 AddDirectiveHandler<&GenericAsmParser::ParseDirectivePurgeMacro>(".purgem");
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000430
431 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".sleb128");
432 AddDirectiveHandler<&GenericAsmParser::ParseDirectiveLEB128>(".uleb128");
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000433 }
434
Roman Divacky54b0f4f2011-01-27 17:16:37 +0000435 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
436
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000437 bool ParseDirectiveFile(StringRef, SMLoc DirectiveLoc);
438 bool ParseDirectiveLine(StringRef, SMLoc DirectiveLoc);
439 bool ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar138abae2010-10-16 04:56:42 +0000440 bool ParseDirectiveStabs(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf9efd832011-05-10 01:10:18 +0000441 bool ParseDirectiveCFISections(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000442 bool ParseDirectiveCFIStartProc(StringRef, SMLoc DirectiveLoc);
443 bool ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab40a71f2010-12-29 01:42:56 +0000444 bool ParseDirectiveCFIDefCfa(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000445 bool ParseDirectiveCFIDefCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola53abbe52011-04-11 20:29:16 +0000446 bool ParseDirectiveCFIAdjustCfaOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000447 bool ParseDirectiveCFIDefCfaRegister(StringRef, SMLoc DirectiveLoc);
448 bool ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000449 bool ParseDirectiveCFIRelOffset(StringRef, SMLoc DirectiveLoc);
Rafael Espindola1fdfbc42010-11-16 18:34:07 +0000450 bool ParseDirectiveCFIPersonalityOrLsda(StringRef, SMLoc DirectiveLoc);
Rafael Espindolafe024d02010-12-28 18:36:23 +0000451 bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
452 bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac5754392011-04-12 15:31:05 +0000453 bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaed23bdb2011-12-29 21:43:03 +0000454 bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
Rafael Espindola6f0b1812011-12-29 20:24:47 +0000455 bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
Rafael Espindola16d7d432012-01-23 21:51:52 +0000456 bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
Rafael Espindolac8fec7e2012-11-23 16:59:41 +0000457 bool ParseDirectiveCFIUndefined(StringRef, SMLoc DirectiveLoc);
Rafael Espindolaf4f14f62012-11-25 15:14:49 +0000458 bool ParseDirectiveCFIRegister(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000459
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000460 bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000461 bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
462 bool ParseDirectiveEndMacro(StringRef, SMLoc DirectiveLoc);
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +0000463 bool ParseDirectivePurgeMacro(StringRef, SMLoc DirectiveLoc);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000464
Rafael Espindolab98ac2a2010-09-11 16:45:15 +0000465 bool ParseDirectiveLEB128(StringRef, SMLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000466};
467
468}
469
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000470namespace llvm {
471
472extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000473extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000474extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000475
476}
477
Chris Lattneraaec2052010-01-19 19:46:13 +0000478enum { DEFAULT_ADDRSPACE = 0 };
479
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000480AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000481 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000482 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Rafael Espindola5d7dcd32011-04-12 18:53:30 +0000483 GenericParser(new GenericAsmParser), PlatformParser(0),
Preston Gurd7b6f2032012-09-19 20:36:12 +0000484 CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000485 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000486 // Save the old handler.
487 SavedDiagHandler = SrcMgr.getDiagHandler();
488 SavedDiagContext = SrcMgr.getDiagContext();
489 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000490 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000491 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000492
493 // Initialize the generic parser.
494 GenericParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000495
496 // Initialize the platform / file format parser.
497 //
498 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
499 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000500 if (_MAI.hasMicrosoftFastStdCallMangling()) {
501 PlatformParser = createCOFFAsmParser();
502 PlatformParser->Initialize(*this);
503 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000504 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000505 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000506 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000507 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000508 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000509 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000510 }
Chris Lattnerebb89b42009-09-27 21:16:52 +0000511}
512
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000513AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000514 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
515
516 // Destroy any macros.
517 for (StringMap<Macro*>::iterator it = MacroMap.begin(),
518 ie = MacroMap.end(); it != ie; ++it)
519 delete it->getValue();
520
Daniel Dunbare4749702010-07-12 18:12:02 +0000521 delete PlatformParser;
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000522 delete GenericParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000523}
524
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000525void AsmParser::PrintMacroInstantiations() {
526 // Print the active macro instantiation stack.
527 for (std::vector<MacroInstantiation*>::const_reverse_iterator
528 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000529 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
530 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000531}
532
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000533bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000534 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000535 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000536 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000537 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000538 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000539}
540
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000541bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000542 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000543 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000544 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000545 return true;
546}
547
Sean Callananfd0b0282010-01-21 00:19:58 +0000548bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000549 std::string IncludedFile;
550 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000551 if (NewBuf == -1)
552 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000553
Sean Callananfd0b0282010-01-21 00:19:58 +0000554 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000555
Sean Callananfd0b0282010-01-21 00:19:58 +0000556 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000557
Sean Callananfd0b0282010-01-21 00:19:58 +0000558 return false;
559}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000560
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000561/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000562/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000563/// returns true on failure.
564bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
565 std::string IncludedFile;
566 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
567 if (NewBuf == -1)
568 return true;
569
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000570 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000571 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
572 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000573 return false;
574}
575
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000576void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
577 if (InBuffer != -1) {
578 CurBuffer = InBuffer;
579 } else {
580 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
581 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000582 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
583}
584
Sean Callananfd0b0282010-01-21 00:19:58 +0000585const AsmToken &AsmParser::Lex() {
586 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000587
Sean Callananfd0b0282010-01-21 00:19:58 +0000588 if (tok->is(AsmToken::Eof)) {
589 // If this is the end of an included file, pop the parent file off the
590 // include stack.
591 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
592 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000593 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000594 tok = &Lexer.Lex();
595 }
596 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000597
Sean Callananfd0b0282010-01-21 00:19:58 +0000598 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000599 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000600
Sean Callananfd0b0282010-01-21 00:19:58 +0000601 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000602}
603
Chris Lattner79180e22010-04-05 23:15:42 +0000604bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000605 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000606 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000607 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000608
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000609 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000610 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000611
612 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000613 AsmCond StartingCondState = TheCondState;
614
Kevin Enderby613b7572011-11-01 22:27:22 +0000615 // If we are generating dwarf for assembly source files save the initial text
616 // section and generate a .file directive.
617 if (getContext().getGenDwarfForAssembly()) {
618 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000619 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
620 getStreamer().EmitLabel(SectionStartSym);
621 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000622 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
Eric Christopher6c583142012-12-18 00:31:01 +0000623 StringRef(),
624 getContext().getMainFileName());
Kevin Enderby613b7572011-11-01 22:27:22 +0000625 }
626
Chris Lattnerb717fb02009-07-02 21:53:43 +0000627 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000628 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000629 ParseStatementInfo Info;
630 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000631
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000632 // We had an error, validate that one was emitted and recover by skipping to
633 // the next line.
634 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000635 EatToEndOfStatement();
636 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000637
638 if (TheCondState.TheCond != StartingCondState.TheCond ||
639 TheCondState.Ignore != StartingCondState.Ignore)
640 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000641
642 // Check to see there are no empty DwarfFile slots.
643 const std::vector<MCDwarfFile *> &MCDwarfFiles =
644 getContext().getMCDwarfFiles();
645 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000646 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000647 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000648 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000649
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000650 // Check to see that all assembler local symbols were actually defined.
651 // Targets that don't do subsections via symbols may not want this, though,
652 // so conservatively exclude them. Only do this if we're finalizing, though,
653 // as otherwise we won't necessarilly have seen everything yet.
654 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
655 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
656 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
657 e = Symbols.end();
658 i != e; ++i) {
659 MCSymbol *Sym = i->getValue();
660 // Variable symbols may not be marked as defined, so check those
661 // explicitly. If we know it's a variable, we have a definition for
662 // the purposes of this check.
663 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
664 // FIXME: We would really like to refer back to where the symbol was
665 // first referenced for a source location. We need to add something
666 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000667 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
668 "assembler local symbol '" + Sym->getName() +
669 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000670 }
671 }
672
673
Chris Lattner79180e22010-04-05 23:15:42 +0000674 // Finalize the output stream if there are no errors and if the client wants
675 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000676 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000677 Out.Finish();
678
Chris Lattnerb717fb02009-07-02 21:53:43 +0000679 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000680}
681
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000682void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000683 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000684 TokError("expected section directive before assembly directive");
685 Out.SwitchSection(Ctx.getMachOSection(
686 "__TEXT", "__text",
687 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
688 0, SectionKind::getText()));
689 }
690}
691
Chris Lattner2cf5f142009-06-22 01:29:09 +0000692/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
693void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000694 while (Lexer.isNot(AsmToken::EndOfStatement) &&
695 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000696 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000697
Chris Lattner2cf5f142009-06-22 01:29:09 +0000698 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000699 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000700 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000701}
702
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000703StringRef AsmParser::ParseStringToEndOfStatement() {
704 const char *Start = getTok().getLoc().getPointer();
705
706 while (Lexer.isNot(AsmToken::EndOfStatement) &&
707 Lexer.isNot(AsmToken::Eof))
708 Lex();
709
710 const char *End = getTok().getLoc().getPointer();
711 return StringRef(Start, End - Start);
712}
Chris Lattnerc4193832009-06-22 05:51:26 +0000713
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000714StringRef AsmParser::ParseStringToComma() {
715 const char *Start = getTok().getLoc().getPointer();
716
717 while (Lexer.isNot(AsmToken::EndOfStatement) &&
718 Lexer.isNot(AsmToken::Comma) &&
719 Lexer.isNot(AsmToken::Eof))
720 Lex();
721
722 const char *End = getTok().getLoc().getPointer();
723 return StringRef(Start, End - Start);
724}
725
Chris Lattner74ec1a32009-06-22 06:32:03 +0000726/// ParseParenExpr - Parse a paren expression and return it.
727/// NOTE: This assumes the leading '(' has already been consumed.
728///
729/// parenexpr ::= expr)
730///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000731bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000732 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000733 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000734 return TokError("expected ')' in parentheses expression");
Chris Lattnerb4307b32010-01-15 19:28:38 +0000735 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000736 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000737 return false;
738}
Chris Lattnerc4193832009-06-22 05:51:26 +0000739
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000740/// ParseBracketExpr - Parse a bracket expression and return it.
741/// NOTE: This assumes the leading '[' has already been consumed.
742///
743/// bracketexpr ::= expr]
744///
745bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
746 if (ParseExpression(Res)) return true;
747 if (Lexer.isNot(AsmToken::RBrac))
748 return TokError("expected ']' in brackets expression");
749 EndLoc = Lexer.getLoc();
750 Lex();
751 return false;
752}
753
Chris Lattner74ec1a32009-06-22 06:32:03 +0000754/// ParsePrimaryExpr - Parse a primary expression and return it.
755/// primaryexpr ::= (parenexpr
756/// primaryexpr ::= symbol
757/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000758/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000759/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000760bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000761 switch (Lexer.getKind()) {
762 default:
763 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000764 // If we have an error assume that we've already handled it.
765 case AsmToken::Error:
766 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000767 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000768 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000769 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000770 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000771 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000772 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000773 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000774 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000775 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000776 EndLoc = Lexer.getLoc();
777
778 StringRef Identifier;
779 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000780 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000781
Daniel Dunbarfffff912009-10-16 01:34:54 +0000782 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000783 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000784 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000785
786 // Lookup the symbol variant if used.
787 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000788 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000789 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000790 if (Variant == MCSymbolRefExpr::VK_Invalid) {
791 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000792 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000793 }
794 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000795
Daniel Dunbarfffff912009-10-16 01:34:54 +0000796 // If this is an absolute variable reference, substitute it now to preserve
797 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000798 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000799 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000800 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000801
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000802 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000803 return false;
804 }
805
806 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000807 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000808 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000809 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000810 case AsmToken::Integer: {
811 SMLoc Loc = getTok().getLoc();
812 int64_t IntVal = getTok().getIntVal();
813 Res = MCConstantExpr::Create(IntVal, getContext());
Chris Lattnerb4307b32010-01-15 19:28:38 +0000814 EndLoc = Lexer.getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000815 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000816 // Look for 'b' or 'f' following an Integer as a directional label
817 if (Lexer.getKind() == AsmToken::Identifier) {
818 StringRef IDVal = getTok().getString();
819 if (IDVal == "f" || IDVal == "b"){
820 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
821 IDVal == "f" ? 1 : 0);
822 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
823 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000824 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000825 return Error(Loc, "invalid reference to undefined symbol");
826 EndLoc = Lexer.getLoc();
827 Lex(); // Eat identifier.
828 }
829 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000830 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000831 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000832 case AsmToken::Real: {
833 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000834 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000835 Res = MCConstantExpr::Create(IntVal, getContext());
836 Lex(); // Eat token.
837 return false;
838 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000839 case AsmToken::Dot: {
840 // This is a '.' reference, which references the current PC. Emit a
841 // temporary label to the streamer and refer to it.
842 MCSymbol *Sym = Ctx.CreateTempSymbol();
843 Out.EmitLabel(Sym);
844 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
845 EndLoc = Lexer.getLoc();
846 Lex(); // Eat identifier.
847 return false;
848 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000849 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000850 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000851 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000852 case AsmToken::LBrac:
853 if (!PlatformParser->HasBracketExpressions())
854 return TokError("brackets expression not supported on this target");
855 Lex(); // Eat the '['.
856 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000857 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000858 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000859 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000860 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000861 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000862 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000863 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000864 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000865 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000866 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000867 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000868 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000869 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000870 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000871 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000872 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000873 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000874 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000875 }
876}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000877
Chris Lattnerb4307b32010-01-15 19:28:38 +0000878bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000879 SMLoc EndLoc;
880 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000881}
882
Daniel Dunbarcceba832010-09-17 02:47:07 +0000883const MCExpr *
884AsmParser::ApplyModifierToExpr(const MCExpr *E,
885 MCSymbolRefExpr::VariantKind Variant) {
886 // Recurse over the given expression, rebuilding it to apply the given variant
887 // if there is exactly one symbol.
888 switch (E->getKind()) {
889 case MCExpr::Target:
890 case MCExpr::Constant:
891 return 0;
892
893 case MCExpr::SymbolRef: {
894 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
895
896 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
897 TokError("invalid variant on expression '" +
898 getTok().getIdentifier() + "' (already modified)");
899 return E;
900 }
901
902 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
903 }
904
905 case MCExpr::Unary: {
906 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
907 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
908 if (!Sub)
909 return 0;
910 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
911 }
912
913 case MCExpr::Binary: {
914 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
915 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
916 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
917
918 if (!LHS && !RHS)
919 return 0;
920
921 if (!LHS) LHS = BE->getLHS();
922 if (!RHS) RHS = BE->getRHS();
923
924 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
925 }
926 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000927
Craig Topper85814382012-02-07 05:05:23 +0000928 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000929}
930
Chris Lattner74ec1a32009-06-22 06:32:03 +0000931/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000932///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000933/// expr ::= expr &&,|| expr -> lowest.
934/// expr ::= expr |,^,&,! expr
935/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
936/// expr ::= expr <<,>> expr
937/// expr ::= expr +,- expr
938/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000939/// expr ::= primaryexpr
940///
Chris Lattner54482b42010-01-15 19:39:23 +0000941bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000942 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000943 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000944 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
945 return true;
946
Daniel Dunbarcceba832010-09-17 02:47:07 +0000947 // As a special case, we support 'a op b @ modifier' by rewriting the
948 // expression to include the modifier. This is inefficient, but in general we
949 // expect users to use 'a@modifier op b'.
950 if (Lexer.getKind() == AsmToken::At) {
951 Lex();
952
953 if (Lexer.isNot(AsmToken::Identifier))
954 return TokError("unexpected symbol modifier following '@'");
955
956 MCSymbolRefExpr::VariantKind Variant =
957 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
958 if (Variant == MCSymbolRefExpr::VK_Invalid)
959 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
960
961 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
962 if (!ModifiedRes) {
963 return TokError("invalid modifier '" + getTok().getIdentifier() +
964 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000965 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000966
Daniel Dunbarcceba832010-09-17 02:47:07 +0000967 Res = ModifiedRes;
968 Lex();
969 }
970
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000971 // Try to constant fold it up front, if possible.
972 int64_t Value;
973 if (Res->EvaluateAsAbsolute(Value))
974 Res = MCConstantExpr::Create(Value, getContext());
975
976 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000977}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000978
Chris Lattnerb4307b32010-01-15 19:28:38 +0000979bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000980 Res = 0;
981 return ParseParenExpr(Res, EndLoc) ||
982 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000983}
984
Daniel Dunbar475839e2009-06-29 20:37:27 +0000985bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000986 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000987
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000988 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000989 if (ParseExpression(Expr))
990 return true;
991
Daniel Dunbare00b0112009-10-16 01:57:52 +0000992 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000993 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000994
995 return false;
996}
997
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000998static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000999 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001000 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001001 default:
1002 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +00001003
Jim Grosbachfbe16812011-08-20 16:24:13 +00001004 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +00001005 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001006 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001007 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001008 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001009 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001010 return 1;
1011
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001012
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001013 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +00001014 //
1015 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +00001016 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001017 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001018 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001019 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001020 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001021 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001022 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001023 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001024 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001025
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001026 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001027 case AsmToken::EqualEqual:
1028 Kind = MCBinaryExpr::EQ;
1029 return 3;
1030 case AsmToken::ExclaimEqual:
1031 case AsmToken::LessGreater:
1032 Kind = MCBinaryExpr::NE;
1033 return 3;
1034 case AsmToken::Less:
1035 Kind = MCBinaryExpr::LT;
1036 return 3;
1037 case AsmToken::LessEqual:
1038 Kind = MCBinaryExpr::LTE;
1039 return 3;
1040 case AsmToken::Greater:
1041 Kind = MCBinaryExpr::GT;
1042 return 3;
1043 case AsmToken::GreaterEqual:
1044 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001045 return 3;
1046
Jim Grosbachfbe16812011-08-20 16:24:13 +00001047 // Intermediate Precedence: <<, >>
1048 case AsmToken::LessLess:
1049 Kind = MCBinaryExpr::Shl;
1050 return 4;
1051 case AsmToken::GreaterGreater:
1052 Kind = MCBinaryExpr::Shr;
1053 return 4;
1054
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001055 // High Intermediate Precedence: +, -
1056 case AsmToken::Plus:
1057 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001058 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001059 case AsmToken::Minus:
1060 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001061 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001062
Jim Grosbachfbe16812011-08-20 16:24:13 +00001063 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001064 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001065 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001066 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001067 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001068 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001069 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001070 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001071 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001072 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001073 }
1074}
1075
1076
1077/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1078/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001079bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1080 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001081 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001082 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001083 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001084
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001085 // If the next token is lower precedence than we are allowed to eat, return
1086 // successfully with what we ate already.
1087 if (TokPrec < Precedence)
1088 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001089
Sean Callanan79ed1a82010-01-19 20:22:31 +00001090 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001091
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001092 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001093 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001094 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001095
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001096 // If BinOp binds less tightly with RHS than the operator after RHS, let
1097 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001098 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001099 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001100 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001101 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001102 }
1103
Daniel Dunbar475839e2009-06-29 20:37:27 +00001104 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001105 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001106 }
1107}
1108
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001109/// ParseStatement:
1110/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001111/// ::= Label* Directive ...Operands... EndOfStatement
1112/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001113bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001114 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001115 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001116 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001117 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001118 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001119
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001120 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001121 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001122 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001123 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001124 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001125 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001126 if (Lexer.is(AsmToken::Hash))
1127 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001128
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001129 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001130 if (Lexer.is(AsmToken::Integer)) {
1131 LocalLabelVal = getTok().getIntVal();
1132 if (LocalLabelVal < 0) {
1133 if (!TheCondState.Ignore)
1134 return TokError("unexpected token at start of statement");
1135 IDVal = "";
1136 }
1137 else {
1138 IDVal = getTok().getString();
1139 Lex(); // Consume the integer token to be used as an identifier token.
1140 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001141 if (!TheCondState.Ignore)
1142 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001143 }
1144 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001145
1146 } else if (Lexer.is(AsmToken::Dot)) {
1147 // Treat '.' as a valid identifier in this context.
1148 Lex();
1149 IDVal = ".";
1150
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001151 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001152 if (!TheCondState.Ignore)
1153 return TokError("unexpected token at start of statement");
1154 IDVal = "";
1155 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001156
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001157
Chris Lattner7834fac2010-04-17 18:14:27 +00001158 // Handle conditional assembly here before checking for skipping. We
1159 // have to do this so that .endif isn't skipped in a ".if 0" block for
1160 // example.
1161 if (IDVal == ".if")
1162 return ParseDirectiveIf(IDLoc);
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00001163 if (IDVal == ".ifb")
1164 return ParseDirectiveIfb(IDLoc, true);
1165 if (IDVal == ".ifnb")
1166 return ParseDirectiveIfb(IDLoc, false);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00001167 if (IDVal == ".ifc")
1168 return ParseDirectiveIfc(IDLoc, true);
1169 if (IDVal == ".ifnc")
1170 return ParseDirectiveIfc(IDLoc, false);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00001171 if (IDVal == ".ifdef")
1172 return ParseDirectiveIfdef(IDLoc, true);
1173 if (IDVal == ".ifndef" || IDVal == ".ifnotdef")
1174 return ParseDirectiveIfdef(IDLoc, false);
Chris Lattner7834fac2010-04-17 18:14:27 +00001175 if (IDVal == ".elseif")
1176 return ParseDirectiveElseIf(IDLoc);
1177 if (IDVal == ".else")
1178 return ParseDirectiveElse(IDLoc);
1179 if (IDVal == ".endif")
1180 return ParseDirectiveEndIf(IDLoc);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001181
Chris Lattner7834fac2010-04-17 18:14:27 +00001182 // If we are in a ".if 0" block, ignore this statement.
Chad Rosier17feeec2012-10-20 00:47:08 +00001183 if (TheCondState.Ignore) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001184 EatToEndOfStatement();
1185 return false;
1186 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001187
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001188 // FIXME: Recurse on local labels?
1189
1190 // See what kind of statement we have.
1191 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001192 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001193 CheckForValidSection();
1194
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001195 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001196 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001197
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001198 // Diagnose attempt to use '.' as a label.
1199 if (IDVal == ".")
1200 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1201
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001202 // Diagnose attempt to use a variable as a label.
1203 //
1204 // FIXME: Diagnostics. Note the location of the definition as a label.
1205 // FIXME: This doesn't diagnose assignment to a symbol which has been
1206 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001207 MCSymbol *Sym;
1208 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001209 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001210 else
1211 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001212 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001213 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001214
Daniel Dunbar959fd882009-08-26 22:13:22 +00001215 // Emit the label.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001216 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001217
Kevin Enderby94c2e852011-12-09 18:09:40 +00001218 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001219 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001220 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001221 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1222 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001223
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001224 // Consume any end of statement token, if present, to avoid spurious
1225 // AddBlankLine calls().
1226 if (Lexer.is(AsmToken::EndOfStatement)) {
1227 Lex();
1228 if (Lexer.is(AsmToken::Eof))
1229 return false;
1230 }
1231
Eli Friedman2128aae2012-10-22 23:58:19 +00001232 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001233 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001234
Daniel Dunbar3f872332009-07-28 16:08:33 +00001235 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001236 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001237 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001238
Nico Weber4c4c7322011-01-28 03:04:41 +00001239 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001240
1241 default: // Normal instruction or directive.
1242 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001243 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001244
1245 // If macros are enabled, check to see if this is a macro instantiation.
1246 if (MacrosEnabled)
1247 if (const Macro *M = MacroMap.lookup(IDVal))
1248 return HandleMacroEntry(IDVal, IDLoc, M);
1249
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001250 // Otherwise, we have a normal instruction or directive.
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001251 if (IDVal[0] == '.' && IDVal != ".") {
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001252
1253 // Target hook for parsing target specific directives.
1254 if (!getTargetParser().ParseDirective(ID))
1255 return false;
1256
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001257 // Assembler features
Roman Divacky50e7a782010-10-28 16:22:58 +00001258 if (IDVal == ".set" || IDVal == ".equ")
Nico Weber4c4c7322011-01-28 03:04:41 +00001259 return ParseDirectiveSet(IDVal, true);
1260 if (IDVal == ".equiv")
1261 return ParseDirectiveSet(IDVal, false);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001262
Daniel Dunbara0d14262009-06-24 23:30:00 +00001263 // Data directives
1264
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001265 if (IDVal == ".ascii")
Rafael Espindola787c3372010-10-28 20:02:27 +00001266 return ParseDirectiveAscii(IDVal, false);
1267 if (IDVal == ".asciz" || IDVal == ".string")
1268 return ParseDirectiveAscii(IDVal, true);
Daniel Dunbara0d14262009-06-24 23:30:00 +00001269
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001270 if (IDVal == ".byte")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001271 return ParseDirectiveValue(1);
Kevin Enderby9c656452009-09-10 20:51:44 +00001272 if (IDVal == ".short")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001273 return ParseDirectiveValue(2);
Rafael Espindolacc3acee2010-11-01 15:29:07 +00001274 if (IDVal == ".value")
1275 return ParseDirectiveValue(2);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001276 if (IDVal == ".2byte")
1277 return ParseDirectiveValue(2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001278 if (IDVal == ".long")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001279 return ParseDirectiveValue(4);
Rafael Espindola435279b2010-11-17 16:24:40 +00001280 if (IDVal == ".int")
1281 return ParseDirectiveValue(4);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001282 if (IDVal == ".4byte")
1283 return ParseDirectiveValue(4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001284 if (IDVal == ".quad")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001285 return ParseDirectiveValue(8);
Rafael Espindola110f22a2010-11-17 16:15:42 +00001286 if (IDVal == ".8byte")
1287 return ParseDirectiveValue(8);
Roman Divacky14e66552011-01-28 14:20:32 +00001288 if (IDVal == ".single" || IDVal == ".float")
Daniel Dunbarb95a0792010-09-24 01:59:56 +00001289 return ParseDirectiveRealValue(APFloat::IEEEsingle);
1290 if (IDVal == ".double")
1291 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001292
Eli Friedman5d68ec22010-07-19 04:17:25 +00001293 if (IDVal == ".align") {
1294 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1295 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1296 }
1297 if (IDVal == ".align32") {
1298 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1299 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1300 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001301 if (IDVal == ".balign")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001302 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001303 if (IDVal == ".balignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001304 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001305 if (IDVal == ".balignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001306 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001307 if (IDVal == ".p2align")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001308 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001309 if (IDVal == ".p2alignw")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001310 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001311 if (IDVal == ".p2alignl")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001312 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1313
Eli Bendersky4766ef42012-12-20 19:05:53 +00001314 if (IDVal == ".bundle_align_mode")
1315 return ParseDirectiveBundleAlignMode();
1316 if (IDVal == ".bundle_lock")
1317 return ParseDirectiveBundleLock();
1318 if (IDVal == ".bundle_unlock")
1319 return ParseDirectiveBundleUnlock();
1320
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001321 if (IDVal == ".org")
Daniel Dunbarc238b582009-06-25 22:44:51 +00001322 return ParseDirectiveOrg();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001323
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001324 if (IDVal == ".fill")
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001325 return ParseDirectiveFill();
Rafael Espindolace8463f2011-04-07 20:26:23 +00001326 if (IDVal == ".space" || IDVal == ".skip")
Daniel Dunbara0d14262009-06-24 23:30:00 +00001327 return ParseDirectiveSpace();
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00001328 if (IDVal == ".zero")
1329 return ParseDirectiveZero();
Daniel Dunbara0d14262009-06-24 23:30:00 +00001330
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001331 // Symbol attribute directives
Daniel Dunbard0c14d62009-08-11 04:24:50 +00001332
Benjamin Kramere14a3c52012-05-12 11:18:59 +00001333 if (IDVal == ".extern") {
1334 EatToEndOfStatement(); // .extern is the default, ignore it.
1335 return false;
1336 }
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001337 if (IDVal == ".globl" || IDVal == ".global")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001338 return ParseDirectiveSymbolAttribute(MCSA_Global);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001339 if (IDVal == ".indirect_symbol")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001340 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001341 if (IDVal == ".lazy_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001342 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001343 if (IDVal == ".no_dead_strip")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001344 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Kevin Enderbye8e98d72010-11-19 18:39:33 +00001345 if (IDVal == ".symbol_resolver")
1346 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001347 if (IDVal == ".private_extern")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001348 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001349 if (IDVal == ".reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001350 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001351 if (IDVal == ".weak_definition")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001352 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001353 if (IDVal == ".weak_reference")
Chris Lattnera5ad93a2010-01-23 06:39:22 +00001354 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Kevin Enderbyf59cac52010-07-08 17:22:42 +00001355 if (IDVal == ".weak_def_can_be_hidden")
1356 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00001357
Hans Wennborg5cc64912011-06-18 13:51:54 +00001358 if (IDVal == ".comm" || IDVal == ".common")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001359 return ParseDirectiveComm(/*IsLocal=*/false);
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001360 if (IDVal == ".lcomm")
Chris Lattner1fc3d752009-07-09 17:25:12 +00001361 return ParseDirectiveComm(/*IsLocal=*/true);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00001362
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001363 if (IDVal == ".abort")
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00001364 return ParseDirectiveAbort();
Daniel Dunbar9a7e2cc2009-07-27 21:49:56 +00001365 if (IDVal == ".include")
Kevin Enderby1f049b22009-07-14 23:21:55 +00001366 return ParseDirectiveInclude();
Kevin Enderbyc55acca2011-12-14 21:47:48 +00001367 if (IDVal == ".incbin")
1368 return ParseDirectiveIncbin();
Kevin Enderbya5c78322009-07-13 21:03:15 +00001369
Benjamin Kramer5cdf0ad2012-05-12 11:19:04 +00001370 if (IDVal == ".code16" || IDVal == ".code16gcc")
Roman Divackyf6fbd842011-01-31 20:56:49 +00001371 return TokError(Twine(IDVal) + " not supported yet");
Roman Divackycb727802011-01-28 19:29:48 +00001372
Rafael Espindola761cb062012-06-03 23:57:14 +00001373 // Macro-like directives
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001374 if (IDVal == ".rept")
1375 return ParseDirectiveRept(IDLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001376 if (IDVal == ".irp")
1377 return ParseDirectiveIrp(IDLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00001378 if (IDVal == ".irpc")
1379 return ParseDirectiveIrpc(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001380 if (IDVal == ".endr")
Rafael Espindola761cb062012-06-03 23:57:14 +00001381 return ParseDirectiveEndr(IDLoc);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00001382
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001383 // Look up the handler in the handler table.
1384 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1385 DirectiveMap.lookup(IDVal);
1386 if (Handler.first)
Daniel Dunbar1edf6ca2010-07-18 22:22:07 +00001387 return (*Handler.second)(Handler.first, IDVal, IDLoc);
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00001388
Kevin Enderby9c656452009-09-10 20:51:44 +00001389
Jim Grosbach686c0182012-05-01 18:38:27 +00001390 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001391 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001392
Eli Friedman2128aae2012-10-22 23:58:19 +00001393 // _emit
1394 if (ParsingInlineAsm && IDVal == "_emit")
1395 return ParseDirectiveEmit(IDLoc, Info);
1396
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001397 CheckForValidSection();
1398
Chris Lattnera7f13542010-05-19 23:34:33 +00001399 // Canonicalize the opcode to lower case.
Chad Rosier8f138d12012-10-15 17:19:13 +00001400 SmallString<128> OpcodeStr;
Chris Lattnera7f13542010-05-19 23:34:33 +00001401 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
Chad Rosier8f138d12012-10-15 17:19:13 +00001402 OpcodeStr.push_back(tolower(IDVal[i]));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001403
Chad Rosier6a020a72012-10-25 20:41:34 +00001404 ParseInstructionInfo IInfo(Info.AsmRewrites);
1405 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1406 IDLoc,Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001407 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001408
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001409 // Dump the parsed representation, if requested.
1410 if (getShowParsedOperands()) {
1411 SmallString<256> Str;
1412 raw_svector_ostream OS(Str);
1413 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001414 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001415 if (i != 0)
1416 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001417 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001418 }
1419 OS << "]";
1420
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001421 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001422 }
1423
Kevin Enderby613b7572011-11-01 22:27:22 +00001424 // If we are generating dwarf for assembly source files and the current
1425 // section is the initial text section then generate a .loc directive for
1426 // the instruction.
1427 if (!HadError && getContext().getGenDwarfForAssembly() &&
Eric Christopher2318ba12012-12-18 00:30:54 +00001428 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001429
1430 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1431
1432 // If we previously parsed a cpp hash file line comment then make sure the
1433 // current Dwarf File is for the CppHashFilename if not then emit the
1434 // Dwarf File table for it and adjust the line number for the .loc.
1435 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1436 getContext().getMCDwarfFiles();
1437 if (CppHashFilename.size() != 0) {
1438 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1439 CppHashFilename)
Eric Christopher2318ba12012-12-18 00:30:54 +00001440 getStreamer().EmitDwarfFileDirective(
1441 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001442
Kevin Enderby32c1a822012-11-05 21:55:41 +00001443 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
Kevin Enderby938482f2012-11-01 17:31:35 +00001444 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1445 }
1446
Kevin Enderby613b7572011-11-01 22:27:22 +00001447 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001448 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001449 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001450 StringRef());
1451 }
1452
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001453 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001454 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001455 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001456 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1457 Info.ParsedOperands,
1458 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001459 ParsingInlineAsm);
1460 }
Chris Lattner98986712010-01-14 22:21:20 +00001461
Chris Lattnercbf8a982010-09-11 16:18:25 +00001462 // Don't skip the rest of the line, the instruction parser is responsible for
1463 // that.
1464 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001465}
Chris Lattner9a023f72009-06-24 04:43:34 +00001466
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001467/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1468/// since they may not be able to be tokenized to get to the end of line token.
1469void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001470 if (!Lexer.is(AsmToken::EndOfStatement))
1471 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001472 // Eat EOL.
1473 Lex();
1474}
1475
1476/// ParseCppHashLineFilenameComment as this:
1477/// ::= # number "filename"
1478/// or just as a full line comment if it doesn't have a number and a string.
1479bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1480 Lex(); // Eat the hash token.
1481
1482 if (getLexer().isNot(AsmToken::Integer)) {
1483 // Consume the line since in cases it is not a well-formed line directive,
1484 // as if were simply a full line comment.
1485 EatToEndOfLine();
1486 return false;
1487 }
1488
1489 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001490 Lex();
1491
1492 if (getLexer().isNot(AsmToken::String)) {
1493 EatToEndOfLine();
1494 return false;
1495 }
1496
1497 StringRef Filename = getTok().getString();
1498 // Get rid of the enclosing quotes.
1499 Filename = Filename.substr(1, Filename.size()-2);
1500
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001501 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1502 CppHashLoc = L;
1503 CppHashFilename = Filename;
1504 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001505 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001506
1507 // Ignore any trailing characters, they're just comment.
1508 EatToEndOfLine();
1509 return false;
1510}
1511
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001512/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001513/// for the Filename and LineNo if any in the diagnostic.
1514void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1515 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1516 raw_ostream &OS = errs();
1517
1518 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1519 const SMLoc &DiagLoc = Diag.getLoc();
1520 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1521 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1522
1523 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1524 // before printing the message.
1525 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001526 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001527 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1528 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1529 }
1530
Eric Christopher2318ba12012-12-18 00:30:54 +00001531 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001532 // manager changed or buffer changed (like in a nested include) then just
1533 // print the normal diagnostic using its Filename and LineNo.
1534 if (!Parser->CppHashLineNumber ||
1535 &DiagSrcMgr != &Parser->SrcMgr ||
1536 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001537 if (Parser->SavedDiagHandler)
1538 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1539 else
1540 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001541 return;
1542 }
1543
Eric Christopher2318ba12012-12-18 00:30:54 +00001544 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001545 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1546 // the diagnostic.
1547 const std::string Filename = Parser->CppHashFilename;
1548
1549 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1550 int CppHashLocLineNo =
1551 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1552 int LineNo = Parser->CppHashLineNumber - 1 +
1553 (DiagLocLineNo - CppHashLocLineNo);
1554
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001555 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1556 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001557 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001558 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001559
Benjamin Kramer04a04262011-10-16 10:48:29 +00001560 if (Parser->SavedDiagHandler)
1561 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1562 else
1563 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001564}
1565
Rafael Espindola799aacf2012-08-21 18:29:30 +00001566// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1567// difference being that that function accepts '@' as part of identifiers and
1568// we can't do that. AsmLexer.cpp should probably be changed to handle
1569// '@' as a special case when needed.
1570static bool isIdentifierChar(char c) {
1571 return isalnum(c) || c == '_' || c == '$' || c == '.';
1572}
1573
Rafael Espindola761cb062012-06-03 23:57:14 +00001574bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Rafael Espindola8a403d32012-08-08 14:51:03 +00001575 const MacroParameters &Parameters,
1576 const MacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001577 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001578 unsigned NParameters = Parameters.size();
1579 if (NParameters != 0 && NParameters != A.size())
1580 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001581
Preston Gurd7b6f2032012-09-19 20:36:12 +00001582 // A macro without parameters is handled differently on Darwin:
1583 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001584 while (!Body.empty()) {
1585 // Scan for the next substitution.
1586 std::size_t End = Body.size(), Pos = 0;
1587 for (; Pos != End; ++Pos) {
1588 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001589 if (!NParameters) {
1590 // This macro has no parameters, look for $0, $1, etc.
1591 if (Body[Pos] != '$' || Pos + 1 == End)
1592 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001593
Rafael Espindola65366442011-06-05 02:43:45 +00001594 char Next = Body[Pos + 1];
1595 if (Next == '$' || Next == 'n' || isdigit(Next))
1596 break;
1597 } else {
1598 // This macro has parameters, look for \foo, \bar, etc.
1599 if (Body[Pos] == '\\' && Pos + 1 != End)
1600 break;
1601 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001602 }
1603
1604 // Add the prefix.
1605 OS << Body.slice(0, Pos);
1606
1607 // Check if we reached the end.
1608 if (Pos == End)
1609 break;
1610
Rafael Espindola65366442011-06-05 02:43:45 +00001611 if (!NParameters) {
1612 switch (Body[Pos+1]) {
1613 // $$ => $
1614 case '$':
1615 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001616 break;
1617
Rafael Espindola65366442011-06-05 02:43:45 +00001618 // $n => number of arguments
1619 case 'n':
1620 OS << A.size();
1621 break;
1622
1623 // $[0-9] => argument
1624 default: {
1625 // Missing arguments are ignored.
1626 unsigned Index = Body[Pos+1] - '0';
1627 if (Index >= A.size())
1628 break;
1629
1630 // Otherwise substitute with the token values, with spaces eliminated.
Rafael Espindola28c1f6662012-06-03 22:41:23 +00001631 for (MacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001632 ie = A[Index].end(); it != ie; ++it)
1633 OS << it->getString();
1634 break;
1635 }
1636 }
1637 Pos += 2;
1638 } else {
1639 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001640 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001641 ++I;
1642
1643 const char *Begin = Body.data() + Pos +1;
1644 StringRef Argument(Begin, I - (Pos +1));
1645 unsigned Index = 0;
1646 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001647 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001648 break;
1649
Preston Gurd7b6f2032012-09-19 20:36:12 +00001650 if (Index == NParameters) {
1651 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1652 Pos += 3;
1653 else {
1654 OS << '\\' << Argument;
1655 Pos = I;
1656 }
1657 } else {
1658 for (MacroArgument::const_iterator it = A[Index].begin(),
1659 ie = A[Index].end(); it != ie; ++it)
1660 if (it->getKind() == AsmToken::String)
1661 OS << it->getStringContents();
1662 else
1663 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001664
Preston Gurd7b6f2032012-09-19 20:36:12 +00001665 Pos += 1 + Argument.size();
1666 }
Rafael Espindola65366442011-06-05 02:43:45 +00001667 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001668 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001669 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001670 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001671
Rafael Espindola65366442011-06-05 02:43:45 +00001672 return false;
1673}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001674
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001675MacroInstantiation::MacroInstantiation(const Macro *M, SMLoc IL,
1676 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001677 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001678 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1679 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001680{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001681}
1682
Preston Gurd7b6f2032012-09-19 20:36:12 +00001683static bool IsOperator(AsmToken::TokenKind kind)
1684{
1685 switch (kind)
1686 {
1687 default:
1688 return false;
1689 case AsmToken::Plus:
1690 case AsmToken::Minus:
1691 case AsmToken::Tilde:
1692 case AsmToken::Slash:
1693 case AsmToken::Star:
1694 case AsmToken::Dot:
1695 case AsmToken::Equal:
1696 case AsmToken::EqualEqual:
1697 case AsmToken::Pipe:
1698 case AsmToken::PipePipe:
1699 case AsmToken::Caret:
1700 case AsmToken::Amp:
1701 case AsmToken::AmpAmp:
1702 case AsmToken::Exclaim:
1703 case AsmToken::ExclaimEqual:
1704 case AsmToken::Percent:
1705 case AsmToken::Less:
1706 case AsmToken::LessEqual:
1707 case AsmToken::LessLess:
1708 case AsmToken::LessGreater:
1709 case AsmToken::Greater:
1710 case AsmToken::GreaterEqual:
1711 case AsmToken::GreaterGreater:
1712 return true;
1713 }
1714}
1715
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001716/// ParseMacroArgument - Extract AsmTokens for a macro argument.
1717/// This is used for both default macro parameter values and the
1718/// arguments in macro invocations
Preston Gurd7b6f2032012-09-19 20:36:12 +00001719bool AsmParser::ParseMacroArgument(MacroArgument &MA,
1720 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001721 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001722 unsigned AddTokens = 0;
1723
1724 // gas accepts arguments separated by whitespace, except on Darwin
1725 if (!IsDarwin)
1726 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001727
1728 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001729 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1730 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001731 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001732 }
1733
1734 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1735 // Spaces and commas cannot be mixed to delimit parameters
1736 if (ArgumentDelimiter == AsmToken::Eof)
1737 ArgumentDelimiter = AsmToken::Comma;
1738 else if (ArgumentDelimiter != AsmToken::Comma) {
1739 Lexer.setSkipSpace(true);
1740 return TokError("expected ' ' for macro argument separator");
1741 }
1742 break;
1743 }
1744
1745 if (Lexer.is(AsmToken::Space)) {
1746 Lex(); // Eat spaces
1747
1748 // Spaces can delimit parameters, but could also be part an expression.
1749 // If the token after a space is an operator, add the token and the next
1750 // one into this argument
1751 if (ArgumentDelimiter == AsmToken::Space ||
1752 ArgumentDelimiter == AsmToken::Eof) {
1753 if (IsOperator(Lexer.getKind())) {
1754 // Check to see whether the token is used as an operator,
1755 // or part of an identifier
1756 const char *NextChar = getTok().getEndLoc().getPointer() + 1;
1757 if (*NextChar == ' ')
1758 AddTokens = 2;
1759 }
1760
1761 if (!AddTokens && ParenLevel == 0) {
1762 if (ArgumentDelimiter == AsmToken::Eof &&
1763 !IsOperator(Lexer.getKind()))
1764 ArgumentDelimiter = AsmToken::Space;
1765 break;
1766 }
1767 }
1768 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001769
1770 // HandleMacroEntry relies on not advancing the lexer here
1771 // to be able to fill in the remaining default parameter values
1772 if (Lexer.is(AsmToken::EndOfStatement))
1773 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001774
1775 // Adjust the current parentheses level.
1776 if (Lexer.is(AsmToken::LParen))
1777 ++ParenLevel;
1778 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1779 --ParenLevel;
1780
1781 // Append the token to the current argument list.
1782 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001783 if (AddTokens)
1784 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001785 Lex();
1786 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001787
1788 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001789 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001790 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001791 return false;
1792}
1793
1794// Parse the macro instantiation arguments.
Rafael Espindola8a403d32012-08-08 14:51:03 +00001795bool AsmParser::ParseMacroArguments(const Macro *M, MacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001796 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001797 // Argument delimiter is initially unknown. It will be set by
1798 // ParseMacroArgument()
1799 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001800
1801 // Parse two kinds of macro invocations:
1802 // - macros defined without any parameters accept an arbitrary number of them
1803 // - macros defined with parameters accept at most that many of them
1804 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1805 ++Parameter) {
1806 MacroArgument MA;
1807
Preston Gurd7b6f2032012-09-19 20:36:12 +00001808 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001809 return true;
1810
Preston Gurd6c9176a2012-09-19 20:29:04 +00001811 if (!MA.empty() || !NParameters)
1812 A.push_back(MA);
1813 else if (NParameters) {
1814 if (!M->Parameters[Parameter].second.empty())
1815 A.push_back(M->Parameters[Parameter].second);
1816 }
Jim Grosbach97146442012-07-30 22:44:17 +00001817
Preston Gurd6c9176a2012-09-19 20:29:04 +00001818 // At the end of the statement, fill in remaining arguments that have
1819 // default values. If there aren't any, then the next argument is
1820 // required but missing
1821 if (Lexer.is(AsmToken::EndOfStatement)) {
1822 if (NParameters && Parameter < NParameters - 1) {
1823 if (M->Parameters[Parameter + 1].second.empty())
1824 return TokError("macro argument '" +
1825 Twine(M->Parameters[Parameter + 1].first) +
1826 "' is missing");
1827 else
1828 continue;
1829 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001830 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001831 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001832
1833 if (Lexer.is(AsmToken::Comma))
1834 Lex();
1835 }
1836 return TokError("Too many arguments");
1837}
1838
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001839bool AsmParser::HandleMacroEntry(StringRef Name, SMLoc NameLoc,
1840 const Macro *M) {
1841 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1842 // this, although we should protect against infinite loops.
1843 if (ActiveMacros.size() == 20)
1844 return TokError("macros cannot be nested more than 20 levels deep");
1845
Rafael Espindola8a403d32012-08-08 14:51:03 +00001846 MacroArguments A;
1847 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001848 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001849
Jim Grosbach97146442012-07-30 22:44:17 +00001850 // Remove any trailing empty arguments. Do this after-the-fact as we have
1851 // to keep empty arguments in the middle of the list or positionality
1852 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001853 while (!A.empty() && A.back().empty())
1854 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001855
Rafael Espindola65366442011-06-05 02:43:45 +00001856 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1857 // to hold the macro body with substitutions.
1858 SmallString<256> Buf;
1859 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001860 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001861
Rafael Espindola8a403d32012-08-08 14:51:03 +00001862 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001863 return true;
1864
Rafael Espindola761cb062012-06-03 23:57:14 +00001865 // We include the .endmacro in the buffer as our queue to exit the macro
1866 // instantiation.
1867 OS << ".endmacro\n";
1868
Rafael Espindola65366442011-06-05 02:43:45 +00001869 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001870 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001871
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001872 // Create the macro instantiation object and add to the current macro
1873 // instantiation stack.
1874 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001875 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001876 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001877 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001878 ActiveMacros.push_back(MI);
1879
1880 // Jump to the macro instantiation and prime the lexer.
1881 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1882 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1883 Lex();
1884
1885 return false;
1886}
1887
1888void AsmParser::HandleMacroExit() {
1889 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001890 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001891 Lex();
1892
1893 // Pop the instantiation entry.
1894 delete ActiveMacros.back();
1895 ActiveMacros.pop_back();
1896}
1897
Rafael Espindolae71cc862012-01-28 05:57:00 +00001898static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001899 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001900 case MCExpr::Binary: {
1901 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1902 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001903 break;
1904 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001905 case MCExpr::Target:
1906 case MCExpr::Constant:
1907 return false;
1908 case MCExpr::SymbolRef: {
1909 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001910 if (S.isVariable())
1911 return IsUsedIn(Sym, S.getVariableValue());
1912 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001913 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001914 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001915 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001916 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001917
1918 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001919}
1920
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001921bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1922 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001923 // FIXME: Use better location, we should use proper tokens.
1924 SMLoc EqualLoc = Lexer.getLoc();
1925
Daniel Dunbar821e3332009-08-31 08:09:28 +00001926 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001927 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001928 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001929
Rafael Espindolae71cc862012-01-28 05:57:00 +00001930 // Note: we don't count b as used in "a = b". This is to allow
1931 // a = b
1932 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001933
Daniel Dunbar3f872332009-07-28 16:08:33 +00001934 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001935 return TokError("unexpected token in assignment");
1936
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001937 // Error on assignment to '.'.
1938 if (Name == ".") {
1939 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1940 "(use '.space' or '.org').)"));
1941 }
1942
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001943 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001944 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001945
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001946 // Validate that the LHS is allowed to be a variable (either it has not been
1947 // used as a symbol, or it is an absolute symbol).
1948 MCSymbol *Sym = getContext().LookupSymbol(Name);
1949 if (Sym) {
1950 // Diagnose assignment to a label.
1951 //
1952 // FIXME: Diagnostics. Note the location of the definition as a label.
1953 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00001954 if (IsUsedIn(Sym, Value))
1955 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1956 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001957 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00001958 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1959 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00001960 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001961 return Error(EqualLoc, "redefinition of '" + Name + "'");
1962 else if (!Sym->isVariable())
1963 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00001964 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001965 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1966 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001967
1968 // Don't count these checks as uses.
1969 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001970 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001971 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001972
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001973 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001974
1975 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00001976 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001977 if (NoDeadStrip)
1978 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
1979
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001980
1981 return false;
1982}
1983
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001984/// ParseIdentifier:
1985/// ::= identifier
1986/// ::= string
1987bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00001988 // The assembler has relaxed rules for accepting identifiers, in particular we
1989 // allow things like '.globl $foo', which would normally be separate
1990 // tokens. At this level, we have already lexed so we cannot (currently)
1991 // handle this as a context dependent token, instead we detect adjacent tokens
1992 // and return the combined identifier.
1993 if (Lexer.is(AsmToken::Dollar)) {
1994 SMLoc DollarLoc = getLexer().getLoc();
1995
1996 // Consume the dollar sign, and check for a following identifier.
1997 Lex();
1998 if (Lexer.isNot(AsmToken::Identifier))
1999 return true;
2000
2001 // We have a '$' followed by an identifier, make sure they are adjacent.
2002 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2003 return true;
2004
2005 // Construct the joined identifier and consume the token.
2006 Res = StringRef(DollarLoc.getPointer(),
2007 getTok().getIdentifier().size() + 1);
2008 Lex();
2009 return false;
2010 }
2011
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002012 if (Lexer.isNot(AsmToken::Identifier) &&
2013 Lexer.isNot(AsmToken::String))
2014 return true;
2015
Sean Callanan18b83232010-01-19 21:44:56 +00002016 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002017
Sean Callanan79ed1a82010-01-19 20:22:31 +00002018 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002019
2020 return false;
2021}
2022
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002023/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002024/// ::= .equ identifier ',' expression
2025/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002026/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002027bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002028 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002029
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002030 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002031 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002032
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002033 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002034 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002035 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002036
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002037 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002038}
2039
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002040bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002041 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002042
2043 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002044 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002045 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2046 if (Str[i] != '\\') {
2047 Data += Str[i];
2048 continue;
2049 }
2050
2051 // Recognize escaped characters. Note that this escape semantics currently
2052 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2053 ++i;
2054 if (i == e)
2055 return TokError("unexpected backslash at end of string");
2056
2057 // Recognize octal sequences.
2058 if ((unsigned) (Str[i] - '0') <= 7) {
2059 // Consume up to three octal characters.
2060 unsigned Value = Str[i] - '0';
2061
2062 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2063 ++i;
2064 Value = Value * 8 + (Str[i] - '0');
2065
2066 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2067 ++i;
2068 Value = Value * 8 + (Str[i] - '0');
2069 }
2070 }
2071
2072 if (Value > 255)
2073 return TokError("invalid octal escape sequence (out of range)");
2074
2075 Data += (unsigned char) Value;
2076 continue;
2077 }
2078
2079 // Otherwise recognize individual escapes.
2080 switch (Str[i]) {
2081 default:
2082 // Just reject invalid escape sequences for now.
2083 return TokError("invalid escape sequence (unrecognized character)");
2084
2085 case 'b': Data += '\b'; break;
2086 case 'f': Data += '\f'; break;
2087 case 'n': Data += '\n'; break;
2088 case 'r': Data += '\r'; break;
2089 case 't': Data += '\t'; break;
2090 case '"': Data += '"'; break;
2091 case '\\': Data += '\\'; break;
2092 }
2093 }
2094
2095 return false;
2096}
2097
Daniel Dunbara0d14262009-06-24 23:30:00 +00002098/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002099/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2100bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002101 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002102 CheckForValidSection();
2103
Daniel Dunbara0d14262009-06-24 23:30:00 +00002104 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002105 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002106 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002107
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002108 std::string Data;
2109 if (ParseEscapedString(Data))
2110 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002111
2112 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002113 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002114 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2115
Sean Callanan79ed1a82010-01-19 20:22:31 +00002116 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002117
2118 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002119 break;
2120
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002121 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002122 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002123 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002124 }
2125 }
2126
Sean Callanan79ed1a82010-01-19 20:22:31 +00002127 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002128 return false;
2129}
2130
2131/// ParseDirectiveValue
2132/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2133bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002134 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002135 CheckForValidSection();
2136
Daniel Dunbara0d14262009-06-24 23:30:00 +00002137 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002138 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002139 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002140 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002141 return true;
2142
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002143 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002144 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2145 assert(Size <= 8 && "Invalid size");
2146 uint64_t IntValue = MCE->getValue();
2147 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2148 return Error(ExprLoc, "literal value out of range for directive");
2149 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2150 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002151 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002152
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002153 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002154 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002155
Daniel Dunbara0d14262009-06-24 23:30:00 +00002156 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002157 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002158 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002159 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002160 }
2161 }
2162
Sean Callanan79ed1a82010-01-19 20:22:31 +00002163 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002164 return false;
2165}
2166
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002167/// ParseDirectiveRealValue
2168/// ::= (.single | .double) [ expression (, expression)* ]
2169bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2170 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2171 CheckForValidSection();
2172
2173 for (;;) {
2174 // We don't truly support arithmetic on floating point expressions, so we
2175 // have to manually parse unary prefixes.
2176 bool IsNeg = false;
2177 if (getLexer().is(AsmToken::Minus)) {
2178 Lex();
2179 IsNeg = true;
2180 } else if (getLexer().is(AsmToken::Plus))
2181 Lex();
2182
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002183 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002184 getLexer().isNot(AsmToken::Real) &&
2185 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002186 return TokError("unexpected token in directive");
2187
2188 // Convert to an APFloat.
2189 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002190 StringRef IDVal = getTok().getString();
2191 if (getLexer().is(AsmToken::Identifier)) {
2192 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2193 Value = APFloat::getInf(Semantics);
2194 else if (!IDVal.compare_lower("nan"))
2195 Value = APFloat::getNaN(Semantics, false, ~0);
2196 else
2197 return TokError("invalid floating point literal");
2198 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002199 APFloat::opInvalidOp)
2200 return TokError("invalid floating point literal");
2201 if (IsNeg)
2202 Value.changeSign();
2203
2204 // Consume the numeric token.
2205 Lex();
2206
2207 // Emit the value as an integer.
2208 APInt AsInt = Value.bitcastToAPInt();
2209 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2210 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2211
2212 if (getLexer().is(AsmToken::EndOfStatement))
2213 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002214
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002215 if (getLexer().isNot(AsmToken::Comma))
2216 return TokError("unexpected token in directive");
2217 Lex();
2218 }
2219 }
2220
2221 Lex();
2222 return false;
2223}
2224
Daniel Dunbara0d14262009-06-24 23:30:00 +00002225/// ParseDirectiveSpace
2226/// ::= .space expression [ , expression ]
2227bool AsmParser::ParseDirectiveSpace() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002228 CheckForValidSection();
2229
Daniel Dunbara0d14262009-06-24 23:30:00 +00002230 int64_t NumBytes;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002231 if (ParseAbsoluteExpression(NumBytes))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002232 return true;
2233
2234 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002235 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2236 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002237 return TokError("unexpected token in '.space' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002238 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002239
Daniel Dunbar475839e2009-06-29 20:37:27 +00002240 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002241 return true;
2242
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002243 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002244 return TokError("unexpected token in '.space' directive");
2245 }
2246
Sean Callanan79ed1a82010-01-19 20:22:31 +00002247 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002248
2249 if (NumBytes <= 0)
2250 return TokError("invalid number of bytes in '.space' directive");
2251
2252 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002253 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002254
2255 return false;
2256}
2257
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002258/// ParseDirectiveZero
2259/// ::= .zero expression
2260bool AsmParser::ParseDirectiveZero() {
2261 CheckForValidSection();
2262
2263 int64_t NumBytes;
2264 if (ParseAbsoluteExpression(NumBytes))
2265 return true;
2266
Rafael Espindolae452b172010-10-05 19:42:57 +00002267 int64_t Val = 0;
2268 if (getLexer().is(AsmToken::Comma)) {
2269 Lex();
2270 if (ParseAbsoluteExpression(Val))
2271 return true;
2272 }
2273
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002274 if (getLexer().isNot(AsmToken::EndOfStatement))
2275 return TokError("unexpected token in '.zero' directive");
2276
2277 Lex();
2278
Rafael Espindolae452b172010-10-05 19:42:57 +00002279 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002280
2281 return false;
2282}
2283
Daniel Dunbara0d14262009-06-24 23:30:00 +00002284/// ParseDirectiveFill
2285/// ::= .fill expression , expression , expression
2286bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002287 CheckForValidSection();
2288
Daniel Dunbara0d14262009-06-24 23:30:00 +00002289 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002290 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002291 return true;
2292
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002293 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002294 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002295 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002296
Daniel Dunbara0d14262009-06-24 23:30:00 +00002297 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002298 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002299 return true;
2300
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002301 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002302 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002303 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002304
Daniel Dunbara0d14262009-06-24 23:30:00 +00002305 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002306 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002307 return true;
2308
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002309 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002310 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002311
Sean Callanan79ed1a82010-01-19 20:22:31 +00002312 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002313
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002314 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2315 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002316
2317 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002318 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002319
2320 return false;
2321}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002322
2323/// ParseDirectiveOrg
2324/// ::= .org expression [ , expression ]
2325bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002326 CheckForValidSection();
2327
Daniel Dunbar821e3332009-08-31 08:09:28 +00002328 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002329 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002330 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002331 return true;
2332
2333 // Parse optional fill expression.
2334 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002335 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2336 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002337 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002338 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002339
Daniel Dunbar475839e2009-06-29 20:37:27 +00002340 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002341 return true;
2342
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002343 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002344 return TokError("unexpected token in '.org' directive");
2345 }
2346
Sean Callanan79ed1a82010-01-19 20:22:31 +00002347 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002348
Jim Grosbachebd4c052012-01-27 00:37:08 +00002349 // Only limited forms of relocatable expressions are accepted here, it
2350 // has to be relative to the current section. The streamer will return
2351 // 'true' if the expression wasn't evaluatable.
2352 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2353 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002354
2355 return false;
2356}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002357
2358/// ParseDirectiveAlign
2359/// ::= {.align, ...} expression [ , expression [ , expression ]]
2360bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002361 CheckForValidSection();
2362
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002363 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002364 int64_t Alignment;
2365 if (ParseAbsoluteExpression(Alignment))
2366 return true;
2367
2368 SMLoc MaxBytesLoc;
2369 bool HasFillExpr = false;
2370 int64_t FillExpr = 0;
2371 int64_t MaxBytesToFill = 0;
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
2377 // The fill expression can be omitted while specifying a maximum number of
2378 // alignment bytes, e.g:
2379 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002380 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002381 HasFillExpr = true;
2382 if (ParseAbsoluteExpression(FillExpr))
2383 return true;
2384 }
2385
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002386 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2387 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002388 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002389 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002390
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002391 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002392 if (ParseAbsoluteExpression(MaxBytesToFill))
2393 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002394
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002395 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002396 return TokError("unexpected token in directive");
2397 }
2398 }
2399
Sean Callanan79ed1a82010-01-19 20:22:31 +00002400 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002401
Daniel Dunbar648ac512010-05-17 21:54:30 +00002402 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002403 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002404
2405 // Compute alignment in bytes.
2406 if (IsPow2) {
2407 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002408 if (Alignment >= 32) {
2409 Error(AlignmentLoc, "invalid alignment value");
2410 Alignment = 31;
2411 }
2412
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002413 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002414 }
2415
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002416 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002417 if (MaxBytesLoc.isValid()) {
2418 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002419 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2420 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002421 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002422 }
2423
2424 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002425 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2426 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002427 MaxBytesToFill = 0;
2428 }
2429 }
2430
Daniel Dunbar648ac512010-05-17 21:54:30 +00002431 // Check whether we should use optimal code alignment for this .align
2432 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002433 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002434 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2435 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002436 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002437 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002438 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002439 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2440 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002441 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002442
2443 return false;
2444}
2445
Eli Bendersky4766ef42012-12-20 19:05:53 +00002446
2447/// ParseDirectiveBundleAlignMode
2448/// ::= {.bundle_align_mode} expression
2449bool AsmParser::ParseDirectiveBundleAlignMode() {
2450 CheckForValidSection();
2451
2452 // Expect a single argument: an expression that evaluates to a constant
2453 // in the inclusive range 0-30.
2454 SMLoc ExprLoc = getLexer().getLoc();
2455 int64_t AlignSizePow2;
2456 if (ParseAbsoluteExpression(AlignSizePow2))
2457 return true;
2458 else if (getLexer().isNot(AsmToken::EndOfStatement))
2459 return TokError("unexpected token after expression in"
2460 " '.bundle_align_mode' directive");
2461 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
2462 return Error(ExprLoc,
2463 "invalid bundle alignment size (expected between 0 and 30)");
2464
2465 Lex();
2466
2467 // Because of AlignSizePow2's verified range we can safely truncate it to
2468 // unsigned.
2469 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
2470 return false;
2471}
2472
2473/// ParseDirectiveBundleLock
2474/// ::= {.bundle_lock}
2475bool AsmParser::ParseDirectiveBundleLock() {
2476 CheckForValidSection();
2477
2478 if (getLexer().isNot(AsmToken::EndOfStatement))
2479 return TokError("unexpected token in '.bundle_lock' directive");
2480 Lex();
2481
2482 getStreamer().EmitBundleLock();
2483 return false;
2484}
2485
2486/// ParseDirectiveBundleLock
2487/// ::= {.bundle_lock}
2488bool AsmParser::ParseDirectiveBundleUnlock() {
2489 CheckForValidSection();
2490
2491 if (getLexer().isNot(AsmToken::EndOfStatement))
2492 return TokError("unexpected token in '.bundle_unlock' directive");
2493 Lex();
2494
2495 getStreamer().EmitBundleUnlock();
2496 return false;
2497}
2498
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002499/// ParseDirectiveSymbolAttribute
2500/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00002501bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002502 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002503 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002504 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00002505 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002506
2507 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00002508 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002509
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002510 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002511
Jim Grosbach10ec6502011-09-15 17:56:49 +00002512 // Assembler local symbols don't make any sense here. Complain loudly.
2513 if (Sym->isTemporary())
2514 return Error(Loc, "non-local symbol required in directive");
2515
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002516 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002517
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002518 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002519 break;
2520
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002521 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002522 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002523 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002524 }
2525 }
2526
Sean Callanan79ed1a82010-01-19 20:22:31 +00002527 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00002528 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00002529}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002530
2531/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00002532/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
2533bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002534 CheckForValidSection();
2535
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002536 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002537 StringRef Name;
2538 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002539 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002540
Daniel Dunbar76c4d762009-07-31 21:55:09 +00002541 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002542 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002543
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002544 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002545 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002546 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002547
2548 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002549 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002550 if (ParseAbsoluteExpression(Size))
2551 return true;
2552
2553 int64_t Pow2Alignment = 0;
2554 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002555 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00002556 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002557 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002558 if (ParseAbsoluteExpression(Pow2Alignment))
2559 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002560
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002561 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
2562 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00002563 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
2564
Chris Lattner258281d2010-01-19 06:22:22 +00002565 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00002566 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
2567 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00002568 if (!isPowerOf2_64(Pow2Alignment))
2569 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
2570 Pow2Alignment = Log2_64(Pow2Alignment);
2571 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002572 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002573
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002574 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00002575 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002576
Sean Callanan79ed1a82010-01-19 20:22:31 +00002577 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002578
Chris Lattner1fc3d752009-07-09 17:25:12 +00002579 // NOTE: a size of zero for a .comm should create a undefined symbol
2580 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002581 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002582 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
2583 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002584
Eric Christopherc260a3e2010-05-14 01:38:54 +00002585 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002586 // may internally end up wanting an alignment in bytes.
2587 // FIXME: Diagnose overflow.
2588 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00002589 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
2590 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002591
Daniel Dunbar8906ff12009-08-22 07:22:36 +00002592 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002593 return Error(IDLoc, "invalid symbol redefinition");
2594
Chris Lattner1fc3d752009-07-09 17:25:12 +00002595 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002596 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00002597 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00002598 return false;
2599 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002600
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002601 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00002602 return false;
2603}
Chris Lattner9be3fee2009-07-10 22:20:30 +00002604
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002605/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002606/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002607bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002608 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002609 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002610
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002611 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002612 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002613 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002614
Sean Callanan79ed1a82010-01-19 20:22:31 +00002615 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002616
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00002617 if (Str.empty())
2618 Error(Loc, ".abort detected. Assembly stopping.");
2619 else
2620 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00002621 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00002622
2623 return false;
2624}
Kevin Enderby71148242009-07-14 21:35:03 +00002625
Kevin Enderby1f049b22009-07-14 23:21:55 +00002626/// ParseDirectiveInclude
2627/// ::= .include "filename"
2628bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002629 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002630 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002631
Sean Callanan18b83232010-01-19 21:44:56 +00002632 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002633 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002634 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00002635
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002636 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00002637 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002638
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002639 // Strip the quotes.
2640 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002641
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002642 // Attempt to switch the lexer to the included file before consuming the end
2643 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00002644 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00002645 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00002646 return true;
2647 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00002648
2649 return false;
2650}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00002651
Kevin Enderbyc55acca2011-12-14 21:47:48 +00002652/// ParseDirectiveIncbin
2653/// ::= .incbin "filename"
2654bool AsmParser::ParseDirectiveIncbin() {
2655 if (getLexer().isNot(AsmToken::String))
2656 return TokError("expected string in '.incbin' directive");
2657
2658 std::string Filename = getTok().getString();
2659 SMLoc IncbinLoc = getLexer().getLoc();
2660 Lex();
2661
2662 if (getLexer().isNot(AsmToken::EndOfStatement))
2663 return TokError("unexpected token in '.incbin' directive");
2664
2665 // Strip the quotes.
2666 Filename = Filename.substr(1, Filename.size()-2);
2667
2668 // Attempt to process the included file.
2669 if (ProcessIncbinFile(Filename)) {
2670 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
2671 return true;
2672 }
2673
2674 return false;
2675}
2676
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002677/// ParseDirectiveIf
2678/// ::= .if expression
2679bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002680 TheCondStack.push_back(TheCondState);
2681 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00002682 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002683 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00002684 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002685 int64_t ExprValue;
2686 if (ParseAbsoluteExpression(ExprValue))
2687 return true;
2688
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002689 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002690 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002691
Sean Callanan79ed1a82010-01-19 20:22:31 +00002692 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002693
2694 TheCondState.CondMet = ExprValue;
2695 TheCondState.Ignore = !TheCondState.CondMet;
2696 }
2697
2698 return false;
2699}
2700
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002701/// ParseDirectiveIfb
2702/// ::= .ifb string
2703bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
2704 TheCondStack.push_back(TheCondState);
2705 TheCondState.TheCond = AsmCond::IfCond;
2706
Benjamin Kramer29739e72012-05-12 16:52:21 +00002707 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00002708 EatToEndOfStatement();
2709 } else {
2710 StringRef Str = ParseStringToEndOfStatement();
2711
2712 if (getLexer().isNot(AsmToken::EndOfStatement))
2713 return TokError("unexpected token in '.ifb' directive");
2714
2715 Lex();
2716
2717 TheCondState.CondMet = ExpectBlank == Str.empty();
2718 TheCondState.Ignore = !TheCondState.CondMet;
2719 }
2720
2721 return false;
2722}
2723
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002724/// ParseDirectiveIfc
2725/// ::= .ifc string1, string2
2726bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
2727 TheCondStack.push_back(TheCondState);
2728 TheCondState.TheCond = AsmCond::IfCond;
2729
Benjamin Kramer29739e72012-05-12 16:52:21 +00002730 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00002731 EatToEndOfStatement();
2732 } else {
2733 StringRef Str1 = ParseStringToComma();
2734
2735 if (getLexer().isNot(AsmToken::Comma))
2736 return TokError("unexpected token in '.ifc' directive");
2737
2738 Lex();
2739
2740 StringRef Str2 = ParseStringToEndOfStatement();
2741
2742 if (getLexer().isNot(AsmToken::EndOfStatement))
2743 return TokError("unexpected token in '.ifc' directive");
2744
2745 Lex();
2746
2747 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
2748 TheCondState.Ignore = !TheCondState.CondMet;
2749 }
2750
2751 return false;
2752}
2753
2754/// ParseDirectiveIfdef
2755/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00002756bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
2757 StringRef Name;
2758 TheCondStack.push_back(TheCondState);
2759 TheCondState.TheCond = AsmCond::IfCond;
2760
2761 if (TheCondState.Ignore) {
2762 EatToEndOfStatement();
2763 } else {
2764 if (ParseIdentifier(Name))
2765 return TokError("expected identifier after '.ifdef'");
2766
2767 Lex();
2768
2769 MCSymbol *Sym = getContext().LookupSymbol(Name);
2770
2771 if (expect_defined)
2772 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
2773 else
2774 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
2775 TheCondState.Ignore = !TheCondState.CondMet;
2776 }
2777
2778 return false;
2779}
2780
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002781/// ParseDirectiveElseIf
2782/// ::= .elseif expression
2783bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
2784 if (TheCondState.TheCond != AsmCond::IfCond &&
2785 TheCondState.TheCond != AsmCond::ElseIfCond)
2786 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
2787 " an .elseif");
2788 TheCondState.TheCond = AsmCond::ElseIfCond;
2789
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002790 bool LastIgnoreState = false;
2791 if (!TheCondStack.empty())
2792 LastIgnoreState = TheCondStack.back().Ignore;
2793 if (LastIgnoreState || TheCondState.CondMet) {
2794 TheCondState.Ignore = true;
2795 EatToEndOfStatement();
2796 }
2797 else {
2798 int64_t ExprValue;
2799 if (ParseAbsoluteExpression(ExprValue))
2800 return true;
2801
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002802 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002803 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002804
Sean Callanan79ed1a82010-01-19 20:22:31 +00002805 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002806 TheCondState.CondMet = ExprValue;
2807 TheCondState.Ignore = !TheCondState.CondMet;
2808 }
2809
2810 return false;
2811}
2812
2813/// ParseDirectiveElse
2814/// ::= .else
2815bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002816 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002817 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002818
Sean Callanan79ed1a82010-01-19 20:22:31 +00002819 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002820
2821 if (TheCondState.TheCond != AsmCond::IfCond &&
2822 TheCondState.TheCond != AsmCond::ElseIfCond)
2823 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
2824 ".elseif");
2825 TheCondState.TheCond = AsmCond::ElseCond;
2826 bool LastIgnoreState = false;
2827 if (!TheCondStack.empty())
2828 LastIgnoreState = TheCondStack.back().Ignore;
2829 if (LastIgnoreState || TheCondState.CondMet)
2830 TheCondState.Ignore = true;
2831 else
2832 TheCondState.Ignore = false;
2833
2834 return false;
2835}
2836
2837/// ParseDirectiveEndIf
2838/// ::= .endif
2839bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002840 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002841 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002842
Sean Callanan79ed1a82010-01-19 20:22:31 +00002843 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00002844
2845 if ((TheCondState.TheCond == AsmCond::NoCond) ||
2846 TheCondStack.empty())
2847 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
2848 ".else");
2849 if (!TheCondStack.empty()) {
2850 TheCondState = TheCondStack.back();
2851 TheCondStack.pop_back();
2852 }
2853
2854 return false;
2855}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002856
2857/// ParseDirectiveFile
Nick Lewycky44d798d2011-10-17 23:05:28 +00002858/// ::= .file [number] filename
2859/// ::= .file number directory filename
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002860bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002861 // FIXME: I'm not sure what this is.
2862 int64_t FileNumber = -1;
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002863 SMLoc FileNumberLoc = getLexer().getLoc();
Daniel Dunbareceec052010-07-12 17:45:27 +00002864 if (getLexer().is(AsmToken::Integer)) {
Sean Callanan18b83232010-01-19 21:44:56 +00002865 FileNumber = getTok().getIntVal();
Sean Callanan79ed1a82010-01-19 20:22:31 +00002866 Lex();
Daniel Dunbareceec052010-07-12 17:45:27 +00002867
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002868 if (FileNumber < 1)
2869 return TokError("file number less than one");
2870 }
2871
Daniel Dunbareceec052010-07-12 17:45:27 +00002872 if (getLexer().isNot(AsmToken::String))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002873 return TokError("unexpected token in '.file' directive");
Daniel Dunbareceec052010-07-12 17:45:27 +00002874
Nick Lewycky44d798d2011-10-17 23:05:28 +00002875 // Usually the directory and filename together, otherwise just the directory.
2876 StringRef Path = getTok().getString();
2877 Path = Path.substr(1, Path.size()-2);
Sean Callanan79ed1a82010-01-19 20:22:31 +00002878 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002879
Nick Lewycky44d798d2011-10-17 23:05:28 +00002880 StringRef Directory;
2881 StringRef Filename;
2882 if (getLexer().is(AsmToken::String)) {
2883 if (FileNumber == -1)
2884 return TokError("explicit path specified, but no file number");
2885 Filename = getTok().getString();
2886 Filename = Filename.substr(1, Filename.size()-2);
2887 Directory = Path;
2888 Lex();
2889 } else {
2890 Filename = Path;
2891 }
2892
Daniel Dunbareceec052010-07-12 17:45:27 +00002893 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002894 return TokError("unexpected token in '.file' directive");
2895
Chris Lattnerd32e8032010-01-25 19:02:58 +00002896 if (FileNumber == -1)
Daniel Dunbareceec052010-07-12 17:45:27 +00002897 getStreamer().EmitFileDirective(Filename);
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002898 else {
Kevin Enderby8704b782012-01-11 18:04:47 +00002899 if (getContext().getGenDwarfForAssembly() == true)
2900 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2901 "used to generate dwarf debug info for assembly code");
2902
Nick Lewycky44d798d2011-10-17 23:05:28 +00002903 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002904 Error(FileNumberLoc, "file number already allocated");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +00002905 }
Daniel Dunbareceec052010-07-12 17:45:27 +00002906
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002907 return false;
2908}
2909
2910/// ParseDirectiveLine
2911/// ::= .line [number]
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002912bool GenericAsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
Daniel Dunbareceec052010-07-12 17:45:27 +00002913 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2914 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002915 return TokError("unexpected token in '.line' directive");
2916
Sean Callanan18b83232010-01-19 21:44:56 +00002917 int64_t LineNumber = getTok().getIntVal();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002918 (void) LineNumber;
Sean Callanan79ed1a82010-01-19 20:22:31 +00002919 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002920
2921 // FIXME: Do something with the .line.
2922 }
2923
Daniel Dunbareceec052010-07-12 17:45:27 +00002924 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar839348a2010-07-01 20:20:01 +00002925 return TokError("unexpected token in '.line' directive");
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002926
2927 return false;
2928}
2929
2930
2931/// ParseDirectiveLoc
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002932/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002933/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2934/// The first number is a file number, must have been previously assigned with
2935/// a .file directive, the second number is the line number and optionally the
2936/// third number is a column position (zero if not specified). The remaining
2937/// optional items are .loc sub-directives.
Daniel Dunbar81ea00f2010-07-12 17:54:38 +00002938bool GenericAsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002939
Daniel Dunbareceec052010-07-12 17:45:27 +00002940 if (getLexer().isNot(AsmToken::Integer))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002941 return TokError("unexpected token in '.loc' directive");
Sean Callanan18b83232010-01-19 21:44:56 +00002942 int64_t FileNumber = getTok().getIntVal();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002943 if (FileNumber < 1)
2944 return TokError("file number less than one in '.loc' directive");
Kevin Enderby3f55c242010-10-04 20:17:24 +00002945 if (!getContext().isValidDwarfFileNumber(FileNumber))
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002946 return TokError("unassigned file number in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002947 Lex();
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002948
Kevin Enderby6d8f1a92010-08-24 21:14:47 +00002949 int64_t LineNumber = 0;
2950 if (getLexer().is(AsmToken::Integer)) {
2951 LineNumber = getTok().getIntVal();
2952 if (LineNumber < 1)
2953 return TokError("line number less than one in '.loc' directive");
2954 Lex();
2955 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002956
2957 int64_t ColumnPos = 0;
2958 if (getLexer().is(AsmToken::Integer)) {
2959 ColumnPos = getTok().getIntVal();
2960 if (ColumnPos < 0)
2961 return TokError("column position less than zero in '.loc' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002962 Lex();
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002963 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002964
Kevin Enderbyc0957932010-09-30 16:52:03 +00002965 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002966 unsigned Isa = 0;
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00002967 int64_t Discriminator = 0;
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002968 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2969 for (;;) {
2970 if (getLexer().is(AsmToken::EndOfStatement))
2971 break;
2972
2973 StringRef Name;
2974 SMLoc Loc = getTok().getLoc();
2975 if (getParser().ParseIdentifier(Name))
Daniel Dunbard0c14d62009-08-11 04:24:50 +00002976 return TokError("unexpected token in '.loc' directive");
2977
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002978 if (Name == "basic_block")
2979 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2980 else if (Name == "prologue_end")
2981 Flags |= DWARF2_FLAG_PROLOGUE_END;
2982 else if (Name == "epilogue_begin")
2983 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2984 else if (Name == "is_stmt") {
2985 SMLoc Loc = getTok().getLoc();
2986 const MCExpr *Value;
2987 if (getParser().ParseExpression(Value))
2988 return true;
2989 // The expression must be the constant 0 or 1.
2990 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2991 int Value = MCE->getValue();
2992 if (Value == 0)
2993 Flags &= ~DWARF2_FLAG_IS_STMT;
2994 else if (Value == 1)
2995 Flags |= DWARF2_FLAG_IS_STMT;
2996 else
2997 return Error(Loc, "is_stmt value not 0 or 1");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002998 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00002999 else {
3000 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3001 }
3002 }
3003 else if (Name == "isa") {
3004 SMLoc Loc = getTok().getLoc();
3005 const MCExpr *Value;
3006 if (getParser().ParseExpression(Value))
3007 return true;
3008 // The expression must be a constant greater or equal to 0.
3009 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3010 int Value = MCE->getValue();
3011 if (Value < 0)
3012 return Error(Loc, "isa number less than zero");
3013 Isa = Value;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003014 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00003015 else {
3016 return Error(Loc, "isa number not a constant value");
3017 }
3018 }
Rafael Espindolac50a0fd2010-11-13 03:18:27 +00003019 else if (Name == "discriminator") {
3020 if (getParser().ParseAbsoluteExpression(Discriminator))
3021 return true;
3022 }
Kevin Enderbyc1840b32010-08-24 20:32:42 +00003023 else {
3024 return Error(Loc, "unknown sub-directive in '.loc' directive");
3025 }
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003026
Kevin Enderbyc1840b32010-08-24 20:32:42 +00003027 if (getLexer().is(AsmToken::EndOfStatement))
3028 break;
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003029 }
3030 }
3031
Rafael Espindolaaf6b58082010-11-16 21:20:32 +00003032 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
Devang Patel3f3bf932011-04-18 20:26:49 +00003033 Isa, Discriminator, StringRef());
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003034
3035 return false;
3036}
3037
Daniel Dunbar138abae2010-10-16 04:56:42 +00003038/// ParseDirectiveStabs
3039/// ::= .stabs string, number, number, number
3040bool GenericAsmParser::ParseDirectiveStabs(StringRef Directive,
3041 SMLoc DirectiveLoc) {
3042 return TokError("unsupported directive '" + Directive + "'");
3043}
3044
Rafael Espindolaf9efd832011-05-10 01:10:18 +00003045/// ParseDirectiveCFISections
3046/// ::= .cfi_sections section [, section]
3047bool GenericAsmParser::ParseDirectiveCFISections(StringRef,
3048 SMLoc DirectiveLoc) {
3049 StringRef Name;
3050 bool EH = false;
3051 bool Debug = false;
3052
3053 if (getParser().ParseIdentifier(Name))
3054 return TokError("Expected an identifier");
3055
3056 if (Name == ".eh_frame")
3057 EH = true;
3058 else if (Name == ".debug_frame")
3059 Debug = true;
3060
3061 if (getLexer().is(AsmToken::Comma)) {
3062 Lex();
3063
3064 if (getParser().ParseIdentifier(Name))
3065 return TokError("Expected an identifier");
3066
3067 if (Name == ".eh_frame")
3068 EH = true;
3069 else if (Name == ".debug_frame")
3070 Debug = true;
3071 }
3072
3073 getStreamer().EmitCFISections(EH, Debug);
3074
3075 return false;
3076}
3077
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003078/// ParseDirectiveCFIStartProc
3079/// ::= .cfi_startproc
3080bool GenericAsmParser::ParseDirectiveCFIStartProc(StringRef,
3081 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003082 getStreamer().EmitCFIStartProc();
3083 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003084}
3085
3086/// ParseDirectiveCFIEndProc
3087/// ::= .cfi_endproc
3088bool GenericAsmParser::ParseDirectiveCFIEndProc(StringRef, SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003089 getStreamer().EmitCFIEndProc();
3090 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003091}
3092
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003093/// ParseRegisterOrRegisterNumber - parse register name or number.
3094bool GenericAsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
3095 SMLoc DirectiveLoc) {
3096 unsigned RegNo;
3097
Jim Grosbach6f888a82011-06-02 17:14:04 +00003098 if (getLexer().isNot(AsmToken::Integer)) {
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003099 if (getParser().getTargetParser().ParseRegister(RegNo, DirectiveLoc,
3100 DirectiveLoc))
3101 return true;
Evan Cheng0e6a0522011-07-18 20:57:22 +00003102 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003103 } else
3104 return getParser().ParseAbsoluteExpression(Register);
Jim Grosbachde2f5f42011-02-11 19:05:56 +00003105
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003106 return false;
3107}
3108
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003109/// ParseDirectiveCFIDefCfa
3110/// ::= .cfi_def_cfa register, offset
3111bool GenericAsmParser::ParseDirectiveCFIDefCfa(StringRef,
3112 SMLoc DirectiveLoc) {
3113 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003114 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003115 return true;
3116
3117 if (getLexer().isNot(AsmToken::Comma))
3118 return TokError("unexpected token in directive");
3119 Lex();
3120
3121 int64_t Offset = 0;
3122 if (getParser().ParseAbsoluteExpression(Offset))
3123 return true;
3124
Rafael Espindola066c2f42011-04-12 23:59:07 +00003125 getStreamer().EmitCFIDefCfa(Register, Offset);
3126 return false;
Rafael Espindolab40a71f2010-12-29 01:42:56 +00003127}
3128
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003129/// ParseDirectiveCFIDefCfaOffset
3130/// ::= .cfi_def_cfa_offset offset
3131bool GenericAsmParser::ParseDirectiveCFIDefCfaOffset(StringRef,
3132 SMLoc DirectiveLoc) {
3133 int64_t Offset = 0;
3134 if (getParser().ParseAbsoluteExpression(Offset))
3135 return true;
3136
Rafael Espindola066c2f42011-04-12 23:59:07 +00003137 getStreamer().EmitCFIDefCfaOffset(Offset);
3138 return false;
Rafael Espindola53abbe52011-04-11 20:29:16 +00003139}
3140
3141/// ParseDirectiveCFIAdjustCfaOffset
3142/// ::= .cfi_adjust_cfa_offset adjustment
3143bool GenericAsmParser::ParseDirectiveCFIAdjustCfaOffset(StringRef,
3144 SMLoc DirectiveLoc) {
3145 int64_t Adjustment = 0;
3146 if (getParser().ParseAbsoluteExpression(Adjustment))
3147 return true;
3148
Rafael Espindola5d7dcd32011-04-12 18:53:30 +00003149 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3150 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003151}
3152
3153/// ParseDirectiveCFIDefCfaRegister
3154/// ::= .cfi_def_cfa_register register
3155bool GenericAsmParser::ParseDirectiveCFIDefCfaRegister(StringRef,
3156 SMLoc DirectiveLoc) {
3157 int64_t Register = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003158 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003159 return true;
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003160
Rafael Espindola066c2f42011-04-12 23:59:07 +00003161 getStreamer().EmitCFIDefCfaRegister(Register);
3162 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003163}
3164
3165/// ParseDirectiveCFIOffset
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003166/// ::= .cfi_offset register, offset
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003167bool GenericAsmParser::ParseDirectiveCFIOffset(StringRef, SMLoc DirectiveLoc) {
3168 int64_t Register = 0;
3169 int64_t Offset = 0;
Roman Divacky54b0f4f2011-01-27 17:16:37 +00003170
3171 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003172 return true;
3173
3174 if (getLexer().isNot(AsmToken::Comma))
3175 return TokError("unexpected token in directive");
3176 Lex();
3177
3178 if (getParser().ParseAbsoluteExpression(Offset))
3179 return true;
3180
Rafael Espindola066c2f42011-04-12 23:59:07 +00003181 getStreamer().EmitCFIOffset(Register, Offset);
3182 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003183}
3184
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003185/// ParseDirectiveCFIRelOffset
3186/// ::= .cfi_rel_offset register, offset
3187bool GenericAsmParser::ParseDirectiveCFIRelOffset(StringRef,
3188 SMLoc DirectiveLoc) {
3189 int64_t Register = 0;
3190
3191 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3192 return true;
3193
3194 if (getLexer().isNot(AsmToken::Comma))
3195 return TokError("unexpected token in directive");
3196 Lex();
3197
3198 int64_t Offset = 0;
3199 if (getParser().ParseAbsoluteExpression(Offset))
3200 return true;
3201
Rafael Espindola25f492e2011-04-12 16:12:03 +00003202 getStreamer().EmitCFIRelOffset(Register, Offset);
3203 return false;
Rafael Espindolaa61842b2011-04-11 21:49:50 +00003204}
3205
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003206static bool isValidEncoding(int64_t Encoding) {
3207 if (Encoding & ~0xff)
3208 return false;
3209
3210 if (Encoding == dwarf::DW_EH_PE_omit)
3211 return true;
3212
3213 const unsigned Format = Encoding & 0xf;
3214 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3215 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3216 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3217 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3218 return false;
3219
Rafael Espindolacaf11582010-12-29 04:31:26 +00003220 const unsigned Application = Encoding & 0x70;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003221 if (Application != dwarf::DW_EH_PE_absptr &&
Rafael Espindolacaf11582010-12-29 04:31:26 +00003222 Application != dwarf::DW_EH_PE_pcrel)
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003223 return false;
3224
3225 return true;
3226}
3227
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003228/// ParseDirectiveCFIPersonalityOrLsda
3229/// ::= .cfi_personality encoding, [symbol_name]
3230/// ::= .cfi_lsda encoding, [symbol_name]
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003231bool GenericAsmParser::ParseDirectiveCFIPersonalityOrLsda(StringRef IDVal,
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003232 SMLoc DirectiveLoc) {
3233 int64_t Encoding = 0;
3234 if (getParser().ParseAbsoluteExpression(Encoding))
3235 return true;
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003236 if (Encoding == dwarf::DW_EH_PE_omit)
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003237 return false;
3238
Rafael Espindolad7c8cca2010-12-26 20:20:31 +00003239 if (!isValidEncoding(Encoding))
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003240 return TokError("unsupported encoding.");
3241
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003242 if (getLexer().isNot(AsmToken::Comma))
3243 return TokError("unexpected token in directive");
3244 Lex();
3245
3246 StringRef Name;
3247 if (getParser().ParseIdentifier(Name))
3248 return TokError("expected identifier in directive");
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003249
3250 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
3251
3252 if (IDVal == ".cfi_personality")
Rafael Espindola066c2f42011-04-12 23:59:07 +00003253 getStreamer().EmitCFIPersonality(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003254 else {
3255 assert(IDVal == ".cfi_lsda");
Rafael Espindola066c2f42011-04-12 23:59:07 +00003256 getStreamer().EmitCFILsda(Sym, Encoding);
Rafael Espindolacdfecc82010-11-22 14:27:24 +00003257 }
Rafael Espindola066c2f42011-04-12 23:59:07 +00003258 return false;
Rafael Espindola1fdfbc42010-11-16 18:34:07 +00003259}
3260
Rafael Espindolafe024d02010-12-28 18:36:23 +00003261/// ParseDirectiveCFIRememberState
3262/// ::= .cfi_remember_state
3263bool GenericAsmParser::ParseDirectiveCFIRememberState(StringRef IDVal,
3264 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003265 getStreamer().EmitCFIRememberState();
3266 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003267}
3268
3269/// ParseDirectiveCFIRestoreState
3270/// ::= .cfi_remember_state
3271bool GenericAsmParser::ParseDirectiveCFIRestoreState(StringRef IDVal,
3272 SMLoc DirectiveLoc) {
Rafael Espindola066c2f42011-04-12 23:59:07 +00003273 getStreamer().EmitCFIRestoreState();
3274 return false;
Rafael Espindolafe024d02010-12-28 18:36:23 +00003275}
3276
Rafael Espindolac5754392011-04-12 15:31:05 +00003277/// ParseDirectiveCFISameValue
3278/// ::= .cfi_same_value register
3279bool GenericAsmParser::ParseDirectiveCFISameValue(StringRef IDVal,
3280 SMLoc DirectiveLoc) {
3281 int64_t Register = 0;
3282
3283 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3284 return true;
3285
3286 getStreamer().EmitCFISameValue(Register);
3287
3288 return false;
3289}
3290
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003291/// ParseDirectiveCFIRestore
3292/// ::= .cfi_restore register
3293bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003294 SMLoc DirectiveLoc) {
Rafael Espindolaed23bdb2011-12-29 21:43:03 +00003295 int64_t Register = 0;
3296 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3297 return true;
3298
3299 getStreamer().EmitCFIRestore(Register);
3300
3301 return false;
3302}
3303
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003304/// ParseDirectiveCFIEscape
3305/// ::= .cfi_escape expression[,...]
3306bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
Bill Wendling96cb1122012-07-19 00:04:14 +00003307 SMLoc DirectiveLoc) {
Rafael Espindola6f0b1812011-12-29 20:24:47 +00003308 std::string Values;
3309 int64_t CurrValue;
3310 if (getParser().ParseAbsoluteExpression(CurrValue))
3311 return true;
3312
3313 Values.push_back((uint8_t)CurrValue);
3314
3315 while (getLexer().is(AsmToken::Comma)) {
3316 Lex();
3317
3318 if (getParser().ParseAbsoluteExpression(CurrValue))
3319 return true;
3320
3321 Values.push_back((uint8_t)CurrValue);
3322 }
3323
3324 getStreamer().EmitCFIEscape(Values);
3325 return false;
3326}
3327
Rafael Espindola16d7d432012-01-23 21:51:52 +00003328/// ParseDirectiveCFISignalFrame
3329/// ::= .cfi_signal_frame
3330bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
3331 SMLoc DirectiveLoc) {
3332 if (getLexer().isNot(AsmToken::EndOfStatement))
3333 return Error(getLexer().getLoc(),
3334 "unexpected token in '" + Directive + "' directive");
3335
3336 getStreamer().EmitCFISignalFrame();
3337
3338 return false;
3339}
3340
Rafael Espindolac8fec7e2012-11-23 16:59:41 +00003341/// ParseDirectiveCFIUndefined
3342/// ::= .cfi_undefined register
3343bool GenericAsmParser::ParseDirectiveCFIUndefined(StringRef Directive,
3344 SMLoc DirectiveLoc) {
3345 int64_t Register = 0;
3346
3347 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
3348 return true;
3349
3350 getStreamer().EmitCFIUndefined(Register);
3351
3352 return false;
3353}
3354
Rafael Espindolaf4f14f62012-11-25 15:14:49 +00003355/// ParseDirectiveCFIRegister
3356/// ::= .cfi_register register, register
3357bool GenericAsmParser::ParseDirectiveCFIRegister(StringRef Directive,
3358 SMLoc DirectiveLoc) {
3359 int64_t Register1 = 0;
3360
3361 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
3362 return true;
3363
3364 if (getLexer().isNot(AsmToken::Comma))
3365 return TokError("unexpected token in directive");
3366 Lex();
3367
3368 int64_t Register2 = 0;
3369
3370 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3371 return true;
3372
3373 getStreamer().EmitCFIRegister(Register1, Register2);
3374
3375 return false;
3376}
3377
Daniel Dunbar3c802de2010-07-18 18:38:02 +00003378/// ParseDirectiveMacrosOnOff
3379/// ::= .macros_on
3380/// ::= .macros_off
3381bool GenericAsmParser::ParseDirectiveMacrosOnOff(StringRef Directive,
3382 SMLoc DirectiveLoc) {
3383 if (getLexer().isNot(AsmToken::EndOfStatement))
3384 return Error(getLexer().getLoc(),
3385 "unexpected token in '" + Directive + "' directive");
3386
3387 getParser().MacrosEnabled = Directive == ".macros_on";
3388
3389 return false;
3390}
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003391
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003392/// ParseDirectiveMacro
Rafael Espindola65366442011-06-05 02:43:45 +00003393/// ::= .macro name [parameters]
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003394bool GenericAsmParser::ParseDirectiveMacro(StringRef Directive,
3395 SMLoc DirectiveLoc) {
3396 StringRef Name;
3397 if (getParser().ParseIdentifier(Name))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003398 return TokError("expected identifier in '.macro' directive");
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003399
Rafael Espindola8a403d32012-08-08 14:51:03 +00003400 MacroParameters Parameters;
Preston Gurd7b6f2032012-09-19 20:36:12 +00003401 // Argument delimiter is initially unknown. It will be set by
3402 // ParseMacroArgument()
3403 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindola65366442011-06-05 02:43:45 +00003404 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Rafael Espindola7996d042012-08-21 16:06:48 +00003405 for (;;) {
3406 MacroParameter Parameter;
Preston Gurd6c9176a2012-09-19 20:29:04 +00003407 if (getParser().ParseIdentifier(Parameter.first))
Rafael Espindolad7ae0f12012-08-21 17:12:05 +00003408 return TokError("expected identifier in '.macro' directive");
Preston Gurd6c9176a2012-09-19 20:29:04 +00003409
3410 if (getLexer().is(AsmToken::Equal)) {
3411 Lex();
Preston Gurd7b6f2032012-09-19 20:36:12 +00003412 if (getParser().ParseMacroArgument(Parameter.second, ArgumentDelimiter))
Preston Gurd6c9176a2012-09-19 20:29:04 +00003413 return true;
3414 }
3415
Rafael Espindola65366442011-06-05 02:43:45 +00003416 Parameters.push_back(Parameter);
3417
Preston Gurd7b6f2032012-09-19 20:36:12 +00003418 if (getLexer().is(AsmToken::Comma))
3419 Lex();
3420 else if (getLexer().is(AsmToken::EndOfStatement))
Rafael Espindola65366442011-06-05 02:43:45 +00003421 break;
Rafael Espindola65366442011-06-05 02:43:45 +00003422 }
3423 }
3424
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003425 // Eat the end of statement.
3426 Lex();
3427
3428 AsmToken EndToken, StartToken = getTok();
3429
3430 // Lex the macro definition.
3431 for (;;) {
3432 // Check whether we have reached the end of the file.
3433 if (getLexer().is(AsmToken::Eof))
3434 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3435
3436 // Otherwise, check whether we have reach the .endmacro.
3437 if (getLexer().is(AsmToken::Identifier) &&
3438 (getTok().getIdentifier() == ".endm" ||
3439 getTok().getIdentifier() == ".endmacro")) {
3440 EndToken = getTok();
3441 Lex();
3442 if (getLexer().isNot(AsmToken::EndOfStatement))
3443 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3444 "' directive");
3445 break;
3446 }
3447
3448 // Otherwise, scan til the end of the statement.
3449 getParser().EatToEndOfStatement();
3450 }
3451
3452 if (getParser().MacroMap.lookup(Name)) {
3453 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3454 }
3455
3456 const char *BodyStart = StartToken.getLoc().getPointer();
3457 const char *BodyEnd = EndToken.getLoc().getPointer();
3458 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Rafael Espindola65366442011-06-05 02:43:45 +00003459 getParser().MacroMap[Name] = new Macro(Name, Body, Parameters);
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003460 return false;
3461}
3462
3463/// ParseDirectiveEndMacro
3464/// ::= .endm
3465/// ::= .endmacro
3466bool GenericAsmParser::ParseDirectiveEndMacro(StringRef Directive,
Rafael Espindola8a403d32012-08-08 14:51:03 +00003467 SMLoc DirectiveLoc) {
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003468 if (getLexer().isNot(AsmToken::EndOfStatement))
3469 return TokError("unexpected token in '" + Directive + "' directive");
3470
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00003471 // If we are inside a macro instantiation, terminate the current
3472 // instantiation.
3473 if (!getParser().ActiveMacros.empty()) {
3474 getParser().HandleMacroExit();
3475 return false;
3476 }
3477
3478 // Otherwise, this .endmacro is a stray entry in the file; well formed
3479 // .endmacro directives are handled during the macro definition parsing.
Daniel Dunbar6d8cf082010-07-18 18:47:21 +00003480 return TokError("unexpected '" + Directive + "' in file, "
3481 "no current macro definition");
3482}
3483
Benjamin Kramerbc3b27c2012-05-12 11:21:46 +00003484/// ParseDirectivePurgeMacro
3485/// ::= .purgem
3486bool GenericAsmParser::ParseDirectivePurgeMacro(StringRef Directive,
3487 SMLoc DirectiveLoc) {
3488 StringRef Name;
3489 if (getParser().ParseIdentifier(Name))
3490 return TokError("expected identifier in '.purgem' directive");
3491
3492 if (getLexer().isNot(AsmToken::EndOfStatement))
3493 return TokError("unexpected token in '.purgem' directive");
3494
3495 StringMap<Macro*>::iterator I = getParser().MacroMap.find(Name);
3496 if (I == getParser().MacroMap.end())
3497 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3498
3499 // Undefine the macro.
3500 delete I->getValue();
3501 getParser().MacroMap.erase(I);
3502 return false;
3503}
3504
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003505bool GenericAsmParser::ParseDirectiveLEB128(StringRef DirName, SMLoc) {
Rafael Espindola3ff57092010-11-02 17:22:24 +00003506 getParser().CheckForValidSection();
3507
3508 const MCExpr *Value;
3509
3510 if (getParser().ParseExpression(Value))
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003511 return true;
3512
3513 if (getLexer().isNot(AsmToken::EndOfStatement))
3514 return TokError("unexpected token in directive");
3515
3516 if (DirName[1] == 's')
Rafael Espindola3ff57092010-11-02 17:22:24 +00003517 getStreamer().EmitSLEB128Value(Value);
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003518 else
Rafael Espindola3ff57092010-11-02 17:22:24 +00003519 getStreamer().EmitULEB128Value(Value);
3520
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003521 return false;
3522}
3523
Rafael Espindola761cb062012-06-03 23:57:14 +00003524Macro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003525 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003526
Rafael Espindola761cb062012-06-03 23:57:14 +00003527 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003528 for (;;) {
3529 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003530 if (getLexer().is(AsmToken::Eof)) {
3531 Error(DirectiveLoc, "no matching '.endr' in definition");
3532 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003533 }
3534
Rafael Espindola761cb062012-06-03 23:57:14 +00003535 if (Lexer.is(AsmToken::Identifier) &&
3536 (getTok().getIdentifier() == ".rept")) {
3537 ++NestLevel;
3538 }
3539
3540 // Otherwise, check whether we have reached the .endr.
3541 if (Lexer.is(AsmToken::Identifier) &&
3542 getTok().getIdentifier() == ".endr") {
3543 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003544 EndToken = getTok();
3545 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003546 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3547 TokError("unexpected token in '.endr' directive");
3548 return 0;
3549 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003550 break;
3551 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003552 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003553 }
3554
Rafael Espindola761cb062012-06-03 23:57:14 +00003555 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003556 EatToEndOfStatement();
3557 }
3558
3559 const char *BodyStart = StartToken.getLoc().getPointer();
3560 const char *BodyEnd = EndToken.getLoc().getPointer();
3561 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3562
Rafael Espindola761cb062012-06-03 23:57:14 +00003563 // We Are Anonymous.
3564 StringRef Name;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003565 MacroParameters Parameters;
Rafael Espindola761cb062012-06-03 23:57:14 +00003566 return new Macro(Name, Body, Parameters);
3567}
3568
3569void AsmParser::InstantiateMacroLikeBody(Macro *M, SMLoc DirectiveLoc,
3570 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003571 OS << ".endr\n";
3572
3573 MemoryBuffer *Instantiation =
3574 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3575
Rafael Espindola761cb062012-06-03 23:57:14 +00003576 // Create the macro instantiation object and add to the current macro
3577 // instantiation stack.
3578 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003579 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003580 getTok().getLoc(),
3581 Instantiation);
3582 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003583
Rafael Espindola761cb062012-06-03 23:57:14 +00003584 // Jump to the macro instantiation and prime the lexer.
3585 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3586 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3587 Lex();
3588}
3589
3590bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3591 int64_t Count;
3592 if (ParseAbsoluteExpression(Count))
3593 return TokError("unexpected token in '.rept' directive");
3594
3595 if (Count < 0)
3596 return TokError("Count is negative");
3597
3598 if (Lexer.isNot(AsmToken::EndOfStatement))
3599 return TokError("unexpected token in '.rept' directive");
3600
3601 // Eat the end of statement.
3602 Lex();
3603
3604 // Lex the rept definition.
3605 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3606 if (!M)
3607 return true;
3608
3609 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3610 // to hold the macro body with substitutions.
3611 SmallString<256> Buf;
Rafael Espindola8a403d32012-08-08 14:51:03 +00003612 MacroParameters Parameters;
3613 MacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003614 raw_svector_ostream OS(Buf);
3615 while (Count--) {
3616 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3617 return true;
3618 }
3619 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003620
3621 return false;
3622}
3623
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003624/// ParseDirectiveIrp
3625/// ::= .irp symbol,values
3626bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003627 MacroParameters Parameters;
3628 MacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003629
Preston Gurd6c9176a2012-09-19 20:29:04 +00003630 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003631 return TokError("expected identifier in '.irp' directive");
3632
3633 Parameters.push_back(Parameter);
3634
3635 if (Lexer.isNot(AsmToken::Comma))
3636 return TokError("expected comma in '.irp' directive");
3637
3638 Lex();
3639
Rafael Espindola8a403d32012-08-08 14:51:03 +00003640 MacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003641 if (ParseMacroArguments(0, A))
3642 return true;
3643
3644 // Eat the end of statement.
3645 Lex();
3646
3647 // Lex the irp definition.
3648 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3649 if (!M)
3650 return true;
3651
3652 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3653 // to hold the macro body with substitutions.
3654 SmallString<256> Buf;
3655 raw_svector_ostream OS(Buf);
3656
Rafael Espindola7996d042012-08-21 16:06:48 +00003657 for (MacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3658 MacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003659 Args.push_back(*i);
3660
3661 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3662 return true;
3663 }
3664
3665 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3666
3667 return false;
3668}
3669
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003670/// ParseDirectiveIrpc
3671/// ::= .irpc symbol,values
3672bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Rafael Espindola8a403d32012-08-08 14:51:03 +00003673 MacroParameters Parameters;
3674 MacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003675
Preston Gurd6c9176a2012-09-19 20:29:04 +00003676 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003677 return TokError("expected identifier in '.irpc' directive");
3678
3679 Parameters.push_back(Parameter);
3680
3681 if (Lexer.isNot(AsmToken::Comma))
3682 return TokError("expected comma in '.irpc' directive");
3683
3684 Lex();
3685
Rafael Espindola8a403d32012-08-08 14:51:03 +00003686 MacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003687 if (ParseMacroArguments(0, A))
3688 return true;
3689
3690 if (A.size() != 1 || A.front().size() != 1)
3691 return TokError("unexpected token in '.irpc' directive");
3692
3693 // Eat the end of statement.
3694 Lex();
3695
3696 // Lex the irpc definition.
3697 Macro *M = ParseMacroLikeBody(DirectiveLoc);
3698 if (!M)
3699 return true;
3700
3701 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3702 // to hold the macro body with substitutions.
3703 SmallString<256> Buf;
3704 raw_svector_ostream OS(Buf);
3705
3706 StringRef Values = A.front().front().getString();
3707 std::size_t I, End = Values.size();
3708 for (I = 0; I < End; ++I) {
3709 MacroArgument Arg;
3710 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3711
Rafael Espindola8a403d32012-08-08 14:51:03 +00003712 MacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003713 Args.push_back(Arg);
3714
3715 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3716 return true;
3717 }
3718
3719 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3720
3721 return false;
3722}
3723
Rafael Espindola761cb062012-06-03 23:57:14 +00003724bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3725 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003726 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003727
3728 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003729 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003730 assert(getLexer().is(AsmToken::EndOfStatement));
3731
Rafael Espindola761cb062012-06-03 23:57:14 +00003732 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003733 return false;
3734}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003735
Eli Friedman2128aae2012-10-22 23:58:19 +00003736bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3737 const MCExpr *Value;
3738 SMLoc ExprLoc = getLexer().getLoc();
3739 if (ParseExpression(Value))
3740 return true;
3741 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3742 if (!MCE)
3743 return Error(ExprLoc, "unexpected expression in _emit");
3744 uint64_t IntValue = MCE->getValue();
3745 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3746 return Error(ExprLoc, "literal value out of range for directive");
3747
3748 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3749 return false;
3750}
3751
Chad Rosierb1f8c132012-10-18 15:49:34 +00003752bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3753 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003754 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003755 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003756 SmallVectorImpl<std::string> &Clobbers,
3757 const MCInstrInfo *MII,
3758 const MCInstPrinter *IP,
3759 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003760 SmallVector<void *, 4> InputDecls;
3761 SmallVector<void *, 4> OutputDecls;
3762 SmallVector<bool, 4> InputDeclsOffsetOf;
3763 SmallVector<bool, 4> OutputDeclsOffsetOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003764 SmallVector<std::string, 4> InputConstraints;
3765 SmallVector<std::string, 4> OutputConstraints;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003766 std::set<std::string> ClobberRegs;
3767
Chad Rosier4e472d22012-10-20 01:02:45 +00003768 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003769
3770 // Prime the lexer.
3771 Lex();
3772
3773 // While we have input, parse each statement.
3774 unsigned InputIdx = 0;
3775 unsigned OutputIdx = 0;
3776 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00003777 ParseStatementInfo Info(&AsmStrRewrites);
3778 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00003779 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003780
Chad Rosier57498012012-12-12 22:45:52 +00003781 if (Info.ParseError)
3782 return true;
3783
Eli Friedman2128aae2012-10-22 23:58:19 +00003784 if (Info.Opcode != ~0U) {
3785 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003786
3787 // Build the list of clobbers, outputs and inputs.
Eli Friedman2128aae2012-10-22 23:58:19 +00003788 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3789 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003790
3791 // Immediate.
3792 if (Operand->isImm()) {
Chad Rosierefcb3d92012-10-26 18:04:20 +00003793 if (Operand->needAsmRewrite())
3794 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3795 Operand->getStartLoc()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003796 continue;
3797 }
3798
3799 // Register operand.
Chad Rosierc0a14b82012-10-24 17:22:29 +00003800 if (Operand->isReg() && !Operand->isOffsetOf()) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003801 unsigned NumDefs = Desc.getNumDefs();
3802 // Clobber.
3803 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3804 std::string Reg;
3805 raw_string_ostream OS(Reg);
3806 IP->printRegName(OS, Operand->getReg());
3807 ClobberRegs.insert(StringRef(OS.str()));
3808 }
3809 continue;
3810 }
3811
3812 // Expr/Input or Output.
Chad Rosier32989592012-10-18 20:27:15 +00003813 unsigned Size;
3814 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
3815 Size);
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003816 if (OpDecl) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003817 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierc0a14b82012-10-24 17:22:29 +00003818 if (!Operand->isOffsetOf() && Operand->needSizeDirective())
Chad Rosier4e472d22012-10-20 01:02:45 +00003819 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
Chad Rosierefcb3d92012-10-26 18:04:20 +00003820 Operand->getStartLoc(),
3821 /*Len*/0,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003822 Operand->getMemSize()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003823 if (isOutput) {
3824 std::string Constraint = "=";
3825 ++InputIdx;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003826 OutputDecls.push_back(OpDecl);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003827 OutputDeclsOffsetOf.push_back(Operand->isOffsetOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003828 Constraint += Operand->getConstraint().str();
3829 OutputConstraints.push_back(Constraint);
Chad Rosier4e472d22012-10-20 01:02:45 +00003830 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003831 Operand->getStartLoc(),
3832 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003833 } else {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003834 InputDecls.push_back(OpDecl);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003835 InputDeclsOffsetOf.push_back(Operand->isOffsetOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003836 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosier4e472d22012-10-20 01:02:45 +00003837 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003838 Operand->getStartLoc(),
3839 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003840 }
3841 }
3842 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00003843 }
3844 }
3845
3846 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003847 NumOutputs = OutputDecls.size();
3848 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00003849
3850 // Set the unique clobbers.
3851 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3852 E = ClobberRegs.end(); I != E; ++I)
3853 Clobbers.push_back(*I);
3854
3855 // Merge the various outputs and inputs. Output are expected first.
3856 if (NumOutputs || NumInputs) {
3857 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003858 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003859 Constraints.resize(NumExprs);
Chad Rosier5a719fc2012-10-23 17:43:43 +00003860 // FIXME: Constraints are hard coded to 'm', but we need an 'r'
3861 // constraint for offsetof. This needs to be cleaned up!
Chad Rosierb1f8c132012-10-18 15:49:34 +00003862 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003863 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsOffsetOf[i]);
3864 Constraints[i] = OutputDeclsOffsetOf[i] ? "=r" : OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003865 }
3866 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003867 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsOffsetOf[i]);
3868 Constraints[j] = InputDeclsOffsetOf[i] ? "r" : InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003869 }
3870 }
3871
3872 // Build the IR assembly string.
3873 std::string AsmStringIR;
Chad Rosier4e472d22012-10-20 01:02:45 +00003874 AsmRewriteKind PrevKind = AOK_Imm;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003875 raw_string_ostream OS(AsmStringIR);
3876 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
Chad Rosier4e472d22012-10-20 01:02:45 +00003877 for (SmallVectorImpl<struct AsmRewrite>::iterator
Chad Rosierb1f8c132012-10-18 15:49:34 +00003878 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3879 const char *Loc = (*I).Loc.getPointer();
Chad Rosier96d58e62012-10-19 20:57:14 +00003880
Chad Rosier4e472d22012-10-20 01:02:45 +00003881 AsmRewriteKind Kind = (*I).Kind;
Chad Rosier96d58e62012-10-19 20:57:14 +00003882
3883 // Emit everything up to the immediate/expression. If the previous rewrite
3884 // was a size directive, then this has already been done.
3885 if (PrevKind != AOK_SizeDirective)
3886 OS << StringRef(Start, Loc - Start);
3887 PrevKind = Kind;
3888
Chad Rosier5a719fc2012-10-23 17:43:43 +00003889 // Skip the original expression.
3890 if (Kind == AOK_Skip) {
3891 Start = Loc + (*I).Len;
3892 continue;
3893 }
3894
Chad Rosierb1f8c132012-10-18 15:49:34 +00003895 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00003896 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003897 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003898 case AOK_Imm:
Chad Rosierefcb3d92012-10-26 18:04:20 +00003899 OS << Twine("$$");
3900 OS << (*I).Val;
3901 break;
3902 case AOK_ImmPrefix:
3903 OS << Twine("$$");
Chad Rosierb1f8c132012-10-18 15:49:34 +00003904 break;
3905 case AOK_Input:
3906 OS << '$';
3907 OS << InputIdx++;
3908 break;
3909 case AOK_Output:
3910 OS << '$';
3911 OS << OutputIdx++;
3912 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00003913 case AOK_SizeDirective:
Chad Rosier6a020a72012-10-25 20:41:34 +00003914 switch((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00003915 default: break;
3916 case 8: OS << "byte ptr "; break;
3917 case 16: OS << "word ptr "; break;
3918 case 32: OS << "dword ptr "; break;
3919 case 64: OS << "qword ptr "; break;
3920 case 80: OS << "xword ptr "; break;
3921 case 128: OS << "xmmword ptr "; break;
3922 case 256: OS << "ymmword ptr "; break;
3923 }
Eli Friedman2128aae2012-10-22 23:58:19 +00003924 break;
3925 case AOK_Emit:
3926 OS << ".byte";
3927 break;
Chad Rosier6a020a72012-10-25 20:41:34 +00003928 case AOK_DotOperator:
3929 OS << (*I).Val;
3930 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003931 }
Chad Rosier96d58e62012-10-19 20:57:14 +00003932
Chad Rosierb1f8c132012-10-18 15:49:34 +00003933 // Skip the original expression.
Chad Rosier96d58e62012-10-19 20:57:14 +00003934 if (Kind != AOK_SizeDirective)
3935 Start = Loc + (*I).Len;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003936 }
3937
3938 // Emit the remainder of the asm string.
3939 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
3940 if (Start != AsmEnd)
3941 OS << StringRef(Start, AsmEnd - Start);
3942
3943 AsmString = OS.str();
3944 return false;
3945}
3946
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003947/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003948MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003949 MCContext &C, MCStreamer &Out,
3950 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00003951 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00003952}