blob: 6d3240a3e11a6e5f6148d4354b2430a562a90427 [file] [log] [blame]
Chris Lattnerb0133452009-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 Dunbar2af16532010-09-24 01:59:56 +000014#include "llvm/ADT/APFloat.h"
Chad Rosiereb5c1682013-02-13 18:38:58 +000015#include "llvm/ADT/STLExtras.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000016#include "llvm/ADT/SmallString.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000017#include "llvm/ADT/StringMap.h"
Daniel Dunbareb6bb322009-07-27 23:20:52 +000018#include "llvm/ADT/Twine.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000019#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000020#include "llvm/MC/MCContext.h"
Evan Cheng11424442011-07-26 00:24:13 +000021#include "llvm/MC/MCDwarf.h"
Daniel Dunbar115e4d62009-08-31 08:06:59 +000022#include "llvm/MC/MCExpr.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000023#include "llvm/MC/MCInstPrinter.h"
24#include "llvm/MC/MCInstrInfo.h"
Rafael Espindolae28610d2013-12-09 20:26:40 +000025#include "llvm/MC/MCObjectFileInfo.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000026#include "llvm/MC/MCParser/AsmCond.h"
27#include "llvm/MC/MCParser/AsmLexer.h"
28#include "llvm/MC/MCParser/MCAsmParser.h"
Pete Cooper80d21cb2015-06-22 19:35:57 +000029#include "llvm/MC/MCParser/MCAsmParserUtils.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000030#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000031#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Cheng76792992011-07-20 05:58:47 +000032#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000033#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000034#include "llvm/MC/MCStreamer.h"
Daniel Dunbarae7ac012009-06-29 23:43:14 +000035#include "llvm/MC/MCSymbol.h"
Daniel Sanders9f6ad492015-11-12 13:33:00 +000036#include "llvm/MC/MCValue.h"
Davide Italiano7c9fc732016-07-27 05:51:56 +000037#include "llvm/Support/CommandLine.h"
Benjamin Kramer4efe5062012-01-28 15:28:41 +000038#include "llvm/Support/ErrorHandling.h"
Jim Grosbach76346c32011-06-29 16:05:14 +000039#include "llvm/Support/MathExtras.h"
Kevin Enderbye233dda2010-06-28 21:45:58 +000040#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000041#include "llvm/Support/SourceMgr.h"
Chris Lattner36e02122009-06-21 20:54:55 +000042#include "llvm/Support/raw_ostream.h"
Nick Lewycky0de20af2010-12-19 20:43:38 +000043#include <cctype>
Benjamin Kramerd59664f2014-04-29 23:26:49 +000044#include <deque>
Davide Italiano7c9fc732016-07-27 05:51:56 +000045#include <sstream>
Chad Rosier8bce6642012-10-18 15:49:34 +000046#include <string>
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000047#include <vector>
Chris Lattnerb0133452009-06-21 20:16:42 +000048using namespace llvm;
49
Eric Christophera7c32732012-12-18 00:30:54 +000050MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
Nick Lewyckyac612272012-10-19 07:00:09 +000051
Davide Italiano7c9fc732016-07-27 05:51:56 +000052static cl::opt<unsigned> AsmMacroMaxNestingDepth(
53 "asm-macro-max-nesting-depth", cl::init(20), cl::Hidden,
54 cl::desc("The maximum nesting depth allowed for assembly macros."));
55
Daniel Dunbar86033402010-07-12 17:54:38 +000056namespace {
Eli Benderskya313ae62013-01-16 18:56:50 +000057/// \brief Helper types for tracking macro definitions.
58typedef std::vector<AsmToken> MCAsmMacroArgument;
59typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000060
61struct MCAsmMacroParameter {
62 StringRef Name;
63 MCAsmMacroArgument Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000064 bool Required;
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +000065 bool Vararg;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000066
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +000067 MCAsmMacroParameter() : Required(false), Vararg(false) {}
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000068};
69
Eli Benderskya313ae62013-01-16 18:56:50 +000070typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
71
72struct MCAsmMacro {
73 StringRef Name;
74 StringRef Body;
75 MCAsmMacroParameters Parameters;
76
77public:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +000078 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
79 : Name(N), Body(B), Parameters(std::move(P)) {}
Eli Benderskya313ae62013-01-16 18:56:50 +000080};
81
Daniel Dunbar43235712010-07-18 18:54:11 +000082/// \brief Helper class for storing information about an active macro
83/// instantiation.
84struct MacroInstantiation {
Daniel Dunbar43235712010-07-18 18:54:11 +000085 /// The location of the instantiation.
86 SMLoc InstantiationLoc;
87
Daniel Dunbar40f1d852012-12-01 01:38:48 +000088 /// The buffer where parsing should resume upon instantiation completion.
89 int ExitBuffer;
90
Daniel Dunbar43235712010-07-18 18:54:11 +000091 /// The location where parsing should resume upon instantiation completion.
92 SMLoc ExitLoc;
93
Nico Weber155dccd12014-07-24 17:08:39 +000094 /// The depth of TheCondStack at the start of the instantiation.
95 size_t CondStackDepth;
96
Daniel Dunbar43235712010-07-18 18:54:11 +000097public:
Rafael Espindola9eef18c2014-08-27 19:49:03 +000098 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
Daniel Dunbar43235712010-07-18 18:54:11 +000099};
100
Eli Friedman0f4871d2012-10-22 23:58:19 +0000101struct ParseStatementInfo {
Jim Grosbach4b905842013-09-20 23:08:21 +0000102 /// \brief The parsed operands from the last parsed statement.
David Blaikie960ea3f2014-06-08 16:18:35 +0000103 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000104
Jim Grosbach4b905842013-09-20 23:08:21 +0000105 /// \brief The opcode from the last parsed instruction.
Eli Friedman0f4871d2012-10-22 23:58:19 +0000106 unsigned Opcode;
107
Jim Grosbach4b905842013-09-20 23:08:21 +0000108 /// \brief Was there an error parsing the inline assembly?
Chad Rosier149e8e02012-12-12 22:45:52 +0000109 bool ParseError;
110
Eli Friedman0f4871d2012-10-22 23:58:19 +0000111 SmallVectorImpl<AsmRewrite> *AsmRewrites;
112
Craig Topper353eda42014-04-24 06:44:33 +0000113 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000114 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier149e8e02012-12-12 22:45:52 +0000115 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000116};
117
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000118/// \brief The concrete assembly parser instance.
119class AsmParser : public MCAsmParser {
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000120 AsmParser(const AsmParser &) = delete;
121 void operator=(const AsmParser &) = delete;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000122private:
123 AsmLexer Lexer;
124 MCContext &Ctx;
125 MCStreamer &Out;
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000126 const MCAsmInfo &MAI;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000127 SourceMgr &SrcMgr;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000128 SourceMgr::DiagHandlerTy SavedDiagHandler;
129 void *SavedDiagContext;
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000130 std::unique_ptr<MCAsmParserExtension> PlatformParser;
Rafael Espindola82065cb2011-04-11 21:49:50 +0000131
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000132 /// This is the current buffer index we're lexing from as managed by the
133 /// SourceMgr object.
Alp Tokera55b95b2014-07-06 10:33:31 +0000134 unsigned CurBuffer;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000135
136 AsmCond TheCondState;
137 std::vector<AsmCond> TheCondStack;
138
Jim Grosbach4b905842013-09-20 23:08:21 +0000139 /// \brief maps directive names to handler methods in parser
Eli Bendersky17233942013-01-15 22:59:42 +0000140 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000141 /// addDirectiveHandler.
Eli Bendersky17233942013-01-15 22:59:42 +0000142 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000143
Jim Grosbach4b905842013-09-20 23:08:21 +0000144 /// \brief Map of currently defined macros.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000145 StringMap<MCAsmMacro> MacroMap;
Daniel Dunbarc1f58ec2010-07-18 18:47:21 +0000146
Jim Grosbach4b905842013-09-20 23:08:21 +0000147 /// \brief Stack of active macro instantiations.
Daniel Dunbar43235712010-07-18 18:54:11 +0000148 std::vector<MacroInstantiation*> ActiveMacros;
149
Jim Grosbach4b905842013-09-20 23:08:21 +0000150 /// \brief List of bodies of anonymous macros.
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +0000151 std::deque<MCAsmMacro> MacroLikeBodies;
152
Daniel Dunbar828984f2010-07-18 18:38:02 +0000153 /// Boolean tracking whether macro substitution is enabled.
Eli Benderskyc2f6f922013-01-14 18:08:41 +0000154 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000155
Toma Tabacu217116e2015-04-27 10:50:29 +0000156 /// \brief Keeps track of how many .macro's have been instantiated.
157 unsigned NumOfMacroInstantiations;
158
Daniel Dunbar43325c42010-09-09 22:42:56 +0000159 /// Flag tracking whether any errors have been encountered.
160 unsigned HadError : 1;
161
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000162 /// The values from the last parsed cpp hash file line comment if any.
Tim Northoverc0bef992016-04-13 19:46:54 +0000163 struct CppHashInfoTy {
164 StringRef Filename;
Andrew Kaylorca196472016-04-21 20:09:35 +0000165 int64_t LineNumber = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000166 SMLoc Loc;
Andrew Kaylorca196472016-04-21 20:09:35 +0000167 unsigned Buf = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000168 };
169 CppHashInfoTy CppHashInfo;
170
171 /// \brief List of forward directional labels for diagnosis at the end.
172 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
173
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000174 /// When generating dwarf for assembly source files we need to calculate the
175 /// logical line number based on the last parsed cpp hash file line comment
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000176 /// and current line. Since this is slow and messes up the SourceMgr's
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000177 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
178 SMLoc LastQueryIDLoc;
Alp Tokera55b95b2014-07-06 10:33:31 +0000179 unsigned LastQueryBuffer;
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000180 unsigned LastQueryLine;
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000181
Devang Patela173ee52012-01-31 18:14:05 +0000182 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
183 unsigned AssemblerDialect;
184
Jim Grosbach4b905842013-09-20 23:08:21 +0000185 /// \brief is Darwin compatibility enabled?
Preston Gurd05500642012-09-19 20:36:12 +0000186 bool IsDarwin;
187
Jim Grosbach4b905842013-09-20 23:08:21 +0000188 /// \brief Are we parsing ms-style inline assembly?
Chad Rosier49963552012-10-13 00:26:04 +0000189 bool ParsingInlineAsm;
190
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000191public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000192 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000193 const MCAsmInfo &MAI);
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000194 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000195
Craig Topper59be68f2014-03-08 07:14:16 +0000196 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000197
Craig Topper59be68f2014-03-08 07:14:16 +0000198 void addDirectiveHandler(StringRef Directive,
199 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000200 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000201 }
202
Toma Tabacu11e14a92015-04-21 11:50:52 +0000203 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
204 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
205 }
206
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000207public:
208 /// @name MCAsmParser Interface
209 /// {
210
Craig Topper59be68f2014-03-08 07:14:16 +0000211 SourceMgr &getSourceManager() override { return SrcMgr; }
212 MCAsmLexer &getLexer() override { return Lexer; }
213 MCContext &getContext() override { return Ctx; }
214 MCStreamer &getStreamer() override { return Out; }
215 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000216 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000217 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000218 else
219 return AssemblerDialect;
220 }
Craig Topper59be68f2014-03-08 07:14:16 +0000221 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000222 AssemblerDialect = i;
223 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000224
Craig Topper59be68f2014-03-08 07:14:16 +0000225 void Note(SMLoc L, const Twine &Msg,
226 ArrayRef<SMRange> Ranges = None) override;
227 bool Warning(SMLoc L, const Twine &Msg,
228 ArrayRef<SMRange> Ranges = None) override;
229 bool Error(SMLoc L, const Twine &Msg,
230 ArrayRef<SMRange> Ranges = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000231
Craig Topper59be68f2014-03-08 07:14:16 +0000232 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000233
Craig Topper59be68f2014-03-08 07:14:16 +0000234 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
235 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000236
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000237 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000238 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier37e755c2012-10-23 17:43:43 +0000239 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000240 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000241 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000242 const MCInstrInfo *MII, const MCInstPrinter *IP,
243 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000244
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000245 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000246 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
247 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
248 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000249 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
250 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000251 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000252
Jim Grosbach4b905842013-09-20 23:08:21 +0000253 /// \brief Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000254 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000255 bool parseIdentifier(StringRef &Res) override;
256 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000257
Craig Topper59be68f2014-03-08 07:14:16 +0000258 void checkForValidSection() override;
Nirav Davea645433c2016-07-18 15:24:03 +0000259
260 bool getTokenLoc(SMLoc &Loc) {
261 Loc = getTok().getLoc();
262 return false;
263 }
264
Nirav Dave9263ae32016-08-02 19:17:54 +0000265 bool parseEOL(const Twine &ErrMsg) {
266 if (getTok().getKind() == AsmToken::Hash) {
267 StringRef CommentStr = parseStringToEndOfStatement();
268 Lexer.Lex();
269 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
270 }
271 if (getTok().getKind() != AsmToken::EndOfStatement)
272 return TokError(ErrMsg);
273 Lex();
274 return false;
275 }
276
Nirav Davea645433c2016-07-18 15:24:03 +0000277 /// parseToken - If current token has the specified kind, eat it and
278 /// return success. Otherwise, emit the specified error and return failure.
279 bool parseToken(AsmToken::TokenKind T, const Twine &ErrMsg) {
Nirav Dave9263ae32016-08-02 19:17:54 +0000280 if (T == AsmToken::EndOfStatement)
281 return parseEOL(ErrMsg);
Nirav Davea645433c2016-07-18 15:24:03 +0000282 if (getTok().getKind() != T)
283 return TokError(ErrMsg);
284 Lex();
285 return false;
286 }
287
288 bool parseIntToken(int64_t &V, const Twine &ErrMsg) {
289 if (getTok().getKind() != AsmToken::Integer)
290 return TokError(ErrMsg);
291 V = getTok().getIntVal();
292 Lex();
293 return false;
294 }
295
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000296 /// }
297
298private:
Daniel Dunbare5444a82010-09-09 22:42:59 +0000299
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000300 bool parseStatement(ParseStatementInfo &Info,
301 MCAsmParserSemaCallback *SI);
Marina Yatsina5f5de9f2016-03-07 18:11:16 +0000302 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
Craig Topper3c76c522015-09-20 23:35:59 +0000303 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000304
Jim Grosbach4b905842013-09-20 23:08:21 +0000305 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000306 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000307 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000308 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000309 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000310 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000311
Eli Benderskya313ae62013-01-16 18:56:50 +0000312 /// \brief Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000313 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000314
315 /// \brief Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000316 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000317
318 /// \brief Lookup a previously defined macro.
319 /// \param Name Macro name.
320 /// \returns Pointer to macro. NULL if no such macro was defined.
Jim Grosbach4b905842013-09-20 23:08:21 +0000321 const MCAsmMacro* lookupMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000322
323 /// \brief Define a new macro with the given name and information.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000324 void defineMacro(StringRef Name, MCAsmMacro Macro);
Eli Benderskya313ae62013-01-16 18:56:50 +0000325
326 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
Jim Grosbach4b905842013-09-20 23:08:21 +0000327 void undefineMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000328
329 /// \brief Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000330 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000331
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000332 /// \brief Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000333 ///
334 /// \param M The macro.
335 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000336 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000337
338 /// \brief Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000339 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000340
David Majnemer91fc4c22014-01-29 18:57:46 +0000341 /// \brief Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000342 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000343
344 /// \brief Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000345 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000346
Jim Grosbach4b905842013-09-20 23:08:21 +0000347 void printMacroInstantiations();
348 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Dmitri Gribenko3238fb72013-05-05 00:40:33 +0000349 ArrayRef<SMRange> Ranges = None) const {
Chris Lattner72845262011-10-16 05:47:55 +0000350 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000351 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000352 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000353
Nirav Davea645433c2016-07-18 15:24:03 +0000354 bool check(bool P, SMLoc Loc, const Twine &Msg) {
355 if (P)
356 return Error(Loc, Msg);
357 return false;
358 }
359
360 bool check(bool P, const Twine &Msg) {
361 if (P)
362 return TokError(Msg);
363 return false;
364 }
365
Jim Grosbach4b905842013-09-20 23:08:21 +0000366 /// \brief Enter the specified file. This returns true on failure.
367 bool enterIncludeFile(const std::string &Filename);
368
369 /// \brief Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000370 /// This returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000371 bool processIncbinFile(const std::string &Filename);
Daniel Dunbar43235712010-07-18 18:54:11 +0000372
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000373 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000374 /// current token is not set; clients should ensure Lex() is called
375 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000376 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000377 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000378 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000379 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000380
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000381 /// \brief Parse up to the end of statement and a return the contents from the
382 /// current token until the end of the statement; the current token on exit
383 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000384 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000385
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000386 /// \brief Parse until the end of a statement or a comma is encountered,
387 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000388 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000389
Jim Grosbach4b905842013-09-20 23:08:21 +0000390 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +0000391 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000392
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000393 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
394 MCBinaryExpr::Opcode &Kind);
395
Jim Grosbach4b905842013-09-20 23:08:21 +0000396 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
397 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
398 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000399
Jim Grosbach4b905842013-09-20 23:08:21 +0000400 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000401
Eli Bendersky17233942013-01-15 22:59:42 +0000402 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000403 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000404 DK_NO_DIRECTIVE, // Placeholder
405 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000406 DK_RELOC,
David Woodhoused6de0d92014-02-01 16:20:59 +0000407 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
408 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky96522722013-01-11 22:55:28 +0000409 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000410 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
Kevin Enderby3aeada22013-08-28 17:50:59 +0000411 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
Lang Hamesf9033bb2016-04-11 18:33:45 +0000412 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER,
Lang Hames1b640e02016-03-15 01:43:05 +0000413 DK_PRIVATE_EXTERN, DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000414 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
415 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000416 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
Sid Manning51c35602015-03-18 14:20:54 +0000417 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
418 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
Eli Bendersky17233942013-01-15 22:59:42 +0000419 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000420 DK_CV_FILE, DK_CV_LOC, DK_CV_LINETABLE, DK_CV_INLINE_LINETABLE,
David Majnemer408b5e62016-02-05 01:55:49 +0000421 DK_CV_DEF_RANGE, DK_CV_STRINGTABLE, DK_CV_FILECHECKSUMS,
Eli Bendersky17233942013-01-15 22:59:42 +0000422 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
423 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
424 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
425 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
426 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000427 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
Nico Weber155dccd12014-07-24 17:08:39 +0000428 DK_MACROS_ON, DK_MACROS_OFF,
429 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000430 DK_SLEB128, DK_ULEB128,
Nico Weber404012b2014-07-24 16:26:06 +0000431 DK_ERR, DK_ERROR, DK_WARNING,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000432 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000433 };
434
Jim Grosbach4b905842013-09-20 23:08:21 +0000435 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000436 /// directives parsed by this class.
437 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000438
439 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000440 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000441 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Jim Grosbach4b905842013-09-20 23:08:21 +0000442 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
David Woodhoused6de0d92014-02-01 16:20:59 +0000443 bool parseDirectiveOctaValue(); // ".octa"
Jim Grosbach4b905842013-09-20 23:08:21 +0000444 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
445 bool parseDirectiveFill(); // ".fill"
446 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000447 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000448 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
449 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000450 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000451 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000452
Eli Bendersky17233942013-01-15 22:59:42 +0000453 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000454 bool parseDirectiveFile(SMLoc DirectiveLoc);
455 bool parseDirectiveLine();
456 bool parseDirectiveLoc();
457 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000458
David Majnemer408b5e62016-02-05 01:55:49 +0000459 // ".cv_file", ".cv_loc", ".cv_linetable", "cv_inline_linetable",
460 // ".cv_def_range"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000461 bool parseDirectiveCVFile();
462 bool parseDirectiveCVLoc();
463 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000464 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000465 bool parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000466 bool parseDirectiveCVStringTable();
467 bool parseDirectiveCVFileChecksums();
468
Eli Bendersky17233942013-01-15 22:59:42 +0000469 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000470 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000471 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000472 bool parseDirectiveCFISections();
473 bool parseDirectiveCFIStartProc();
474 bool parseDirectiveCFIEndProc();
475 bool parseDirectiveCFIDefCfaOffset();
476 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
477 bool parseDirectiveCFIAdjustCfaOffset();
478 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
479 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
480 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
481 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
482 bool parseDirectiveCFIRememberState();
483 bool parseDirectiveCFIRestoreState();
484 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
485 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
486 bool parseDirectiveCFIEscape();
487 bool parseDirectiveCFISignalFrame();
488 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000489
490 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000491 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000492 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000493 bool parseDirectiveEndMacro(StringRef Directive);
494 bool parseDirectiveMacro(SMLoc DirectiveLoc);
495 bool parseDirectiveMacrosOnOff(StringRef Directive);
Eli Bendersky17233942013-01-15 22:59:42 +0000496
Eli Benderskyf483ff92012-12-20 19:05:53 +0000497 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000498 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000499 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000500 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000501 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000502 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000503
Eli Bendersky17233942013-01-15 22:59:42 +0000504 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000505 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000506
507 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000508 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000509
Jim Grosbach4b905842013-09-20 23:08:21 +0000510 /// \brief Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000511 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000512 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000513
Jim Grosbach4b905842013-09-20 23:08:21 +0000514 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000515
Jim Grosbach4b905842013-09-20 23:08:21 +0000516 bool parseDirectiveAbort(); // ".abort"
517 bool parseDirectiveInclude(); // ".include"
518 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000519
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000520 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
521 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000522 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000523 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000524 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000525 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000526 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
527 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000528 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000529 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
530 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
531 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
532 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000533 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000534
Jim Grosbach4b905842013-09-20 23:08:21 +0000535 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000536 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000537
Rafael Espindola34b9c512012-06-03 23:57:14 +0000538 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000539 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
540 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000541 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000542 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000543 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
544 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
545 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000546
Chad Rosierc7f552c2013-02-12 21:33:51 +0000547 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000548 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000549 size_t Len);
550
551 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000552 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000553
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000554 // "end"
555 bool parseDirectiveEnd(SMLoc DirectiveLoc);
556
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000557 // ".err" or ".error"
558 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000559
Nico Weber404012b2014-07-24 16:26:06 +0000560 // ".warning"
561 bool parseDirectiveWarning(SMLoc DirectiveLoc);
562
Eli Bendersky17233942013-01-15 22:59:42 +0000563 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000564};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000565}
Daniel Dunbar86033402010-07-12 17:54:38 +0000566
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000567namespace llvm {
568
569extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000570extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000571extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000572
573}
574
Chris Lattnerc35681b2010-01-19 19:46:13 +0000575enum { DEFAULT_ADDRSPACE = 0 };
576
David Blaikie9f380a32015-03-16 18:06:57 +0000577AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
578 const MCAsmInfo &MAI)
579 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
580 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
Tim Northoverc0bef992016-04-13 19:46:54 +0000581 MacrosEnabledFlag(true), HadError(false), CppHashInfo(),
Oliver Stannardcf6bfb12014-11-03 12:19:03 +0000582 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000583 // Save the old handler.
584 SavedDiagHandler = SrcMgr.getDiagHandler();
585 SavedDiagContext = SrcMgr.getDiagContext();
586 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000587 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000588 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000589
Daniel Dunbarc5011082010-07-12 18:12:02 +0000590 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000591 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
592 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000593 PlatformParser.reset(createCOFFAsmParser());
594 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000595 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000596 PlatformParser.reset(createDarwinAsmParser());
597 IsDarwin = true;
598 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000599 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000600 PlatformParser.reset(createELFAsmParser());
601 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000602 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000603
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000604 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000605 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000606
607 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000608}
609
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000610AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000611 assert((HadError || ActiveMacros.empty()) &&
612 "Unexpected active macro instantiation!");
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000613}
614
Jim Grosbach4b905842013-09-20 23:08:21 +0000615void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000616 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000617 for (std::vector<MacroInstantiation *>::const_reverse_iterator
618 it = ActiveMacros.rbegin(),
619 ie = ActiveMacros.rend();
620 it != ie; ++it)
621 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000622 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000623}
624
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000625void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
626 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
627 printMacroInstantiations();
628}
629
Chris Lattnera3a06812011-10-16 04:47:35 +0000630bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000631 if(getTargetParser().getTargetOptions().MCNoWarn)
632 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000633 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Chris Lattnera3a06812011-10-16 04:47:35 +0000634 return Error(L, Msg, Ranges);
Jim Grosbach4b905842013-09-20 23:08:21 +0000635 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
636 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000637 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000638}
639
Chris Lattnera3a06812011-10-16 04:47:35 +0000640bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000641 HadError = true;
Jim Grosbach4b905842013-09-20 23:08:21 +0000642 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
643 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000644 return true;
645}
646
Jim Grosbach4b905842013-09-20 23:08:21 +0000647bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000648 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000649 unsigned NewBuf =
650 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
651 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000652 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000653
Sean Callanan7a77eae2010-01-21 00:19:58 +0000654 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000655 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000656 return false;
657}
Daniel Dunbar43235712010-07-18 18:54:11 +0000658
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000659/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000660/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000661/// returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000662bool AsmParser::processIncbinFile(const std::string &Filename) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000663 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000664 unsigned NewBuf =
665 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
666 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000667 return true;
668
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000669 // Pick up the bytes from the file and emit them.
Rafael Espindola64e1af82013-07-02 15:49:13 +0000670 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
Kevin Enderby109f25c2011-12-14 21:47:48 +0000671 return false;
672}
673
Alp Tokera55b95b2014-07-06 10:33:31 +0000674void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
675 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000676 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
677 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000678}
679
Sean Callanan7a77eae2010-01-21 00:19:58 +0000680const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000681 if (Lexer.getTok().is(AsmToken::Error))
682 Error(Lexer.getErrLoc(), Lexer.getErr());
683
Nirav Dave53a72f42016-07-11 12:42:14 +0000684 // if it's a end of statement with a comment in it
685 if (getTok().is(AsmToken::EndOfStatement)) {
686 // if this is a line comment output it.
687 if (getTok().getString().front() != '\n' &&
688 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
689 Out.addExplicitComment(Twine(getTok().getString()));
690 }
691
Sean Callanan7a77eae2010-01-21 00:19:58 +0000692 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000693
694 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000695 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000696 if (MAI.preserveAsmComments())
697 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000698 tok = &Lexer.Lex();
699 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000700
Sean Callanan7a77eae2010-01-21 00:19:58 +0000701 if (tok->is(AsmToken::Eof)) {
702 // If this is the end of an included file, pop the parent file off the
703 // include stack.
704 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
705 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000706 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000707 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000708 }
709 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000710
Michael J. Spencer530ce852010-10-09 11:00:50 +0000711
Sean Callanan7a77eae2010-01-21 00:19:58 +0000712 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000713}
714
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000715bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000716 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000717 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000718 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000719
Chris Lattner36e02122009-06-21 20:54:55 +0000720 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000721 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000722
723 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000724 AsmCond StartingCondState = TheCondState;
725
Kevin Enderby6469fc22011-11-01 22:27:22 +0000726 // If we are generating dwarf for assembly source files save the initial text
727 // section and generate a .file directive.
728 if (getContext().getGenDwarfForAssembly()) {
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000729 MCSection *Sec = getStreamer().getCurrentSection().first;
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000730 if (!Sec->getBeginSymbol()) {
731 MCSymbol *SectionStartSym = getContext().createTempSymbol();
732 getStreamer().EmitLabel(SectionStartSym);
733 Sec->setBeginSymbol(SectionStartSym);
734 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000735 bool InsertResult = getContext().addGenDwarfSection(Sec);
736 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000737 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000738 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
739 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000740 }
741
Chris Lattner73f36112009-07-02 21:53:43 +0000742 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000743 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman0f4871d2012-10-22 23:58:19 +0000744 ParseStatementInfo Info;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000745 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000746 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000747
Nirav Dave1180e6892016-06-02 17:15:05 +0000748 // If we've failed, but on a Error Token, but did not consume it in
749 // favor of a better message, emit it now.
750 if (Lexer.getTok().is(AsmToken::Error)) {
751 Lex();
752 }
753
Daniel Dunbar43325c42010-09-09 22:42:56 +0000754 // We had an error, validate that one was emitted and recover by skipping to
755 // the next line.
756 assert(HadError && "Parse statement returned an error, but none emitted!");
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000757 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000758 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000759
Oliver Stannard21718282016-07-26 14:19:47 +0000760 getTargetParser().flushPendingInstructions(getStreamer());
761
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000762 if (TheCondState.TheCond != StartingCondState.TheCond ||
763 TheCondState.Ignore != StartingCondState.Ignore)
764 return TokError("unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000765
766 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000767 const auto &LineTables = getContext().getMCDwarfLineTables();
768 if (!LineTables.empty()) {
769 unsigned Index = 0;
770 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
771 if (File.Name.empty() && Index != 0)
772 TokError("unassigned file number: " + Twine(Index) +
773 " for .file directives");
774 ++Index;
775 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000776 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000777
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000778 // Check to see that all assembler local symbols were actually defined.
779 // Targets that don't do subsections via symbols may not want this, though,
780 // so conservatively exclude them. Only do this if we're finalizing, though,
781 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000782 if (!NoFinalize) {
783 if (MAI.hasSubsectionsViaSymbols()) {
784 for (const auto &TableEntry : getContext().getSymbols()) {
785 MCSymbol *Sym = TableEntry.getValue();
786 // Variable symbols may not be marked as defined, so check those
787 // explicitly. If we know it's a variable, we have a definition for
788 // the purposes of this check.
789 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
790 // FIXME: We would really like to refer back to where the symbol was
791 // first referenced for a source location. We need to add something
792 // to track that. Currently, we just point to the end of the file.
793 HadError |=
Nirav Davefd910412016-06-17 16:06:17 +0000794 Error(getTok().getLoc(), "assembler local symbol '" +
795 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000796 }
797 }
798
799 // Temporary symbols like the ones for directional jumps don't go in the
800 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000801 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
802 if (std::get<2>(LocSym)->isUndefined()) {
803 // Reset the state of any "# line file" directives we've seen to the
804 // context as it was at the diagnostic site.
805 CppHashInfo = std::get<1>(LocSym);
806 HadError |= Error(std::get<0>(LocSym), "directional label undefined");
807 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000808 }
809 }
810
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000811 // Finalize the output stream if there are no errors and if the client wants
812 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000813 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000814 Out.Finish();
815
Oliver Stannard07b43d32015-11-17 09:58:07 +0000816 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000817}
818
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000819void AsmParser::checkForValidSection() {
Peter Collingbourne2f495b92013-04-17 21:18:16 +0000820 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
Daniel Dunbare5444a82010-09-09 22:42:59 +0000821 TokError("expected section directive before assembly directive");
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000822 Out.InitSections(false);
Daniel Dunbare5444a82010-09-09 22:42:59 +0000823 }
824}
825
Jim Grosbach4b905842013-09-20 23:08:21 +0000826/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000827void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000828 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000829 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000830
Chris Lattnere5074c42009-06-22 01:29:09 +0000831 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000832 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000833 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000834}
835
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000836StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000837 const char *Start = getTok().getLoc().getPointer();
838
Jim Grosbach4b905842013-09-20 23:08:21 +0000839 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000840 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000841
842 const char *End = getTok().getLoc().getPointer();
843 return StringRef(Start, End - Start);
844}
Chris Lattner78db3622009-06-22 05:51:26 +0000845
Jim Grosbach4b905842013-09-20 23:08:21 +0000846StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000847 const char *Start = getTok().getLoc().getPointer();
848
849 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000850 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000851 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000852
853 const char *End = getTok().getLoc().getPointer();
854 return StringRef(Start, End - Start);
855}
856
Jim Grosbach4b905842013-09-20 23:08:21 +0000857/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000858/// NOTE: This assumes the leading '(' has already been consumed.
859///
860/// parenexpr ::= expr)
861///
Jim Grosbach4b905842013-09-20 23:08:21 +0000862bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
863 if (parseExpression(Res))
864 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000865 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +0000866 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000867 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000868 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +0000869 return false;
870}
Chris Lattner78db3622009-06-22 05:51:26 +0000871
Jim Grosbach4b905842013-09-20 23:08:21 +0000872/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000873/// NOTE: This assumes the leading '[' has already been consumed.
874///
875/// bracketexpr ::= expr]
876///
Jim Grosbach4b905842013-09-20 23:08:21 +0000877bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
878 if (parseExpression(Res))
879 return true;
Nirav Davea645433c2016-07-18 15:24:03 +0000880 EndLoc = getTok().getEndLoc();
881 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
882 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000883 return false;
884}
885
Jim Grosbach4b905842013-09-20 23:08:21 +0000886/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000887/// primaryexpr ::= (parenexpr
888/// primaryexpr ::= symbol
889/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +0000890/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +0000891/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +0000892bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000893 SMLoc FirstTokenLoc = getLexer().getLoc();
894 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
895 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +0000896 default:
897 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +0000898 // If we have an error assume that we've already handled it.
899 case AsmToken::Error:
900 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000901 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000902 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000903 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000904 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000905 Res = MCUnaryExpr::createLNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000906 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +0000907 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +0000908 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +0000909 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +0000910 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +0000911 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000912 if (parseIdentifier(Identifier)) {
David Majnemer0c58bc62013-09-25 10:47:21 +0000913 if (FirstTokenKind == AsmToken::Dollar) {
914 if (Lexer.getMAI().getDollarIsPC()) {
915 // This is a '$' reference, which references the current PC. Emit a
916 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000917 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +0000918 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000919 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +0000920 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +0000921 EndLoc = FirstTokenLoc;
922 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +0000923 }
924 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +0000925 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000926 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000927 // Parse symbol variant
928 std::pair<StringRef, StringRef> Split;
929 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +0000930 if (FirstTokenKind == AsmToken::String) {
931 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +0000932 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +0000933 SMLoc AtLoc = getLexer().getLoc();
934 StringRef VName;
935 if (parseIdentifier(VName))
936 return Error(AtLoc, "expected symbol variant after '@'");
937
938 Split = std::make_pair(Identifier, VName);
939 }
940 } else {
941 Split = Identifier.split('@');
942 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000943 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +0000944 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +0000945 StringRef VName;
946 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +0000947 // eat ')'.
948 if (parseToken(AsmToken::RParen,
949 "unexpected token in variant, expected ')'"))
950 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +0000951 Split = std::make_pair(Identifier, VName);
952 }
Daniel Dunbar24764322010-08-24 19:13:42 +0000953
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000954 EndLoc = SMLoc::getFromPointer(Identifier.end());
955
Daniel Dunbard20cda02009-10-16 01:34:54 +0000956 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +0000957 StringRef SymbolName = Identifier;
958 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +0000959
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000960 // Lookup the symbol variant if used.
David Peixotto8ad70b32013-12-04 22:43:20 +0000961 if (Split.second.size()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000962 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +0000963 if (Variant != MCSymbolRefExpr::VK_Invalid) {
964 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +0000965 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +0000966 Variant = MCSymbolRefExpr::VK_None;
967 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +0000968 return Error(SMLoc::getFromPointer(Split.second.begin()),
969 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000970 }
971 }
Daniel Dunbar55992562010-03-15 23:51:06 +0000972
Jim Grosbach6f482002015-05-18 18:43:14 +0000973 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +0000974
Daniel Dunbard20cda02009-10-16 01:34:54 +0000975 // If this is an absolute variable reference, substitute it now to preserve
976 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +0000977 if (Sym->isVariable() &&
978 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +0000979 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +0000980 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +0000981
Vedant Kumar86dbd922015-08-31 17:44:53 +0000982 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +0000983 return false;
984 }
985
986 // Otherwise create a symbol ref.
Jim Grosbach13760bd2015-05-30 01:25:56 +0000987 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Chris Lattner78db3622009-06-22 05:51:26 +0000988 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +0000989 }
David Woodhousef42a6662014-02-01 16:20:54 +0000990 case AsmToken::BigNum:
991 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +0000992 case AsmToken::Integer: {
993 SMLoc Loc = getTok().getLoc();
994 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +0000995 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000996 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000997 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +0000998 // Look for 'b' or 'f' following an Integer as a directional label
999 if (Lexer.getKind() == AsmToken::Identifier) {
1000 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001001 // Lookup the symbol variant if used.
1002 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1003 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1004 if (Split.first.size() != IDVal.size()) {
1005 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001006 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001007 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001008 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001009 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001010 if (IDVal == "f" || IDVal == "b") {
1011 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001012 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001013 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001014 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001015 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001016 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001017 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001018 Lex(); // Eat identifier.
1019 }
1020 }
Chris Lattner78db3622009-06-22 05:51:26 +00001021 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001022 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001023 case AsmToken::Real: {
1024 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001025 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001026 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001027 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001028 Lex(); // Eat token.
1029 return false;
1030 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001031 case AsmToken::Dot: {
1032 // This is a '.' reference, which references the current PC. Emit a
1033 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001034 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001035 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001036 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001037 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001038 Lex(); // Eat identifier.
1039 return false;
1040 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001041 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001042 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001043 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001044 case AsmToken::LBrac:
1045 if (!PlatformParser->HasBracketExpressions())
1046 return TokError("brackets expression not supported on this target");
1047 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001048 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001049 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001050 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001051 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001052 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001053 Res = MCUnaryExpr::createMinus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001054 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001055 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001056 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001057 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001058 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001059 Res = MCUnaryExpr::createPlus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001060 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001061 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001062 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001063 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001064 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001065 Res = MCUnaryExpr::createNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001066 return false;
Chris Lattner78db3622009-06-22 05:51:26 +00001067 }
1068}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001069
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001070bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001071 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001072 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001073}
1074
Daniel Dunbar55f16672010-09-17 02:47:07 +00001075const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001076AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001077 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001078 // Ask the target implementation about this expression first.
1079 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1080 if (NewE)
1081 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001082 // Recurse over the given expression, rebuilding it to apply the given variant
1083 // if there is exactly one symbol.
1084 switch (E->getKind()) {
1085 case MCExpr::Target:
1086 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001087 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001088
1089 case MCExpr::SymbolRef: {
1090 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1091
1092 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001093 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1094 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001095 return E;
1096 }
1097
Jim Grosbach13760bd2015-05-30 01:25:56 +00001098 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001099 }
1100
1101 case MCExpr::Unary: {
1102 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001103 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001104 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001105 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001106 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001107 }
1108
1109 case MCExpr::Binary: {
1110 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001111 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1112 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001113
1114 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001115 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001116
Jim Grosbach4b905842013-09-20 23:08:21 +00001117 if (!LHS)
1118 LHS = BE->getLHS();
1119 if (!RHS)
1120 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001121
Jim Grosbach13760bd2015-05-30 01:25:56 +00001122 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001123 }
1124 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001125
Craig Toppera2886c22012-02-07 05:05:23 +00001126 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001127}
1128
Jim Grosbach4b905842013-09-20 23:08:21 +00001129/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001130///
Jim Grosbachbd164242011-08-20 16:24:13 +00001131/// expr ::= expr &&,|| expr -> lowest.
1132/// expr ::= expr |,^,&,! expr
1133/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1134/// expr ::= expr <<,>> expr
1135/// expr ::= expr +,- expr
1136/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001137/// expr ::= primaryexpr
1138///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001139bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001140 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001141 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001142 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001143 return true;
1144
Daniel Dunbar55f16672010-09-17 02:47:07 +00001145 // As a special case, we support 'a op b @ modifier' by rewriting the
1146 // expression to include the modifier. This is inefficient, but in general we
1147 // expect users to use 'a@modifier op b'.
1148 if (Lexer.getKind() == AsmToken::At) {
1149 Lex();
1150
1151 if (Lexer.isNot(AsmToken::Identifier))
1152 return TokError("unexpected symbol modifier following '@'");
1153
1154 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001155 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001156 if (Variant == MCSymbolRefExpr::VK_Invalid)
1157 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1158
Jim Grosbach4b905842013-09-20 23:08:21 +00001159 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001160 if (!ModifiedRes) {
1161 return TokError("invalid modifier '" + getTok().getIdentifier() +
1162 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001163 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001164
Daniel Dunbar55f16672010-09-17 02:47:07 +00001165 Res = ModifiedRes;
1166 Lex();
1167 }
1168
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001169 // Try to constant fold it up front, if possible.
1170 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001171 if (Res->evaluateAsAbsolute(Value))
1172 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001173
1174 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001175}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001176
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001177bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001178 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001179 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001180}
1181
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001182bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1183 SMLoc &EndLoc) {
1184 if (parseParenExpr(Res, EndLoc))
1185 return true;
1186
1187 for (; ParenDepth > 0; --ParenDepth) {
1188 if (parseBinOpRHS(1, Res, EndLoc))
1189 return true;
1190
1191 // We don't Lex() the last RParen.
1192 // This is the same behavior as parseParenExpression().
1193 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001194 EndLoc = getTok().getEndLoc();
1195 if (parseToken(AsmToken::RParen,
1196 "expected ')' in parentheses expression"))
1197 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001198 }
1199 }
1200 return false;
1201}
1202
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001203bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001204 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001205
Daniel Dunbar75630b32009-06-30 02:10:03 +00001206 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001207 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001208 return true;
1209
Jim Grosbach13760bd2015-05-30 01:25:56 +00001210 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001211 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001212
1213 return false;
1214}
1215
David Majnemer0993e0b2015-10-26 03:15:34 +00001216static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1217 MCBinaryExpr::Opcode &Kind,
1218 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001219 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001220 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001221 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001222
Jim Grosbach4b905842013-09-20 23:08:21 +00001223 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001224 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001225 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001226 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001227 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001228 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001229 return 1;
1230
Jim Grosbach4b905842013-09-20 23:08:21 +00001231 // Low Precedence: |, &, ^
1232 //
1233 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001234 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001235 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001236 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001237 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001238 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001239 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001240 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001241 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001242 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001243
Jim Grosbach4b905842013-09-20 23:08:21 +00001244 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001245 case AsmToken::EqualEqual:
1246 Kind = MCBinaryExpr::EQ;
1247 return 3;
1248 case AsmToken::ExclaimEqual:
1249 case AsmToken::LessGreater:
1250 Kind = MCBinaryExpr::NE;
1251 return 3;
1252 case AsmToken::Less:
1253 Kind = MCBinaryExpr::LT;
1254 return 3;
1255 case AsmToken::LessEqual:
1256 Kind = MCBinaryExpr::LTE;
1257 return 3;
1258 case AsmToken::Greater:
1259 Kind = MCBinaryExpr::GT;
1260 return 3;
1261 case AsmToken::GreaterEqual:
1262 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001263 return 3;
1264
Jim Grosbach4b905842013-09-20 23:08:21 +00001265 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001266 case AsmToken::LessLess:
1267 Kind = MCBinaryExpr::Shl;
1268 return 4;
1269 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001270 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001271 return 4;
1272
Jim Grosbach4b905842013-09-20 23:08:21 +00001273 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001274 case AsmToken::Plus:
1275 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001276 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001277 case AsmToken::Minus:
1278 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001279 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001280
Jim Grosbach4b905842013-09-20 23:08:21 +00001281 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001282 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001283 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001284 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001285 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001286 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001287 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001288 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001289 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001290 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001291 }
1292}
1293
David Majnemer0993e0b2015-10-26 03:15:34 +00001294static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1295 MCBinaryExpr::Opcode &Kind,
1296 bool ShouldUseLogicalShr) {
1297 switch (K) {
1298 default:
1299 return 0; // not a binop.
1300
1301 // Lowest Precedence: &&, ||
1302 case AsmToken::AmpAmp:
1303 Kind = MCBinaryExpr::LAnd;
1304 return 2;
1305 case AsmToken::PipePipe:
1306 Kind = MCBinaryExpr::LOr;
1307 return 1;
1308
1309 // Low Precedence: ==, !=, <>, <, <=, >, >=
1310 case AsmToken::EqualEqual:
1311 Kind = MCBinaryExpr::EQ;
1312 return 3;
1313 case AsmToken::ExclaimEqual:
1314 case AsmToken::LessGreater:
1315 Kind = MCBinaryExpr::NE;
1316 return 3;
1317 case AsmToken::Less:
1318 Kind = MCBinaryExpr::LT;
1319 return 3;
1320 case AsmToken::LessEqual:
1321 Kind = MCBinaryExpr::LTE;
1322 return 3;
1323 case AsmToken::Greater:
1324 Kind = MCBinaryExpr::GT;
1325 return 3;
1326 case AsmToken::GreaterEqual:
1327 Kind = MCBinaryExpr::GTE;
1328 return 3;
1329
1330 // Low Intermediate Precedence: +, -
1331 case AsmToken::Plus:
1332 Kind = MCBinaryExpr::Add;
1333 return 4;
1334 case AsmToken::Minus:
1335 Kind = MCBinaryExpr::Sub;
1336 return 4;
1337
1338 // High Intermediate Precedence: |, &, ^
1339 //
1340 // FIXME: gas seems to support '!' as an infix operator?
1341 case AsmToken::Pipe:
1342 Kind = MCBinaryExpr::Or;
1343 return 5;
1344 case AsmToken::Caret:
1345 Kind = MCBinaryExpr::Xor;
1346 return 5;
1347 case AsmToken::Amp:
1348 Kind = MCBinaryExpr::And;
1349 return 5;
1350
1351 // Highest Precedence: *, /, %, <<, >>
1352 case AsmToken::Star:
1353 Kind = MCBinaryExpr::Mul;
1354 return 6;
1355 case AsmToken::Slash:
1356 Kind = MCBinaryExpr::Div;
1357 return 6;
1358 case AsmToken::Percent:
1359 Kind = MCBinaryExpr::Mod;
1360 return 6;
1361 case AsmToken::LessLess:
1362 Kind = MCBinaryExpr::Shl;
1363 return 6;
1364 case AsmToken::GreaterGreater:
1365 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1366 return 6;
1367 }
1368}
1369
1370unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1371 MCBinaryExpr::Opcode &Kind) {
1372 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1373 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1374 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1375}
1376
Jim Grosbach4b905842013-09-20 23:08:21 +00001377/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001378/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001379bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001380 SMLoc &EndLoc) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001381 while (1) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001382 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001383 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001384
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001385 // If the next token is lower precedence than we are allowed to eat, return
1386 // successfully with what we ate already.
1387 if (TokPrec < Precedence)
1388 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001389
Sean Callanan686ed8d2010-01-19 20:22:31 +00001390 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001391
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001392 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001393 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001394 if (parsePrimaryExpr(RHS, EndLoc))
1395 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001396
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001397 // If BinOp binds less tightly with RHS than the operator after RHS, let
1398 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001399 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001400 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001401 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1402 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001403
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001404 // Merge LHS and RHS according to operator.
Jim Grosbach13760bd2015-05-30 01:25:56 +00001405 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001406 }
1407}
1408
Chris Lattner36e02122009-06-21 20:54:55 +00001409/// ParseStatement:
1410/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001411/// ::= Label* Directive ...Operands... EndOfStatement
1412/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001413bool AsmParser::parseStatement(ParseStatementInfo &Info,
1414 MCAsmParserSemaCallback *SI) {
Nirav Davefd910412016-06-17 16:06:17 +00001415 // Eat initial spaces and comments
1416 while (Lexer.is(AsmToken::Space))
1417 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001418 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001419 // if this is a line comment we can drop it safely
1420 if (getTok().getString().front() == '\r' ||
1421 getTok().getString().front() == '\n')
1422 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001423 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001424 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001425 }
Nirav Dave9263ae32016-08-02 19:17:54 +00001426 if (Lexer.is(AsmToken::Hash)) {
1427 // Seeing a hash here means that it was an end-of-line comment in
1428 // an asm syntax where hash's are not comment and the previous
1429 // statement parser did not check the end of statement. Relex as
1430 // EndOfStatement.
1431 StringRef CommentStr = parseStringToEndOfStatement();
1432 Lexer.Lex();
1433 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1434 return false;
1435 }
Nirav Davefd910412016-06-17 16:06:17 +00001436 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001437 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001438 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001439 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001440 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001441 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001442 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001443 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001444 if (Lexer.is(AsmToken::Integer)) {
1445 LocalLabelVal = getTok().getIntVal();
1446 if (LocalLabelVal < 0) {
1447 if (!TheCondState.Ignore)
1448 return TokError("unexpected token at start of statement");
1449 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001450 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001451 IDVal = getTok().getString();
1452 Lex(); // Consume the integer token to be used as an identifier token.
1453 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands41b4a6b2010-07-12 08:16:59 +00001454 if (!TheCondState.Ignore)
1455 return TokError("unexpected token at start of statement");
Kevin Enderby0510b482010-05-17 23:08:19 +00001456 }
1457 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001458 } else if (Lexer.is(AsmToken::Dot)) {
1459 // Treat '.' as a valid identifier in this context.
1460 Lex();
1461 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001462 } else if (Lexer.is(AsmToken::LCurly)) {
1463 // Treat '{' as a valid identifier in this context.
1464 Lex();
1465 IDVal = "{";
1466
1467 } else if (Lexer.is(AsmToken::RCurly)) {
1468 // Treat '}' as a valid identifier in this context.
1469 Lex();
1470 IDVal = "}";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001471 } else if (parseIdentifier(IDVal)) {
Chris Lattner926885c2010-04-17 18:14:27 +00001472 if (!TheCondState.Ignore)
1473 return TokError("unexpected token at start of statement");
1474 IDVal = "";
1475 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001476
Chris Lattner926885c2010-04-17 18:14:27 +00001477 // Handle conditional assembly here before checking for skipping. We
1478 // have to do this so that .endif isn't skipped in a ".if 0" block for
1479 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001480 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001481 DirectiveKindMap.find(IDVal);
1482 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1483 ? DK_NO_DIRECTIVE
1484 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001485 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001486 default:
1487 break;
1488 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001489 case DK_IFEQ:
1490 case DK_IFGE:
1491 case DK_IFGT:
1492 case DK_IFLE:
1493 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001494 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001495 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001496 case DK_IFB:
1497 return parseDirectiveIfb(IDLoc, true);
1498 case DK_IFNB:
1499 return parseDirectiveIfb(IDLoc, false);
1500 case DK_IFC:
1501 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001502 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001503 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001504 case DK_IFNC:
1505 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001506 case DK_IFNES:
1507 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001508 case DK_IFDEF:
1509 return parseDirectiveIfdef(IDLoc, true);
1510 case DK_IFNDEF:
1511 case DK_IFNOTDEF:
1512 return parseDirectiveIfdef(IDLoc, false);
1513 case DK_ELSEIF:
1514 return parseDirectiveElseIf(IDLoc);
1515 case DK_ELSE:
1516 return parseDirectiveElse(IDLoc);
1517 case DK_ENDIF:
1518 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001519 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001520
Eli Bendersky88024712013-01-16 19:32:36 +00001521 // Ignore the statement if in the middle of inactive conditional
1522 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001523 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001524 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001525 return false;
1526 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001527
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001528 // FIXME: Recurse on local labels?
1529
1530 // See what kind of statement we have.
1531 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001532 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001533 if (!getTargetParser().isLabel(ID))
1534 break;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001535 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00001536
Chris Lattner36e02122009-06-21 20:54:55 +00001537 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001538 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001539
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001540 // Diagnose attempt to use '.' as a label.
1541 if (IDVal == ".")
1542 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1543
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001544 // Diagnose attempt to use a variable as a label.
1545 //
1546 // FIXME: Diagnostics. Note the location of the definition as a label.
1547 // FIXME: This doesn't diagnose assignment to a symbol which has been
1548 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001549 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001550 if (LocalLabelVal == -1) {
1551 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001552 StringRef RewrittenLabel =
1553 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1554 assert(RewrittenLabel.size() &&
1555 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001556 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1557 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001558 IDVal = RewrittenLabel;
1559 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001560 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001561 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001562 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
David Majnemer58cb80c2014-12-24 10:27:50 +00001563
1564 Sym->redefineIfPossible();
1565
Daniel Dunbardeb7ba92010-05-05 19:01:00 +00001566 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001567 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencer530ce852010-10-09 11:00:50 +00001568
Nirav Dave9263ae32016-08-02 19:17:54 +00001569 // End of Labels should be treated as end of line for lexing
1570 // purposes but that information is not available to the Lexer who
1571 // does not understand Labels. This may cause us to see a Hash
1572 // here instead of a preprocessor line comment.
1573 if (getTok().is(AsmToken::Hash)) {
1574 StringRef CommentStr = parseStringToEndOfStatement();
1575 Lexer.Lex();
1576 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1577 }
1578
Nirav Dave8ea792d2016-07-13 14:03:12 +00001579 // Consume any end of statement token, if present, to avoid spurious
1580 // AddBlankLine calls().
1581 if (getTok().is(AsmToken::EndOfStatement)) {
1582 Lex();
1583 }
1584
Daniel Dunbare73b2672009-08-26 22:13:22 +00001585 // Emit the label.
Chad Rosierf3feab32013-01-07 20:34:12 +00001586 if (!ParsingInlineAsm)
1587 Out.EmitLabel(Sym);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001588
Kevin Enderbye7739d42011-12-09 18:09:40 +00001589 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001590 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001591 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001592 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1593 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001594
Tim Northover1744d0a2013-10-25 12:49:50 +00001595 getTargetParser().onLabelParsed(Sym);
1596
Nirav Dave8ea792d2016-07-13 14:03:12 +00001597
Daniel Dunbar8271d1bb2010-05-23 18:36:34 +00001598
Eli Friedman0f4871d2012-10-22 23:58:19 +00001599 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001600 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001601
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001602 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001603 if (!getTargetParser().equalIsAsmAssignment())
1604 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001605 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001606 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001607
Jim Grosbach4b905842013-09-20 23:08:21 +00001608 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001609
1610 default: // Normal instruction or directive.
1611 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001612 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001613
1614 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001615 if (areMacrosEnabled())
1616 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1617 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001618 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001619
Michael J. Spencer530ce852010-10-09 11:00:50 +00001620 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001621
Eli Bendersky17233942013-01-15 22:59:42 +00001622 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001623 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001624 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001625 //
Eli Bendersky17233942013-01-15 22:59:42 +00001626 // 1. The target-specific assembly parser. Some directives are target
1627 // specific or may potentially behave differently on certain targets.
1628 // 2. Asm parser extensions. For example, platform-specific parsers
1629 // (like the ELF parser) register themselves as extensions.
1630 // 3. The generic directive parser implemented by this class. These are
1631 // all the directives that behave in a target and platform independent
1632 // manner, or at least have a default behavior that's shared between
1633 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001634
Oliver Stannard21718282016-07-26 14:19:47 +00001635 getTargetParser().flushPendingInstructions(getStreamer());
1636
Eli Bendersky17233942013-01-15 22:59:42 +00001637 // First query the target-specific parser. It will return 'true' if it
1638 // isn't interested in this directive.
Akira Hatanakad3590752012-07-05 19:09:33 +00001639 if (!getTargetParser().ParseDirective(ID))
1640 return false;
1641
Alp Tokercb402912014-01-24 17:20:08 +00001642 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001643 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001644 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1645 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001646 if (Handler.first)
1647 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1648
1649 // Finally, if no one else is interested in this directive, it must be
1650 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001651 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001652 default:
1653 break;
1654 case DK_SET:
1655 case DK_EQU:
1656 return parseDirectiveSet(IDVal, true);
1657 case DK_EQUIV:
1658 return parseDirectiveSet(IDVal, false);
1659 case DK_ASCII:
1660 return parseDirectiveAscii(IDVal, false);
1661 case DK_ASCIZ:
1662 case DK_STRING:
1663 return parseDirectiveAscii(IDVal, true);
1664 case DK_BYTE:
1665 return parseDirectiveValue(1);
1666 case DK_SHORT:
1667 case DK_VALUE:
1668 case DK_2BYTE:
1669 return parseDirectiveValue(2);
1670 case DK_LONG:
1671 case DK_INT:
1672 case DK_4BYTE:
1673 return parseDirectiveValue(4);
1674 case DK_QUAD:
1675 case DK_8BYTE:
1676 return parseDirectiveValue(8);
David Woodhoused6de0d92014-02-01 16:20:59 +00001677 case DK_OCTA:
1678 return parseDirectiveOctaValue();
Jim Grosbach4b905842013-09-20 23:08:21 +00001679 case DK_SINGLE:
1680 case DK_FLOAT:
1681 return parseDirectiveRealValue(APFloat::IEEEsingle);
1682 case DK_DOUBLE:
1683 return parseDirectiveRealValue(APFloat::IEEEdouble);
1684 case DK_ALIGN: {
1685 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1686 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1687 }
1688 case DK_ALIGN32: {
1689 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1690 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1691 }
1692 case DK_BALIGN:
1693 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1694 case DK_BALIGNW:
1695 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1696 case DK_BALIGNL:
1697 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1698 case DK_P2ALIGN:
1699 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1700 case DK_P2ALIGNW:
1701 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1702 case DK_P2ALIGNL:
1703 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1704 case DK_ORG:
1705 return parseDirectiveOrg();
1706 case DK_FILL:
1707 return parseDirectiveFill();
1708 case DK_ZERO:
1709 return parseDirectiveZero();
1710 case DK_EXTERN:
1711 eatToEndOfStatement(); // .extern is the default, ignore it.
1712 return false;
1713 case DK_GLOBL:
1714 case DK_GLOBAL:
1715 return parseDirectiveSymbolAttribute(MCSA_Global);
1716 case DK_LAZY_REFERENCE:
1717 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1718 case DK_NO_DEAD_STRIP:
1719 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1720 case DK_SYMBOL_RESOLVER:
1721 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1722 case DK_PRIVATE_EXTERN:
1723 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1724 case DK_REFERENCE:
1725 return parseDirectiveSymbolAttribute(MCSA_Reference);
1726 case DK_WEAK_DEFINITION:
1727 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1728 case DK_WEAK_REFERENCE:
1729 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1730 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1731 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1732 case DK_COMM:
1733 case DK_COMMON:
1734 return parseDirectiveComm(/*IsLocal=*/false);
1735 case DK_LCOMM:
1736 return parseDirectiveComm(/*IsLocal=*/true);
1737 case DK_ABORT:
1738 return parseDirectiveAbort();
1739 case DK_INCLUDE:
1740 return parseDirectiveInclude();
1741 case DK_INCBIN:
1742 return parseDirectiveIncbin();
1743 case DK_CODE16:
1744 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001745 return TokError(Twine(IDVal) +
1746 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001747 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001748 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001749 case DK_IRP:
1750 return parseDirectiveIrp(IDLoc);
1751 case DK_IRPC:
1752 return parseDirectiveIrpc(IDLoc);
1753 case DK_ENDR:
1754 return parseDirectiveEndr(IDLoc);
1755 case DK_BUNDLE_ALIGN_MODE:
1756 return parseDirectiveBundleAlignMode();
1757 case DK_BUNDLE_LOCK:
1758 return parseDirectiveBundleLock();
1759 case DK_BUNDLE_UNLOCK:
1760 return parseDirectiveBundleUnlock();
1761 case DK_SLEB128:
1762 return parseDirectiveLEB128(true);
1763 case DK_ULEB128:
1764 return parseDirectiveLEB128(false);
1765 case DK_SPACE:
1766 case DK_SKIP:
1767 return parseDirectiveSpace(IDVal);
1768 case DK_FILE:
1769 return parseDirectiveFile(IDLoc);
1770 case DK_LINE:
1771 return parseDirectiveLine();
1772 case DK_LOC:
1773 return parseDirectiveLoc();
1774 case DK_STABS:
1775 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001776 case DK_CV_FILE:
1777 return parseDirectiveCVFile();
1778 case DK_CV_LOC:
1779 return parseDirectiveCVLoc();
1780 case DK_CV_LINETABLE:
1781 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00001782 case DK_CV_INLINE_LINETABLE:
1783 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00001784 case DK_CV_DEF_RANGE:
1785 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001786 case DK_CV_STRINGTABLE:
1787 return parseDirectiveCVStringTable();
1788 case DK_CV_FILECHECKSUMS:
1789 return parseDirectiveCVFileChecksums();
Jim Grosbach4b905842013-09-20 23:08:21 +00001790 case DK_CFI_SECTIONS:
1791 return parseDirectiveCFISections();
1792 case DK_CFI_STARTPROC:
1793 return parseDirectiveCFIStartProc();
1794 case DK_CFI_ENDPROC:
1795 return parseDirectiveCFIEndProc();
1796 case DK_CFI_DEF_CFA:
1797 return parseDirectiveCFIDefCfa(IDLoc);
1798 case DK_CFI_DEF_CFA_OFFSET:
1799 return parseDirectiveCFIDefCfaOffset();
1800 case DK_CFI_ADJUST_CFA_OFFSET:
1801 return parseDirectiveCFIAdjustCfaOffset();
1802 case DK_CFI_DEF_CFA_REGISTER:
1803 return parseDirectiveCFIDefCfaRegister(IDLoc);
1804 case DK_CFI_OFFSET:
1805 return parseDirectiveCFIOffset(IDLoc);
1806 case DK_CFI_REL_OFFSET:
1807 return parseDirectiveCFIRelOffset(IDLoc);
1808 case DK_CFI_PERSONALITY:
1809 return parseDirectiveCFIPersonalityOrLsda(true);
1810 case DK_CFI_LSDA:
1811 return parseDirectiveCFIPersonalityOrLsda(false);
1812 case DK_CFI_REMEMBER_STATE:
1813 return parseDirectiveCFIRememberState();
1814 case DK_CFI_RESTORE_STATE:
1815 return parseDirectiveCFIRestoreState();
1816 case DK_CFI_SAME_VALUE:
1817 return parseDirectiveCFISameValue(IDLoc);
1818 case DK_CFI_RESTORE:
1819 return parseDirectiveCFIRestore(IDLoc);
1820 case DK_CFI_ESCAPE:
1821 return parseDirectiveCFIEscape();
1822 case DK_CFI_SIGNAL_FRAME:
1823 return parseDirectiveCFISignalFrame();
1824 case DK_CFI_UNDEFINED:
1825 return parseDirectiveCFIUndefined(IDLoc);
1826 case DK_CFI_REGISTER:
1827 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00001828 case DK_CFI_WINDOW_SAVE:
1829 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00001830 case DK_MACROS_ON:
1831 case DK_MACROS_OFF:
1832 return parseDirectiveMacrosOnOff(IDVal);
1833 case DK_MACRO:
1834 return parseDirectiveMacro(IDLoc);
Nico Weber155dccd12014-07-24 17:08:39 +00001835 case DK_EXITM:
1836 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001837 case DK_ENDM:
1838 case DK_ENDMACRO:
1839 return parseDirectiveEndMacro(IDVal);
1840 case DK_PURGEM:
1841 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00001842 case DK_END:
1843 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00001844 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00001845 return parseDirectiveError(IDLoc, false);
1846 case DK_ERROR:
1847 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00001848 case DK_WARNING:
1849 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00001850 case DK_RELOC:
1851 return parseDirectiveReloc(IDLoc);
Eli Friedman20b02642010-07-19 04:17:25 +00001852 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00001853
Jim Grosbach758e0cc2012-05-01 18:38:27 +00001854 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00001855 }
Chris Lattner36e02122009-06-21 20:54:55 +00001856
Chad Rosierc7f552c2013-02-12 21:33:51 +00001857 // __asm _emit or __asm __emit
1858 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1859 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001860 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00001861
1862 // __asm align
1863 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001864 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00001865
Michael Zuckerman02ecd432015-12-13 17:07:23 +00001866 if (ParsingInlineAsm && (IDVal == "even"))
1867 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001868 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00001869
Chris Lattner7cbfa442010-05-19 23:34:33 +00001870 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00001871 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00001872 ParseInstructionInfo IInfo(Info.AsmRewrites);
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001873 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001874 Info.ParsedOperands);
Chad Rosier149e8e02012-12-12 22:45:52 +00001875 Info.ParseError = HadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00001876
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001877 // Dump the parsed representation, if requested.
1878 if (getShowParsedOperands()) {
1879 SmallString<256> Str;
1880 raw_svector_ostream OS(Str);
1881 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001882 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001883 if (i != 0)
1884 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001885 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001886 }
1887 OS << "]";
1888
Jim Grosbach4b905842013-09-20 23:08:21 +00001889 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001890 }
1891
Oliver Stannard8b273082014-06-19 15:52:37 +00001892 // If we are generating dwarf for the current section then generate a .loc
1893 // directive for the instruction.
Kevin Enderby6469fc22011-11-01 22:27:22 +00001894 if (!HadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00001895 getContext().getGenDwarfSectionSyms().count(
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00001896 getStreamer().getCurrentSection().first)) {
1897 unsigned Line;
1898 if (ActiveMacros.empty())
1899 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1900 else
Frederic Riss16238d92015-06-25 21:57:33 +00001901 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
1902 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001903
Eli Bendersky88024712013-01-16 19:32:36 +00001904 // If we previously parsed a cpp hash file line comment then make sure the
1905 // current Dwarf File is for the CppHashFilename if not then emit the
1906 // Dwarf File table for it and adjust the line number for the .loc.
Tim Northoverc0bef992016-04-13 19:46:54 +00001907 if (CppHashInfo.Filename.size()) {
David Blaikiec714ef42014-03-17 01:52:11 +00001908 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00001909 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00001910 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001911
Jim Grosbach4b905842013-09-20 23:08:21 +00001912 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1913 // cache with the different Loc from the call above we save the last
1914 // info we queried here with SrcMgr.FindLineNumber().
1915 unsigned CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00001916 if (LastQueryIDLoc == CppHashInfo.Loc &&
1917 LastQueryBuffer == CppHashInfo.Buf)
Jim Grosbach4b905842013-09-20 23:08:21 +00001918 CppHashLocLineNo = LastQueryLine;
1919 else {
Tim Northoverc0bef992016-04-13 19:46:54 +00001920 CppHashLocLineNo =
1921 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Jim Grosbach4b905842013-09-20 23:08:21 +00001922 LastQueryLine = CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00001923 LastQueryIDLoc = CppHashInfo.Loc;
1924 LastQueryBuffer = CppHashInfo.Buf;
Jim Grosbach4b905842013-09-20 23:08:21 +00001925 }
Tim Northoverc0bef992016-04-13 19:46:54 +00001926 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00001927 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001928
Jim Grosbach4b905842013-09-20 23:08:21 +00001929 getStreamer().EmitDwarfLocDirective(
1930 getContext().getGenDwarfFileNumber(), Line, 0,
1931 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1932 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00001933 }
1934
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00001935 // If parsing succeeded, match the instruction.
Chad Rosier49963552012-10-13 00:26:04 +00001936 if (!HadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00001937 uint64_t ErrorInfo;
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001938 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1939 Info.ParsedOperands, Out,
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00001940 ErrorInfo, ParsingInlineAsm);
Chad Rosier49963552012-10-13 00:26:04 +00001941 }
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001942
Chris Lattnera2a9d162010-09-11 16:18:25 +00001943 // Don't skip the rest of the line, the instruction parser is responsible for
1944 // that.
1945 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00001946}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00001947
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00001948// Parse and erase curly braces marking block start/end
1949bool
1950AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
1951 // Identify curly brace marking block start/end
1952 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
1953 return false;
1954
1955 SMLoc StartLoc = Lexer.getLoc();
1956 Lex(); // Eat the brace
1957 if (Lexer.is(AsmToken::EndOfStatement))
1958 Lex(); // Eat EndOfStatement following the brace
1959
1960 // Erase the block start/end brace from the output asm string
1961 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
1962 StartLoc.getPointer());
1963 return true;
1964}
1965
Jim Grosbach4b905842013-09-20 23:08:21 +00001966/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00001967/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00001968bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00001969 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00001970 // Lexer only ever emits HashDirective if it fully formed if it's
1971 // done the checking already so this is an internal error.
1972 assert(getTok().is(AsmToken::Integer) &&
1973 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00001974 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00001975 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00001976 assert(getTok().is(AsmToken::String) &&
1977 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00001978 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00001979 Lex();
Kevin Enderby72553612011-09-13 23:45:18 +00001980 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00001981 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00001982
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001983 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00001984 CppHashInfo.Loc = L;
1985 CppHashInfo.Filename = Filename;
1986 CppHashInfo.LineNumber = LineNumber;
1987 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00001988 return false;
1989}
1990
Jim Grosbach4b905842013-09-20 23:08:21 +00001991/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001992/// for the Filename and LineNo if any in the diagnostic.
1993void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001994 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001995 raw_ostream &OS = errs();
1996
1997 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00001998 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00001999 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2000 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002001 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002002
Jim Grosbach4b905842013-09-20 23:08:21 +00002003 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002004 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002005 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2006 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2007 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002008 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2009 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002010 }
2011
Eric Christophera7c32732012-12-18 00:30:54 +00002012 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002013 // manager changed or buffer changed (like in a nested include) then just
2014 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002015 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002016 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002017 if (Parser->SavedDiagHandler)
2018 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2019 else
Craig Topper353eda42014-04-24 06:44:33 +00002020 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002021 return;
2022 }
2023
Eric Christophera7c32732012-12-18 00:30:54 +00002024 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002025 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2026 // for the diagnostic.
2027 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002028
2029 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2030 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002031 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002032 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002033 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002034
Jim Grosbach4b905842013-09-20 23:08:21 +00002035 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2036 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002037 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002038
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002039 if (Parser->SavedDiagHandler)
2040 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2041 else
Craig Topper353eda42014-04-24 06:44:33 +00002042 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002043}
2044
Rafael Espindola2c064482012-08-21 18:29:30 +00002045// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2046// difference being that that function accepts '@' as part of identifiers and
2047// we can't do that. AsmLexer.cpp should probably be changed to handle
2048// '@' as a special case when needed.
2049static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002050 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2051 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002052}
2053
Rafael Espindola34b9c512012-06-03 23:57:14 +00002054bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002055 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002056 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002057 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002058 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002059 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002060 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002061 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002062
Preston Gurd05500642012-09-19 20:36:12 +00002063 // A macro without parameters is handled differently on Darwin:
2064 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002065 while (!Body.empty()) {
2066 // Scan for the next substitution.
2067 std::size_t End = Body.size(), Pos = 0;
2068 for (; Pos != End; ++Pos) {
2069 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002070 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002071 // This macro has no parameters, look for $0, $1, etc.
2072 if (Body[Pos] != '$' || Pos + 1 == End)
2073 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002074
Rafael Espindola1134ab232011-06-05 02:43:45 +00002075 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002076 if (Next == '$' || Next == 'n' ||
2077 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002078 break;
2079 } else {
2080 // This macro has parameters, look for \foo, \bar, etc.
2081 if (Body[Pos] == '\\' && Pos + 1 != End)
2082 break;
2083 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002084 }
2085
2086 // Add the prefix.
2087 OS << Body.slice(0, Pos);
2088
2089 // Check if we reached the end.
2090 if (Pos == End)
2091 break;
2092
Benjamin Kramer513e7442014-02-20 13:36:32 +00002093 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002094 switch (Body[Pos + 1]) {
2095 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002096 case '$':
2097 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002098 break;
2099
Jim Grosbach4b905842013-09-20 23:08:21 +00002100 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002101 case 'n':
2102 OS << A.size();
2103 break;
2104
Jim Grosbach4b905842013-09-20 23:08:21 +00002105 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002106 default: {
2107 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002108 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002109 if (Index >= A.size())
2110 break;
2111
2112 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002113 for (const AsmToken &Token : A[Index])
2114 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002115 break;
2116 }
2117 }
2118 Pos += 2;
2119 } else {
2120 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002121
2122 // Check for the \@ pseudo-variable.
2123 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002124 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002125 else
2126 while (isIdentifierChar(Body[I]) && I + 1 != End)
2127 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002128
Jim Grosbach4b905842013-09-20 23:08:21 +00002129 const char *Begin = Body.data() + Pos + 1;
2130 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002131 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002132
Toma Tabacu217116e2015-04-27 10:50:29 +00002133 if (Argument == "@") {
2134 OS << NumOfMacroInstantiations;
2135 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002136 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002137 for (; Index < NParameters; ++Index)
2138 if (Parameters[Index].Name == Argument)
2139 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002140
Toma Tabacu217116e2015-04-27 10:50:29 +00002141 if (Index == NParameters) {
2142 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2143 Pos += 3;
2144 else {
2145 OS << '\\' << Argument;
2146 Pos = I;
2147 }
2148 } else {
2149 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002150 for (const AsmToken &Token : A[Index])
Toma Tabacu217116e2015-04-27 10:50:29 +00002151 // We expect no quotes around the string's contents when
2152 // parsing for varargs.
Craig Topper84008482015-10-10 05:38:14 +00002153 if (Token.getKind() != AsmToken::String || VarargParameter)
2154 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002155 else
Craig Topper84008482015-10-10 05:38:14 +00002156 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002157
2158 Pos += 1 + Argument.size();
2159 }
Preston Gurd05500642012-09-19 20:36:12 +00002160 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002161 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002162 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002163 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002164 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002165
Rafael Espindola1134ab232011-06-05 02:43:45 +00002166 return false;
2167}
Daniel Dunbar43235712010-07-18 18:54:11 +00002168
Nico Weber2a8f9222014-07-24 16:29:04 +00002169MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002170 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002171 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002172 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002173
Jim Grosbach4b905842013-09-20 23:08:21 +00002174static bool isOperator(AsmToken::TokenKind kind) {
2175 switch (kind) {
2176 default:
2177 return false;
2178 case AsmToken::Plus:
2179 case AsmToken::Minus:
2180 case AsmToken::Tilde:
2181 case AsmToken::Slash:
2182 case AsmToken::Star:
2183 case AsmToken::Dot:
2184 case AsmToken::Equal:
2185 case AsmToken::EqualEqual:
2186 case AsmToken::Pipe:
2187 case AsmToken::PipePipe:
2188 case AsmToken::Caret:
2189 case AsmToken::Amp:
2190 case AsmToken::AmpAmp:
2191 case AsmToken::Exclaim:
2192 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002193 case AsmToken::Less:
2194 case AsmToken::LessEqual:
2195 case AsmToken::LessLess:
2196 case AsmToken::LessGreater:
2197 case AsmToken::Greater:
2198 case AsmToken::GreaterEqual:
2199 case AsmToken::GreaterGreater:
2200 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002201 }
2202}
2203
David Majnemer16252452014-01-29 00:07:39 +00002204namespace {
2205class AsmLexerSkipSpaceRAII {
2206public:
2207 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2208 Lexer.setSkipSpace(SkipSpace);
2209 }
2210
2211 ~AsmLexerSkipSpaceRAII() {
2212 Lexer.setSkipSpace(true);
2213 }
2214
2215private:
2216 AsmLexer &Lexer;
2217};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002218}
David Majnemer16252452014-01-29 00:07:39 +00002219
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002220bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2221
2222 if (Vararg) {
2223 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2224 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002225 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002226 }
2227 return false;
2228 }
2229
Rafael Espindola768b41c2012-06-15 14:02:34 +00002230 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002231
David Majnemer16252452014-01-29 00:07:39 +00002232 // Darwin doesn't use spaces to delmit arguments.
2233 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002234
Scott Egertona1fa68a2016-02-11 13:48:49 +00002235 bool SpaceEaten;
2236
Rafael Espindola768b41c2012-06-15 14:02:34 +00002237 for (;;) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002238 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002239 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002240 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002241
Scott Egertona1fa68a2016-02-11 13:48:49 +00002242 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002243
Scott Egertona1fa68a2016-02-11 13:48:49 +00002244 if (Lexer.is(AsmToken::Comma))
2245 break;
2246
2247 if (Lexer.is(AsmToken::Space)) {
2248 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002249 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002250 }
Preston Gurd05500642012-09-19 20:36:12 +00002251
2252 // Spaces can delimit parameters, but could also be part an expression.
2253 // If the token after a space is an operator, add the token and the next
2254 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002255 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002256 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002257 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002258 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002259
Scott Egertona1fa68a2016-02-11 13:48:49 +00002260 // Whitespace after an operator can be ignored.
2261 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002262 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002263
2264 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002265 }
2266 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002267 if (SpaceEaten)
2268 break;
Preston Gurd05500642012-09-19 20:36:12 +00002269 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002270
Jim Grosbach4b905842013-09-20 23:08:21 +00002271 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002272 // to be able to fill in the remaining default parameter values
2273 if (Lexer.is(AsmToken::EndOfStatement))
2274 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002275
2276 // Adjust the current parentheses level.
2277 if (Lexer.is(AsmToken::LParen))
2278 ++ParenLevel;
2279 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2280 --ParenLevel;
2281
2282 // Append the token to the current argument list.
2283 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002284 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002285 }
Preston Gurd05500642012-09-19 20:36:12 +00002286
Rafael Espindola768b41c2012-06-15 14:02:34 +00002287 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002288 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002289 return false;
2290}
2291
2292// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002293bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002294 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002295 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002296 bool NamedParametersFound = false;
2297 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002298
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002299 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002300 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002301
Rafael Espindola768b41c2012-06-15 14:02:34 +00002302 // Parse two kinds of macro invocations:
2303 // - macros defined without any parameters accept an arbitrary number of them
2304 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002305 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002306 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2307 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002308 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002309 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002310
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002311 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002312 if (parseIdentifier(FA.Name)) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002313 Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002314 eatToEndOfStatement();
2315 return true;
2316 }
2317
Nirav Davea645433c2016-07-18 15:24:03 +00002318 if (Lexer.isNot(AsmToken::Equal)) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002319 TokError("expected '=' after formal parameter identifier");
2320 eatToEndOfStatement();
2321 return true;
2322 }
2323 Lex();
2324
2325 NamedParametersFound = true;
2326 }
2327
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002328 if (NamedParametersFound && FA.Name.empty()) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002329 Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002330 eatToEndOfStatement();
2331 return true;
2332 }
2333
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002334 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2335 if (parseMacroArgument(FA.Value, Vararg))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002336 return true;
2337
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002338 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002339 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002340 unsigned FAI = 0;
2341 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002342 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002343 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002344
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002345 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002346 assert(M && "expected macro to be defined");
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002347 Error(IDLoc,
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002348 "parameter named '" + FA.Name + "' does not exist for macro '" +
Saleem Abdulrasool3f44cd72014-03-17 17:13:57 +00002349 M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002350 return true;
2351 }
2352 PI = FAI;
2353 }
2354
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002355 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002356 if (A.size() <= PI)
2357 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002358 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002359
2360 if (FALocs.size() <= PI)
2361 FALocs.resize(PI + 1);
2362
2363 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002364 }
Jim Grosbach206661622012-07-30 22:44:17 +00002365
Preston Gurd242ed3152012-09-19 20:29:04 +00002366 // At the end of the statement, fill in remaining arguments that have
2367 // default values. If there aren't any, then the next argument is
2368 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002369 if (Lexer.is(AsmToken::EndOfStatement)) {
2370 bool Failure = false;
2371 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2372 if (A[FAI].empty()) {
2373 if (M->Parameters[FAI].Required) {
2374 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2375 "missing value for required parameter "
2376 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2377 Failure = true;
2378 }
2379
2380 if (!M->Parameters[FAI].Value.empty())
2381 A[FAI] = M->Parameters[FAI].Value;
2382 }
2383 }
2384 return Failure;
2385 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002386
2387 if (Lexer.is(AsmToken::Comma))
2388 Lex();
2389 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002390
2391 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002392}
2393
Jim Grosbach4b905842013-09-20 23:08:21 +00002394const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002395 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2396 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002397}
2398
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002399void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2400 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002401}
2402
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002403void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002404
Jim Grosbach4b905842013-09-20 23:08:21 +00002405bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002406 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2407 // eliminate this, although we should protect against infinite loops.
2408 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2409 if (ActiveMacros.size() == MaxNestingDepth) {
2410 std::ostringstream MaxNestingDepthError;
2411 MaxNestingDepthError << "macros cannot be nested more than "
2412 << MaxNestingDepth << " levels deep."
2413 << " Use -asm-macro-max-nesting-depth to increase "
2414 "this limit.";
2415 return TokError(MaxNestingDepthError.str());
2416 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002417
Eli Bendersky38274122013-01-14 23:22:36 +00002418 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002419 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002420 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002421
Rafael Espindola1134ab232011-06-05 02:43:45 +00002422 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2423 // to hold the macro body with substitutions.
2424 SmallString<256> Buf;
2425 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002426 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002427
Toma Tabacu217116e2015-04-27 10:50:29 +00002428 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002429 return true;
2430
Eli Bendersky38274122013-01-14 23:22:36 +00002431 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002432 // instantiation.
2433 OS << ".endmacro\n";
2434
Rafael Espindola3560ff22014-08-27 20:03:13 +00002435 std::unique_ptr<MemoryBuffer> Instantiation =
2436 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002437
Daniel Dunbar43235712010-07-18 18:54:11 +00002438 // Create the macro instantiation object and add to the current macro
2439 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002440 MacroInstantiation *MI = new MacroInstantiation(
2441 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002442 ActiveMacros.push_back(MI);
2443
Toma Tabacu217116e2015-04-27 10:50:29 +00002444 ++NumOfMacroInstantiations;
2445
Daniel Dunbar43235712010-07-18 18:54:11 +00002446 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002447 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002448 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002449 Lex();
2450
2451 return false;
2452}
2453
Jim Grosbach4b905842013-09-20 23:08:21 +00002454void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002455 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002456 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002457 Lex();
2458
2459 // Pop the instantiation entry.
2460 delete ActiveMacros.back();
2461 ActiveMacros.pop_back();
2462}
2463
Jim Grosbach4b905842013-09-20 23:08:21 +00002464bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002465 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002466 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002467 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002468 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2469 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002470 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002471
Pete Cooper80d21cb2015-06-22 19:35:57 +00002472 if (!Sym) {
2473 // In the case where we parse an expression starting with a '.', we will
2474 // not generate an error, nor will we create a symbol. In this case we
2475 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002476 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002477 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002478
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002479 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002480 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002481 if (NoDeadStrip)
2482 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2483
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002484 return false;
2485}
2486
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002487/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002488/// ::= identifier
2489/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002490bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002491 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002492 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2493 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002494 // handle this as a context dependent token, instead we detect adjacent tokens
2495 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002496 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2497 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002498
Hans Wennborgce69d772013-10-18 20:46:28 +00002499 // Consume the prefix character, and check for a following identifier.
Nirav Dave1180e6892016-06-02 17:15:05 +00002500 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002501 if (Lexer.isNot(AsmToken::Identifier))
2502 return true;
2503
Hans Wennborgce69d772013-10-18 20:46:28 +00002504 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2505 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002506 return true;
2507
2508 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002509 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002510 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002511 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002512 return false;
2513 }
2514
Jim Grosbach4b905842013-09-20 23:08:21 +00002515 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002516 return true;
2517
Sean Callanan936b0d32010-01-19 21:44:56 +00002518 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002519
Sean Callanan686ed8d2010-01-19 20:22:31 +00002520 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002521
2522 return false;
2523}
2524
Jim Grosbach4b905842013-09-20 23:08:21 +00002525/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002526/// ::= .equ identifier ',' expression
2527/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002528/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002529bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002530 StringRef Name;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002531
Nirav Davea645433c2016-07-18 15:24:03 +00002532 if (check(parseIdentifier(Name),
2533 "expected identifier after '" + Twine(IDVal) + "'") ||
2534 parseToken(AsmToken::Comma, "unexpected token in '" + Twine(IDVal) + "'"))
2535 return true;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002536
Jim Grosbach4b905842013-09-20 23:08:21 +00002537 return parseAssignment(Name, allow_redef, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002538}
2539
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002540bool AsmParser::parseEscapedString(std::string &Data) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002541 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbaref668c12009-08-14 18:19:52 +00002542
2543 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002544 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002545 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2546 if (Str[i] != '\\') {
2547 Data += Str[i];
2548 continue;
2549 }
2550
2551 // Recognize escaped characters. Note that this escape semantics currently
2552 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2553 ++i;
2554 if (i == e)
2555 return TokError("unexpected backslash at end of string");
2556
2557 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002558 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002559 // Consume up to three octal characters.
2560 unsigned Value = Str[i] - '0';
2561
Jim Grosbach4b905842013-09-20 23:08:21 +00002562 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002563 ++i;
2564 Value = Value * 8 + (Str[i] - '0');
2565
Jim Grosbach4b905842013-09-20 23:08:21 +00002566 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002567 ++i;
2568 Value = Value * 8 + (Str[i] - '0');
2569 }
2570 }
2571
2572 if (Value > 255)
2573 return TokError("invalid octal escape sequence (out of range)");
2574
Jim Grosbach4b905842013-09-20 23:08:21 +00002575 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002576 continue;
2577 }
2578
2579 // Otherwise recognize individual escapes.
2580 switch (Str[i]) {
2581 default:
2582 // Just reject invalid escape sequences for now.
2583 return TokError("invalid escape sequence (unrecognized character)");
2584
2585 case 'b': Data += '\b'; break;
2586 case 'f': Data += '\f'; break;
2587 case 'n': Data += '\n'; break;
2588 case 'r': Data += '\r'; break;
2589 case 't': Data += '\t'; break;
2590 case '"': Data += '"'; break;
2591 case '\\': Data += '\\'; break;
2592 }
2593 }
2594
Nirav Davea645433c2016-07-18 15:24:03 +00002595 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002596 return false;
2597}
2598
Jim Grosbach4b905842013-09-20 23:08:21 +00002599/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002600/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002601bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002602 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002603 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002604
Daniel Dunbara10e5192009-06-24 23:30:00 +00002605 for (;;) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002606 std::string Data;
Nirav Davea645433c2016-07-18 15:24:03 +00002607 if (check(getTok().isNot(AsmToken::String),
2608 "expected string in '" + Twine(IDVal) + "' directive") ||
2609 parseEscapedString(Data))
Daniel Dunbaref668c12009-08-14 18:19:52 +00002610 return true;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002611
Rafael Espindola64e1af82013-07-02 15:49:13 +00002612 getStreamer().EmitBytes(Data);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002613 if (ZeroTerminated)
Rafael Espindola64e1af82013-07-02 15:49:13 +00002614 getStreamer().EmitBytes(StringRef("\0", 1));
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002615
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002616 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002617 break;
2618
Nirav Davea645433c2016-07-18 15:24:03 +00002619 if (parseToken(AsmToken::Comma,
2620 "unexpected token in '" + Twine(IDVal) + "' directive"))
2621 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002622 }
2623 }
2624
Sean Callanan686ed8d2010-01-19 20:22:31 +00002625 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002626 return false;
2627}
2628
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002629/// parseDirectiveReloc
2630/// ::= .reloc expression , identifier [ , expression ]
2631bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2632 const MCExpr *Offset;
2633 const MCExpr *Expr = nullptr;
2634
2635 SMLoc OffsetLoc = Lexer.getTok().getLoc();
2636 if (parseExpression(Offset))
2637 return true;
2638
2639 // We can only deal with constant expressions at the moment.
2640 int64_t OffsetValue;
Nirav Davea645433c2016-07-18 15:24:03 +00002641 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2642 "expression is not a constant value") ||
2643 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2644 parseToken(AsmToken::Comma, "expected comma") ||
2645 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2646 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002647
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002648 SMLoc NameLoc = Lexer.getTok().getLoc();
2649 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002650 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002651
2652 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002653 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002654 SMLoc ExprLoc = Lexer.getLoc();
2655 if (parseExpression(Expr))
2656 return true;
2657
2658 MCValue Value;
2659 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2660 return Error(ExprLoc, "expression must be relocatable");
2661 }
2662
Nirav Davea645433c2016-07-18 15:24:03 +00002663 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002664 "unexpected token in .reloc directive"))
2665 return true;
2666
2667 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2668 return Error(NameLoc, "unknown relocation name");
2669
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002670 return false;
2671}
2672
Jim Grosbach4b905842013-09-20 23:08:21 +00002673/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002674/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002675bool AsmParser::parseDirectiveValue(unsigned Size) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002676 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002677 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002678
Daniel Dunbara10e5192009-06-24 23:30:00 +00002679 for (;;) {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002680 const MCExpr *Value;
Jim Grosbach76346c32011-06-29 16:05:14 +00002681 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002682 if (parseExpression(Value))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002683 return true;
2684
Daniel Dunbar6738a2e2010-05-23 18:36:38 +00002685 // Special case constant expressions to match code generator.
Jim Grosbach76346c32011-06-29 16:05:14 +00002686 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2687 assert(Size <= 8 && "Invalid size");
2688 uint64_t IntValue = MCE->getValue();
2689 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2690 return Error(ExprLoc, "literal value out of range for directive");
Rafael Espindola64e1af82013-07-02 15:49:13 +00002691 getStreamer().EmitIntValue(IntValue, Size);
Jim Grosbach76346c32011-06-29 16:05:14 +00002692 } else
Kevin Enderby96918bc2014-04-22 17:27:29 +00002693 getStreamer().EmitValue(Value, Size, ExprLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002694
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002695 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002696 break;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002697
Daniel Dunbara10e5192009-06-24 23:30:00 +00002698 // FIXME: Improve diagnostic.
Nirav Davea645433c2016-07-18 15:24:03 +00002699 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
2700 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002701 }
2702 }
2703
Sean Callanan686ed8d2010-01-19 20:22:31 +00002704 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002705 return false;
2706}
2707
David Woodhoused6de0d92014-02-01 16:20:59 +00002708/// ParseDirectiveOctaValue
2709/// ::= .octa [ hexconstant (, hexconstant)* ]
2710bool AsmParser::parseDirectiveOctaValue() {
2711 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2712 checkForValidSection();
2713
2714 for (;;) {
Nirav Davea645433c2016-07-18 15:24:03 +00002715 if (getTok().is(AsmToken::Error))
David Woodhoused6de0d92014-02-01 16:20:59 +00002716 return true;
Nirav Davea645433c2016-07-18 15:24:03 +00002717 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
David Woodhoused6de0d92014-02-01 16:20:59 +00002718 return TokError("unknown token in expression");
2719
2720 SMLoc ExprLoc = getLexer().getLoc();
2721 APInt IntValue = getTok().getAPIntVal();
2722 Lex();
2723
2724 uint64_t hi, lo;
2725 if (IntValue.isIntN(64)) {
2726 hi = 0;
2727 lo = IntValue.getZExtValue();
2728 } else if (IntValue.isIntN(128)) {
David Woodhouse6c9a6f92014-02-01 16:52:33 +00002729 // It might actually have more than 128 bits, but the top ones are zero.
2730 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002731 lo = IntValue.getLoBits(64).getZExtValue();
2732 } else
2733 return Error(ExprLoc, "literal value out of range for directive");
2734
2735 if (MAI.isLittleEndian()) {
2736 getStreamer().EmitIntValue(lo, 8);
2737 getStreamer().EmitIntValue(hi, 8);
2738 } else {
2739 getStreamer().EmitIntValue(hi, 8);
2740 getStreamer().EmitIntValue(lo, 8);
2741 }
2742
2743 if (getLexer().is(AsmToken::EndOfStatement))
2744 break;
2745
2746 // FIXME: Improve diagnostic.
Nirav Davea645433c2016-07-18 15:24:03 +00002747 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
2748 return true;
David Woodhoused6de0d92014-02-01 16:20:59 +00002749 }
2750 }
2751
2752 Lex();
2753 return false;
2754}
2755
Jim Grosbach4b905842013-09-20 23:08:21 +00002756/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00002757/// ::= (.single | .double) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002758bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
Daniel Dunbar2af16532010-09-24 01:59:56 +00002759 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002760 checkForValidSection();
Daniel Dunbar2af16532010-09-24 01:59:56 +00002761
2762 for (;;) {
2763 // We don't truly support arithmetic on floating point expressions, so we
2764 // have to manually parse unary prefixes.
2765 bool IsNeg = false;
2766 if (getLexer().is(AsmToken::Minus)) {
Nirav Dave1180e6892016-06-02 17:15:05 +00002767 Lexer.Lex();
Daniel Dunbar2af16532010-09-24 01:59:56 +00002768 IsNeg = true;
2769 } else if (getLexer().is(AsmToken::Plus))
Nirav Dave1180e6892016-06-02 17:15:05 +00002770 Lexer.Lex();
Daniel Dunbar2af16532010-09-24 01:59:56 +00002771
Nirav Dave1180e6892016-06-02 17:15:05 +00002772 if (Lexer.is(AsmToken::Error))
2773 return TokError(Lexer.getErr());
2774 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
2775 Lexer.isNot(AsmToken::Identifier))
Daniel Dunbar2af16532010-09-24 01:59:56 +00002776 return TokError("unexpected token in directive");
2777
2778 // Convert to an APFloat.
2779 APFloat Value(Semantics);
Kevin Enderby5bbe9572011-03-29 21:11:52 +00002780 StringRef IDVal = getTok().getString();
2781 if (getLexer().is(AsmToken::Identifier)) {
2782 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2783 Value = APFloat::getInf(Semantics);
2784 else if (!IDVal.compare_lower("nan"))
2785 Value = APFloat::getNaN(Semantics, false, ~0);
2786 else
2787 return TokError("invalid floating point literal");
2788 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Jim Grosbach4b905842013-09-20 23:08:21 +00002789 APFloat::opInvalidOp)
Daniel Dunbar2af16532010-09-24 01:59:56 +00002790 return TokError("invalid floating point literal");
2791 if (IsNeg)
2792 Value.changeSign();
2793
2794 // Consume the numeric token.
2795 Lex();
2796
2797 // Emit the value as an integer.
2798 APInt AsInt = Value.bitcastToAPInt();
2799 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
Rafael Espindola64e1af82013-07-02 15:49:13 +00002800 AsInt.getBitWidth() / 8);
Daniel Dunbar2af16532010-09-24 01:59:56 +00002801
Nirav Dave1180e6892016-06-02 17:15:05 +00002802 if (Lexer.is(AsmToken::EndOfStatement))
Daniel Dunbar2af16532010-09-24 01:59:56 +00002803 break;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002804
Nirav Davea645433c2016-07-18 15:24:03 +00002805 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
2806 return true;
Daniel Dunbar2af16532010-09-24 01:59:56 +00002807 }
2808 }
2809
2810 Lex();
2811 return false;
2812}
2813
Jim Grosbach4b905842013-09-20 23:08:21 +00002814/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00002815/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002816bool AsmParser::parseDirectiveZero() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002817 checkForValidSection();
Rafael Espindola922e3f42010-09-16 15:03:59 +00002818
Petr Hosek67a94a72016-05-28 05:57:48 +00002819 SMLoc NumBytesLoc = Lexer.getLoc();
2820 const MCExpr *NumBytes;
2821 if (parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00002822 return true;
2823
Rafael Espindolab91bac62010-10-05 19:42:57 +00002824 int64_t Val = 0;
2825 if (getLexer().is(AsmToken::Comma)) {
2826 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002827 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00002828 return true;
2829 }
2830
Nirav Davea645433c2016-07-18 15:24:03 +00002831 if (parseToken(AsmToken::EndOfStatement,
2832 "unexpected token in '.zero' directive"))
2833 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00002834 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00002835
2836 return false;
2837}
2838
Jim Grosbach4b905842013-09-20 23:08:21 +00002839/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00002840/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002841bool AsmParser::parseDirectiveFill() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002842 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002843
Petr Hosek67a94a72016-05-28 05:57:48 +00002844 SMLoc NumValuesLoc = Lexer.getLoc();
2845 const MCExpr *NumValues;
2846 if (parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002847 return true;
2848
Roman Divackye33098f2013-09-24 17:44:41 +00002849 int64_t FillSize = 1;
2850 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002851
David Majnemer522d3db2014-02-01 07:19:38 +00002852 SMLoc SizeLoc, ExprLoc;
Roman Divackye33098f2013-09-24 17:44:41 +00002853 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbara10e5192009-06-24 23:30:00 +00002854
Nirav Davea645433c2016-07-18 15:24:03 +00002855 if (parseToken(AsmToken::Comma, "unexpected token in '.fill' directive") ||
2856 getTokenLoc(SizeLoc) || parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00002857 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002858
Roman Divackye33098f2013-09-24 17:44:41 +00002859 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00002860 if (parseToken(AsmToken::Comma,
2861 "unexpected token in '.fill' directive") ||
2862 getTokenLoc(ExprLoc) || parseAbsoluteExpression(FillExpr) ||
2863 parseToken(AsmToken::EndOfStatement,
2864 "unexpected token in '.fill' directive"))
Roman Divackye33098f2013-09-24 17:44:41 +00002865 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00002866 }
2867 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002868
David Majnemer522d3db2014-02-01 07:19:38 +00002869 if (FillSize < 0) {
2870 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00002871 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00002872 }
2873 if (FillSize > 8) {
2874 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2875 FillSize = 8;
2876 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002877
David Majnemer522d3db2014-02-01 07:19:38 +00002878 if (!isUInt<32>(FillExpr) && FillSize > 4)
2879 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2880
Petr Hosek67a94a72016-05-28 05:57:48 +00002881 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002882
2883 return false;
2884}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002885
Jim Grosbach4b905842013-09-20 23:08:21 +00002886/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002887/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002888bool AsmParser::parseDirectiveOrg() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002889 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002890
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002891 const MCExpr *Offset;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002892 if (parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002893 return true;
2894
2895 // Parse optional fill expression.
2896 int64_t FillExpr = 0;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002897 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00002898 if (parseToken(AsmToken::Comma, "unexpected token in '.org' directive") ||
2899 parseAbsoluteExpression(FillExpr))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002900 return true;
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002901 }
2902
Nirav Davea645433c2016-07-18 15:24:03 +00002903 if (parseToken(AsmToken::EndOfStatement,
2904 "unexpected token in '.org' directive"))
2905 return true;
2906
Rafael Espindola7ae65d82015-11-04 23:59:18 +00002907 getStreamer().emitValueToOffset(Offset, FillExpr);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002908 return false;
2909}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002910
Jim Grosbach4b905842013-09-20 23:08:21 +00002911/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002912/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00002913bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002914 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002915
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002916 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002917 int64_t Alignment;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002918 if (parseAbsoluteExpression(Alignment))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002919 return true;
2920
2921 SMLoc MaxBytesLoc;
2922 bool HasFillExpr = false;
2923 int64_t FillExpr = 0;
2924 int64_t MaxBytesToFill = 0;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002925 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00002926 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
2927 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002928
2929 // The fill expression can be omitted while specifying a maximum number of
2930 // alignment bytes, e.g:
2931 // .align 3,,4
Nirav Davea645433c2016-07-18 15:24:03 +00002932 if (getTok().isNot(AsmToken::Comma)) {
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002933 HasFillExpr = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002934 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002935 return true;
2936 }
2937
Nirav Davea645433c2016-07-18 15:24:03 +00002938 if (getTok().isNot(AsmToken::EndOfStatement)) {
2939 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
2940 getTokenLoc(MaxBytesLoc) || parseAbsoluteExpression(MaxBytesToFill))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002941 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002942 }
2943 }
2944
Nirav Davea645433c2016-07-18 15:24:03 +00002945 if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
2946 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002947
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002948 if (!HasFillExpr)
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002949 FillExpr = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002950
2951 // Compute alignment in bytes.
2952 if (IsPow2) {
2953 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002954 if (Alignment >= 32) {
2955 Error(AlignmentLoc, "invalid alignment value");
2956 Alignment = 31;
2957 }
2958
Benjamin Kramer63951ad2009-09-06 09:35:10 +00002959 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00002960 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00002961 // Reject alignments that aren't either a power of two or zero,
2962 // for gas compatibility. Alignment of zero is silently rounded
2963 // up to one.
2964 if (Alignment == 0)
2965 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00002966 if (!isPowerOf2_64(Alignment))
2967 Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002968 }
2969
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002970 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002971 if (MaxBytesLoc.isValid()) {
2972 if (MaxBytesToFill < 1) {
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002973 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00002974 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00002975 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002976 }
2977
2978 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00002979 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00002980 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002981 MaxBytesToFill = 0;
2982 }
2983 }
2984
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002985 // Check whether we should use optimal code alignment for this .align
2986 // directive.
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00002987 const MCSection *Section = getStreamer().getCurrentSection().first;
2988 assert(Section && "must have section to emit alignment");
2989 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002990 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2991 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002992 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002993 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00002994 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00002995 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2996 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002997 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002998
2999 return false;
3000}
3001
Jim Grosbach4b905842013-09-20 23:08:21 +00003002/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00003003/// ::= .file [number] filename
3004/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00003005bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003006 // FIXME: I'm not sure what this is.
3007 int64_t FileNumber = -1;
3008 SMLoc FileNumberLoc = getLexer().getLoc();
3009 if (getLexer().is(AsmToken::Integer)) {
3010 FileNumber = getTok().getIntVal();
3011 Lex();
3012
3013 if (FileNumber < 1)
3014 return TokError("file number less than one");
3015 }
3016
Nirav Davea645433c2016-07-18 15:24:03 +00003017 std::string Path = getTok().getString();
Eli Bendersky17233942013-01-15 22:59:42 +00003018
3019 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003020 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003021 if (check(getTok().isNot(AsmToken::String),
3022 "unexpected token in '.file' directive") ||
3023 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003024 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003025
3026 StringRef Directory;
3027 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003028 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003029 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003030 if (check(FileNumber == -1,
3031 "explicit path specified, but no file number") ||
3032 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003033 return true;
3034 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003035 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003036 } else {
3037 Filename = Path;
3038 }
3039
Nirav Davea645433c2016-07-18 15:24:03 +00003040 if (parseToken(AsmToken::EndOfStatement,
3041 "unexpected token in '.file' directive"))
3042 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003043
3044 if (FileNumber == -1)
3045 getStreamer().EmitFileDirective(Filename);
3046 else {
David Blaikie22748082016-05-26 00:22:26 +00003047 // If there is -g option as well as debug info from directive file,
3048 // we turn off -g option, directly use the existing debug info instead.
David Blaikiedc3f01e2015-03-09 01:57:13 +00003049 if (getContext().getGenDwarfForAssembly())
David Blaikie22748082016-05-26 00:22:26 +00003050 getContext().setGenDwarfForAssembly(false);
3051 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
David Blaikiec714ef42014-03-17 01:52:11 +00003052 0)
Eli Bendersky17233942013-01-15 22:59:42 +00003053 Error(FileNumberLoc, "file number already allocated");
3054 }
3055
3056 return false;
3057}
3058
Jim Grosbach4b905842013-09-20 23:08:21 +00003059/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003060/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003061bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003062 int64_t LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003063 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003064 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3065 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003066 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003067 // FIXME: Do something with the .line.
3068 }
Nirav Davea645433c2016-07-18 15:24:03 +00003069 if (parseToken(AsmToken::EndOfStatement,
3070 "unexpected token in '.line' directive"))
3071 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003072
3073 return false;
3074}
3075
Jim Grosbach4b905842013-09-20 23:08:21 +00003076/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003077/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3078/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3079/// The first number is a file number, must have been previously assigned with
3080/// a .file directive, the second number is the line number and optionally the
3081/// third number is a column position (zero if not specified). The remaining
3082/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003083bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003084 int64_t FileNumber = 0, LineNumber = 0;
3085 SMLoc Loc = getTok().getLoc();
3086 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3087 check(FileNumber < 1, Loc,
3088 "file number less than one in '.loc' directive") ||
3089 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3090 "unassigned file number in '.loc' directive"))
3091 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003092
Nirav Davea645433c2016-07-18 15:24:03 +00003093 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003094 if (getLexer().is(AsmToken::Integer)) {
3095 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003096 if (LineNumber < 0)
3097 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003098 Lex();
3099 }
3100
3101 int64_t ColumnPos = 0;
3102 if (getLexer().is(AsmToken::Integer)) {
3103 ColumnPos = getTok().getIntVal();
3104 if (ColumnPos < 0)
3105 return TokError("column position less than zero in '.loc' directive");
3106 Lex();
3107 }
3108
3109 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3110 unsigned Isa = 0;
3111 int64_t Discriminator = 0;
3112 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3113 for (;;) {
3114 if (getLexer().is(AsmToken::EndOfStatement))
3115 break;
3116
3117 StringRef Name;
3118 SMLoc Loc = getTok().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003119 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003120 return TokError("unexpected token in '.loc' directive");
3121
3122 if (Name == "basic_block")
3123 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3124 else if (Name == "prologue_end")
3125 Flags |= DWARF2_FLAG_PROLOGUE_END;
3126 else if (Name == "epilogue_begin")
3127 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3128 else if (Name == "is_stmt") {
3129 Loc = getTok().getLoc();
3130 const MCExpr *Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003131 if (parseExpression(Value))
Eli Bendersky17233942013-01-15 22:59:42 +00003132 return true;
3133 // The expression must be the constant 0 or 1.
3134 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3135 int Value = MCE->getValue();
3136 if (Value == 0)
3137 Flags &= ~DWARF2_FLAG_IS_STMT;
3138 else if (Value == 1)
3139 Flags |= DWARF2_FLAG_IS_STMT;
3140 else
3141 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003142 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003143 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3144 }
Craig Topperf15655b2013-04-22 04:22:40 +00003145 } else if (Name == "isa") {
Eli Bendersky17233942013-01-15 22:59:42 +00003146 Loc = getTok().getLoc();
3147 const MCExpr *Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003148 if (parseExpression(Value))
Eli Bendersky17233942013-01-15 22:59:42 +00003149 return true;
3150 // The expression must be a constant greater or equal to 0.
3151 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3152 int Value = MCE->getValue();
3153 if (Value < 0)
3154 return Error(Loc, "isa number less than zero");
3155 Isa = Value;
Craig Topperf15655b2013-04-22 04:22:40 +00003156 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003157 return Error(Loc, "isa number not a constant value");
3158 }
Craig Topperf15655b2013-04-22 04:22:40 +00003159 } else if (Name == "discriminator") {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003160 if (parseAbsoluteExpression(Discriminator))
Eli Bendersky17233942013-01-15 22:59:42 +00003161 return true;
Craig Topperf15655b2013-04-22 04:22:40 +00003162 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003163 return Error(Loc, "unknown sub-directive in '.loc' directive");
3164 }
3165
3166 if (getLexer().is(AsmToken::EndOfStatement))
3167 break;
3168 }
3169 }
Nirav Davea645433c2016-07-18 15:24:03 +00003170 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003171
3172 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3173 Isa, Discriminator, StringRef());
3174
3175 return false;
3176}
3177
Jim Grosbach4b905842013-09-20 23:08:21 +00003178/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003179/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003180bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003181 return TokError("unsupported directive '.stabs'");
3182}
3183
Reid Kleckner2214ed82016-01-29 00:49:42 +00003184/// parseDirectiveCVFile
3185/// ::= .cv_file number filename
3186bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003187 SMLoc FileNumberLoc = getTok().getLoc();
3188 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003189 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00003190
3191 if (parseIntToken(FileNumber,
3192 "expected file number in '.cv_file' directive") ||
3193 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3194 check(getTok().isNot(AsmToken::String),
3195 "unexpected token in '.cv_file' directive") ||
3196 // Usually directory and filename are together, otherwise just
3197 // directory. Allow the strings to have escaped octal character sequence.
3198 parseEscapedString(Filename) ||
3199 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00003200 "unexpected token in '.cv_file' directive"))
3201 return true;
3202
3203 if (getStreamer().EmitCVFileDirective(FileNumber, Filename) == 0)
3204 Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003205
3206 return false;
3207}
3208
3209/// parseDirectiveCVLoc
3210/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3211/// [is_stmt VALUE]
3212/// The first number is a file number, must have been previously assigned with
3213/// a .file directive, the second number is the line number and optionally the
3214/// third number is a column position (zero if not specified). The remaining
3215/// optional items are .loc sub-directives.
3216bool AsmParser::parseDirectiveCVLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003217 SMLoc Loc;
3218 int64_t FunctionId, FileNumber;
3219 if (getTokenLoc(Loc) ||
3220 parseIntToken(FunctionId, "unexpected token in '.cv_loc' directive") ||
3221 check(FunctionId < 0, Loc,
3222 "function id less than zero in '.cv_loc' directive") ||
3223 getTokenLoc(Loc) ||
3224 parseIntToken(FileNumber, "expected integer in '.cv_loc' directive") ||
3225 check(FileNumber < 1, Loc,
3226 "file number less than one in '.cv_loc' directive") ||
3227 check(!getContext().isValidCVFileNumber(FileNumber), Loc,
3228 "unassigned file number in '.cv_loc' directive"))
3229 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003230
3231 int64_t LineNumber = 0;
3232 if (getLexer().is(AsmToken::Integer)) {
3233 LineNumber = getTok().getIntVal();
3234 if (LineNumber < 0)
3235 return TokError("line number less than zero in '.cv_loc' directive");
3236 Lex();
3237 }
3238
3239 int64_t ColumnPos = 0;
3240 if (getLexer().is(AsmToken::Integer)) {
3241 ColumnPos = getTok().getIntVal();
3242 if (ColumnPos < 0)
3243 return TokError("column position less than zero in '.cv_loc' directive");
3244 Lex();
3245 }
3246
3247 bool PrologueEnd = false;
3248 uint64_t IsStmt = 0;
3249 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3250 StringRef Name;
3251 SMLoc Loc = getTok().getLoc();
3252 if (parseIdentifier(Name))
3253 return TokError("unexpected token in '.cv_loc' directive");
3254
3255 if (Name == "prologue_end")
3256 PrologueEnd = true;
3257 else if (Name == "is_stmt") {
3258 Loc = getTok().getLoc();
3259 const MCExpr *Value;
3260 if (parseExpression(Value))
3261 return true;
3262 // The expression must be the constant 0 or 1.
3263 IsStmt = ~0ULL;
3264 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3265 IsStmt = MCE->getValue();
3266
3267 if (IsStmt > 1)
3268 return Error(Loc, "is_stmt value not 0 or 1");
3269 } else {
3270 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3271 }
3272 }
Nirav Davea645433c2016-07-18 15:24:03 +00003273 Lex();
Reid Kleckner2214ed82016-01-29 00:49:42 +00003274
3275 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
3276 ColumnPos, PrologueEnd, IsStmt, StringRef());
3277 return false;
3278}
3279
3280/// parseDirectiveCVLinetable
3281/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3282bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003283 int64_t FunctionId;
3284 StringRef FnStartName, FnEndName;
3285 SMLoc Loc = getTok().getLoc();
3286 if (parseIntToken(FunctionId,
3287 "expected Integer in '.cv_linetable' directive") ||
3288 check(FunctionId < 0, Loc,
3289 "function id less than zero in '.cv_linetable' directive") ||
3290 parseToken(AsmToken::Comma,
3291 "unexpected token in '.cv_linetable' directive") ||
3292 getTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3293 "expected identifier in directive") ||
3294 parseToken(AsmToken::Comma,
3295 "unexpected token in '.cv_linetable' directive") ||
3296 getTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3297 "expected identifier in directive"))
3298 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003299
3300 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3301 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3302
3303 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3304 return false;
3305}
3306
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003307/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003308/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003309/// ("contains" SecondaryFunctionId+)?
3310bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003311 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3312 StringRef FnStartName, FnEndName;
3313 SMLoc Loc = getTok().getLoc();
3314 if (parseIntToken(
3315 PrimaryFunctionId,
3316 "expected PrimaryFunctionId in '.cv_inline_linetable' directive") ||
3317 check(PrimaryFunctionId < 0, Loc,
3318 "function id less than zero in '.cv_inline_linetable' directive") ||
3319 getTokenLoc(Loc) ||
3320 parseIntToken(
3321 SourceFileId,
3322 "expected SourceField in '.cv_inline_linetable' directive") ||
3323 check(SourceFileId <= 0, Loc,
3324 "File id less than zero in '.cv_inline_linetable' directive") ||
3325 getTokenLoc(Loc) ||
3326 parseIntToken(
3327 SourceLineNum,
3328 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3329 check(SourceLineNum < 0, Loc,
3330 "Line number less than zero in '.cv_inline_linetable' directive") ||
3331 getTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3332 "expected identifier in directive") ||
3333 getTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3334 "expected identifier in directive"))
3335 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003336
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003337 SmallVector<unsigned, 8> SecondaryFunctionIds;
3338 if (getLexer().is(AsmToken::Identifier)) {
3339 if (getTok().getIdentifier() != "contains")
3340 return TokError(
3341 "unexpected identifier in '.cv_inline_linetable' directive");
3342 Lex();
3343
3344 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3345 int64_t SecondaryFunctionId = getTok().getIntVal();
3346 if (SecondaryFunctionId < 0)
3347 return TokError(
3348 "function id less than zero in '.cv_inline_linetable' directive");
3349 Lex();
3350
3351 SecondaryFunctionIds.push_back(SecondaryFunctionId);
3352 }
3353 }
3354
Nirav Davea645433c2016-07-18 15:24:03 +00003355 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3356 return true;
3357
3358 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3359 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003360 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3361 SourceLineNum, FnStartSym,
David Majnemerc9911f22016-02-02 19:22:34 +00003362 FnEndSym, SecondaryFunctionIds);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003363 return false;
3364}
3365
David Majnemer408b5e62016-02-05 01:55:49 +00003366/// parseDirectiveCVDefRange
3367/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3368bool AsmParser::parseDirectiveCVDefRange() {
3369 SMLoc Loc;
3370 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3371 while (getLexer().is(AsmToken::Identifier)) {
3372 Loc = getLexer().getLoc();
3373 StringRef GapStartName;
3374 if (parseIdentifier(GapStartName))
3375 return Error(Loc, "expected identifier in directive");
3376 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3377
3378 Loc = getLexer().getLoc();
3379 StringRef GapEndName;
3380 if (parseIdentifier(GapEndName))
3381 return Error(Loc, "expected identifier in directive");
3382 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3383
3384 Ranges.push_back({GapStartSym, GapEndSym});
3385 }
3386
David Majnemer408b5e62016-02-05 01:55:49 +00003387 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003388 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3389 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003390 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003391
3392 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3393 return false;
3394}
3395
Reid Kleckner2214ed82016-01-29 00:49:42 +00003396/// parseDirectiveCVStringTable
3397/// ::= .cv_stringtable
3398bool AsmParser::parseDirectiveCVStringTable() {
3399 getStreamer().EmitCVStringTableDirective();
3400 return false;
3401}
3402
3403/// parseDirectiveCVFileChecksums
3404/// ::= .cv_filechecksums
3405bool AsmParser::parseDirectiveCVFileChecksums() {
3406 getStreamer().EmitCVFileChecksumsDirective();
3407 return false;
3408}
3409
Jim Grosbach4b905842013-09-20 23:08:21 +00003410/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003411/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003412bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003413 StringRef Name;
3414 bool EH = false;
3415 bool Debug = false;
3416
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003417 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003418 return TokError("Expected an identifier");
3419
3420 if (Name == ".eh_frame")
3421 EH = true;
3422 else if (Name == ".debug_frame")
3423 Debug = true;
3424
3425 if (getLexer().is(AsmToken::Comma)) {
3426 Lex();
3427
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003428 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003429 return TokError("Expected an identifier");
3430
3431 if (Name == ".eh_frame")
3432 EH = true;
3433 else if (Name == ".debug_frame")
3434 Debug = true;
3435 }
3436
3437 getStreamer().EmitCFISections(EH, Debug);
3438 return false;
3439}
3440
Jim Grosbach4b905842013-09-20 23:08:21 +00003441/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003442/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003443bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003444 StringRef Simple;
3445 if (getLexer().isNot(AsmToken::EndOfStatement))
3446 if (parseIdentifier(Simple) || Simple != "simple")
3447 return TokError("unexpected token in .cfi_startproc directive");
3448
Nirav Davea645433c2016-07-18 15:24:03 +00003449 if (parseToken(AsmToken::EndOfStatement, "Expected end of statement"))
3450 return true;
3451
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003452 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003453 return false;
3454}
3455
Jim Grosbach4b905842013-09-20 23:08:21 +00003456/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003457/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003458bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003459 getStreamer().EmitCFIEndProc();
3460 return false;
3461}
3462
Jim Grosbach4b905842013-09-20 23:08:21 +00003463/// \brief parse register name or number.
3464bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003465 SMLoc DirectiveLoc) {
3466 unsigned RegNo;
3467
3468 if (getLexer().isNot(AsmToken::Integer)) {
3469 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3470 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003471 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003472 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003473 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003474
3475 return false;
3476}
3477
Jim Grosbach4b905842013-09-20 23:08:21 +00003478/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003479/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003480bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003481 int64_t Register = 0, Offset = 0;
3482 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3483 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3484 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003485 return true;
3486
3487 getStreamer().EmitCFIDefCfa(Register, Offset);
3488 return false;
3489}
3490
Jim Grosbach4b905842013-09-20 23:08:21 +00003491/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003492/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003493bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003494 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003495 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003496 return true;
3497
3498 getStreamer().EmitCFIDefCfaOffset(Offset);
3499 return false;
3500}
3501
Jim Grosbach4b905842013-09-20 23:08:21 +00003502/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003503/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003504bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003505 int64_t Register1 = 0, Register2 = 0;
3506 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3507 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3508 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003509 return true;
3510
3511 getStreamer().EmitCFIRegister(Register1, Register2);
3512 return false;
3513}
3514
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003515/// parseDirectiveCFIWindowSave
3516/// ::= .cfi_window_save
3517bool AsmParser::parseDirectiveCFIWindowSave() {
3518 getStreamer().EmitCFIWindowSave();
3519 return false;
3520}
3521
Jim Grosbach4b905842013-09-20 23:08:21 +00003522/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003523/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003524bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003525 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003526 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003527 return true;
3528
3529 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3530 return false;
3531}
3532
Jim Grosbach4b905842013-09-20 23:08:21 +00003533/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003534/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003535bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003536 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003537 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003538 return true;
3539
3540 getStreamer().EmitCFIDefCfaRegister(Register);
3541 return false;
3542}
3543
Jim Grosbach4b905842013-09-20 23:08:21 +00003544/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003545/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003546bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003547 int64_t Register = 0;
3548 int64_t Offset = 0;
3549
Nirav Davea645433c2016-07-18 15:24:03 +00003550 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3551 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3552 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003553 return true;
3554
3555 getStreamer().EmitCFIOffset(Register, Offset);
3556 return false;
3557}
3558
Jim Grosbach4b905842013-09-20 23:08:21 +00003559/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003560/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003561bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003562 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003563
Nirav Davea645433c2016-07-18 15:24:03 +00003564 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3565 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3566 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003567 return true;
3568
3569 getStreamer().EmitCFIRelOffset(Register, Offset);
3570 return false;
3571}
3572
3573static bool isValidEncoding(int64_t Encoding) {
3574 if (Encoding & ~0xff)
3575 return false;
3576
3577 if (Encoding == dwarf::DW_EH_PE_omit)
3578 return true;
3579
3580 const unsigned Format = Encoding & 0xf;
3581 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3582 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3583 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3584 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3585 return false;
3586
3587 const unsigned Application = Encoding & 0x70;
3588 if (Application != dwarf::DW_EH_PE_absptr &&
3589 Application != dwarf::DW_EH_PE_pcrel)
3590 return false;
3591
3592 return true;
3593}
3594
Jim Grosbach4b905842013-09-20 23:08:21 +00003595/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003596/// IsPersonality true for cfi_personality, false for cfi_lsda
3597/// ::= .cfi_personality encoding, [symbol_name]
3598/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003599bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003600 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003601 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003602 return true;
3603 if (Encoding == dwarf::DW_EH_PE_omit)
3604 return false;
3605
Eli Bendersky17233942013-01-15 22:59:42 +00003606 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00003607 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
3608 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3609 check(parseIdentifier(Name), "expected identifier in directive"))
3610 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003611
Jim Grosbach6f482002015-05-18 18:43:14 +00003612 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003613
3614 if (IsPersonality)
3615 getStreamer().EmitCFIPersonality(Sym, Encoding);
3616 else
3617 getStreamer().EmitCFILsda(Sym, Encoding);
3618 return false;
3619}
3620
Jim Grosbach4b905842013-09-20 23:08:21 +00003621/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00003622/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003623bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003624 getStreamer().EmitCFIRememberState();
3625 return false;
3626}
3627
Jim Grosbach4b905842013-09-20 23:08:21 +00003628/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00003629/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003630bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003631 getStreamer().EmitCFIRestoreState();
3632 return false;
3633}
3634
Jim Grosbach4b905842013-09-20 23:08:21 +00003635/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00003636/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00003637bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003638 int64_t Register = 0;
3639
Jim Grosbach4b905842013-09-20 23:08:21 +00003640 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003641 return true;
3642
3643 getStreamer().EmitCFISameValue(Register);
3644 return false;
3645}
3646
Jim Grosbach4b905842013-09-20 23:08:21 +00003647/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00003648/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00003649bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003650 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003651 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003652 return true;
3653
3654 getStreamer().EmitCFIRestore(Register);
3655 return false;
3656}
3657
Jim Grosbach4b905842013-09-20 23:08:21 +00003658/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00003659/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003660bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00003661 std::string Values;
3662 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003663 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003664 return true;
3665
3666 Values.push_back((uint8_t)CurrValue);
3667
3668 while (getLexer().is(AsmToken::Comma)) {
3669 Lex();
3670
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003671 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003672 return true;
3673
3674 Values.push_back((uint8_t)CurrValue);
3675 }
3676
3677 getStreamer().EmitCFIEscape(Values);
3678 return false;
3679}
3680
Jim Grosbach4b905842013-09-20 23:08:21 +00003681/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00003682/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00003683bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00003684 if (parseToken(AsmToken::EndOfStatement,
3685 "unexpected token in '.cfi_signal_frame'"))
3686 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003687
3688 getStreamer().EmitCFISignalFrame();
3689 return false;
3690}
3691
Jim Grosbach4b905842013-09-20 23:08:21 +00003692/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00003693/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00003694bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003695 int64_t Register = 0;
3696
Jim Grosbach4b905842013-09-20 23:08:21 +00003697 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003698 return true;
3699
3700 getStreamer().EmitCFIUndefined(Register);
3701 return false;
3702}
3703
Jim Grosbach4b905842013-09-20 23:08:21 +00003704/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00003705/// ::= .macros_on
3706/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00003707bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00003708 if (parseToken(AsmToken::EndOfStatement,
3709 "unexpected token in '" + Directive + "' directive"))
3710 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003711
Jim Grosbach4b905842013-09-20 23:08:21 +00003712 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00003713 return false;
3714}
3715
Jim Grosbach4b905842013-09-20 23:08:21 +00003716/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003717/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00003718bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003719 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003720 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003721 return TokError("expected identifier in '.macro' directive");
3722
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003723 if (getLexer().is(AsmToken::Comma))
3724 Lex();
3725
Eli Bendersky17233942013-01-15 22:59:42 +00003726 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00003727 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003728
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003729 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003730 return Error(Lexer.getLoc(),
3731 "Vararg parameter '" + Parameters.back().Name +
3732 "' should be last one in the list of parameters.");
3733
David Majnemer91fc4c22014-01-29 18:57:46 +00003734 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003735 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00003736 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003737
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003738 if (Lexer.is(AsmToken::Colon)) {
3739 Lex(); // consume ':'
3740
3741 SMLoc QualLoc;
3742 StringRef Qualifier;
3743
3744 QualLoc = Lexer.getLoc();
3745 if (parseIdentifier(Qualifier))
3746 return Error(QualLoc, "missing parameter qualifier for "
3747 "'" + Parameter.Name + "' in macro '" + Name + "'");
3748
3749 if (Qualifier == "req")
3750 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00003751 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003752 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003753 else
3754 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3755 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3756 }
3757
David Majnemer91fc4c22014-01-29 18:57:46 +00003758 if (getLexer().is(AsmToken::Equal)) {
3759 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003760
3761 SMLoc ParamLoc;
3762
3763 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003764 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00003765 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003766
3767 if (Parameter.Required)
3768 Warning(ParamLoc, "pointless default value for required parameter "
3769 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00003770 }
David Majnemer91fc4c22014-01-29 18:57:46 +00003771
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003772 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00003773
3774 if (getLexer().is(AsmToken::Comma))
3775 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003776 }
3777
Nirav Dave1180e6892016-06-02 17:15:05 +00003778 // Eat just the end of statement.
3779 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003780
Nirav Dave1180e6892016-06-02 17:15:05 +00003781 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00003782 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003783 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003784 // Lex the macro definition.
3785 for (;;) {
Nirav Dave1180e6892016-06-02 17:15:05 +00003786 // Ignore Lexing errors in macros.
3787 while (Lexer.is(AsmToken::Error)) {
3788 Lexer.Lex();
3789 }
3790
Eli Bendersky17233942013-01-15 22:59:42 +00003791 // Check whether we have reached the end of the file.
3792 if (getLexer().is(AsmToken::Eof))
3793 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3794
3795 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003796 if (getLexer().is(AsmToken::Identifier)) {
3797 if (getTok().getIdentifier() == ".endm" ||
3798 getTok().getIdentifier() == ".endmacro") {
3799 if (MacroDepth == 0) { // Outermost macro.
3800 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00003801 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003802 if (getLexer().isNot(AsmToken::EndOfStatement))
3803 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3804 "' directive");
3805 break;
3806 } else {
3807 // Otherwise we just found the end of an inner macro.
3808 --MacroDepth;
3809 }
3810 } else if (getTok().getIdentifier() == ".macro") {
3811 // We allow nested macros. Those aren't instantiated until the outermost
3812 // macro is expanded so just ignore them for now.
3813 ++MacroDepth;
3814 }
Eli Bendersky17233942013-01-15 22:59:42 +00003815 }
3816
3817 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003818 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00003819 }
3820
Jim Grosbach4b905842013-09-20 23:08:21 +00003821 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00003822 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3823 }
3824
3825 const char *BodyStart = StartToken.getLoc().getPointer();
3826 const char *BodyEnd = EndToken.getLoc().getPointer();
3827 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00003828 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003829 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00003830 return false;
3831}
3832
Jim Grosbach4b905842013-09-20 23:08:21 +00003833/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00003834///
3835/// With the support added for named parameters there may be code out there that
3836/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00003837/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00003838/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00003839/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00003840/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3841/// warning that the positional parameter found in body which have no effect.
3842/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00003843/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00003844/// intended or change the macro to use the named parameters. It is possible
3845/// this warning will trigger when the none of the named parameters are used
3846/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00003847void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00003848 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00003849 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00003850 // If this macro is not defined with named parameters the warning we are
3851 // checking for here doesn't apply.
3852 unsigned NParameters = Parameters.size();
3853 if (NParameters == 0)
3854 return;
3855
3856 bool NamedParametersFound = false;
3857 bool PositionalParametersFound = false;
3858
3859 // Look at the body of the macro for use of both the named parameters and what
3860 // are likely to be positional parameters. This is what expandMacro() is
3861 // doing when it finds the parameters in the body.
3862 while (!Body.empty()) {
3863 // Scan for the next possible parameter.
3864 std::size_t End = Body.size(), Pos = 0;
3865 for (; Pos != End; ++Pos) {
3866 // Check for a substitution or escape.
3867 // This macro is defined with parameters, look for \foo, \bar, etc.
3868 if (Body[Pos] == '\\' && Pos + 1 != End)
3869 break;
3870
3871 // This macro should have parameters, but look for $0, $1, ..., $n too.
3872 if (Body[Pos] != '$' || Pos + 1 == End)
3873 continue;
3874 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00003875 if (Next == '$' || Next == 'n' ||
3876 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00003877 break;
3878 }
3879
3880 // Check if we reached the end.
3881 if (Pos == End)
3882 break;
3883
3884 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00003885 switch (Body[Pos + 1]) {
3886 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00003887 case '$':
3888 break;
3889
Jim Grosbach4b905842013-09-20 23:08:21 +00003890 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00003891 case 'n':
3892 PositionalParametersFound = true;
3893 break;
3894
Jim Grosbach4b905842013-09-20 23:08:21 +00003895 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00003896 default: {
3897 PositionalParametersFound = true;
3898 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00003899 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00003900 }
3901 Pos += 2;
3902 } else {
3903 unsigned I = Pos + 1;
3904 while (isIdentifierChar(Body[I]) && I + 1 != End)
3905 ++I;
3906
Jim Grosbach4b905842013-09-20 23:08:21 +00003907 const char *Begin = Body.data() + Pos + 1;
3908 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00003909 unsigned Index = 0;
3910 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003911 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00003912 break;
3913
3914 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00003915 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3916 Pos += 3;
3917 else {
3918 Pos = I;
3919 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00003920 } else {
3921 NamedParametersFound = true;
3922 Pos += 1 + Argument.size();
3923 }
3924 }
3925 // Update the scan point.
3926 Body = Body.substr(Pos);
3927 }
3928
3929 if (!NamedParametersFound && PositionalParametersFound)
3930 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3931 "used in macro body, possible positional parameter "
3932 "found in body which will have no effect");
3933}
3934
Nico Weber155dccd12014-07-24 17:08:39 +00003935/// parseDirectiveExitMacro
3936/// ::= .exitm
3937bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00003938 if (parseToken(AsmToken::EndOfStatement,
3939 "unexpected token in '" + Directive + "' directive"))
3940 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00003941
3942 if (!isInsideMacroInstantiation())
3943 return TokError("unexpected '" + Directive + "' in file, "
3944 "no current macro definition");
3945
3946 // Exit all conditionals that are active in the current macro.
3947 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3948 TheCondState = TheCondStack.back();
3949 TheCondStack.pop_back();
3950 }
3951
3952 handleMacroExit();
3953 return false;
3954}
3955
Jim Grosbach4b905842013-09-20 23:08:21 +00003956/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00003957/// ::= .endm
3958/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00003959bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00003960 if (getLexer().isNot(AsmToken::EndOfStatement))
3961 return TokError("unexpected token in '" + Directive + "' directive");
3962
3963 // If we are inside a macro instantiation, terminate the current
3964 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00003965 if (isInsideMacroInstantiation()) {
3966 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00003967 return false;
3968 }
3969
3970 // Otherwise, this .endmacro is a stray entry in the file; well formed
3971 // .endmacro directives are handled during the macro definition parsing.
3972 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00003973 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00003974}
3975
Jim Grosbach4b905842013-09-20 23:08:21 +00003976/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00003977/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00003978bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003979 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00003980 SMLoc Loc;
3981 if (getTokenLoc(Loc) || check(parseIdentifier(Name), Loc,
3982 "expected identifier in '.purgem' directive") ||
3983 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00003984 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003985 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003986
Nirav Dave1ab71992016-07-18 19:35:21 +00003987 if (!lookupMacro(Name))
3988 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3989
Jim Grosbach4b905842013-09-20 23:08:21 +00003990 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003991 return false;
3992}
Eli Benderskyf483ff92012-12-20 19:05:53 +00003993
Jim Grosbach4b905842013-09-20 23:08:21 +00003994/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00003995/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003996bool AsmParser::parseDirectiveBundleAlignMode() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003997 checkForValidSection();
Eli Benderskyf483ff92012-12-20 19:05:53 +00003998
3999 // Expect a single argument: an expression that evaluates to a constant
4000 // in the inclusive range 0-30.
4001 SMLoc ExprLoc = getLexer().getLoc();
4002 int64_t AlignSizePow2;
Nirav Davea645433c2016-07-18 15:24:03 +00004003 if (parseAbsoluteExpression(AlignSizePow2) ||
4004 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4005 "in '.bundle_align_mode' "
4006 "directive") ||
4007 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4008 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004009 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004010
4011 // Because of AlignSizePow2's verified range we can safely truncate it to
4012 // unsigned.
4013 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4014 return false;
4015}
4016
Jim Grosbach4b905842013-09-20 23:08:21 +00004017/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004018/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004019bool AsmParser::parseDirectiveBundleLock() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004020 checkForValidSection();
Eli Bendersky802b6282013-01-07 21:51:08 +00004021 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004022
Eli Bendersky802b6282013-01-07 21:51:08 +00004023 if (getLexer().isNot(AsmToken::EndOfStatement)) {
4024 StringRef Option;
4025 SMLoc Loc = getTok().getLoc();
4026 const char *kInvalidOptionError =
Jim Grosbach4b905842013-09-20 23:08:21 +00004027 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004028
Nirav Davea645433c2016-07-18 15:24:03 +00004029 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4030 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
4031 check(getTok().isNot(AsmToken::EndOfStatement), Loc,
4032 "unexpected token after '.bundle_lock' directive option"))
4033 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004034 AlignToEnd = true;
4035 }
4036
Eli Benderskyf483ff92012-12-20 19:05:53 +00004037 Lex();
4038
Eli Bendersky802b6282013-01-07 21:51:08 +00004039 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004040 return false;
4041}
4042
Jim Grosbach4b905842013-09-20 23:08:21 +00004043/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004044/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004045bool AsmParser::parseDirectiveBundleUnlock() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004046 checkForValidSection();
Eli Benderskyf483ff92012-12-20 19:05:53 +00004047
Nirav Davea645433c2016-07-18 15:24:03 +00004048 if (parseToken(AsmToken::EndOfStatement,
4049 "unexpected token in '.bundle_unlock' directive"))
4050 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004051
4052 getStreamer().EmitBundleUnlock();
4053 return false;
4054}
4055
Jim Grosbach4b905842013-09-20 23:08:21 +00004056/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004057/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004058bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004059 checkForValidSection();
Eli Bendersky17233942013-01-15 22:59:42 +00004060
Petr Hosek67a94a72016-05-28 05:57:48 +00004061 SMLoc NumBytesLoc = Lexer.getLoc();
4062 const MCExpr *NumBytes;
4063 if (parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004064 return true;
4065
4066 int64_t FillExpr = 0;
4067 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Eli Bendersky17233942013-01-15 22:59:42 +00004068
Nirav Davea645433c2016-07-18 15:24:03 +00004069 if (parseToken(AsmToken::Comma,
4070 "unexpected token in '" + Twine(IDVal) + "' directive") ||
4071 parseAbsoluteExpression(FillExpr))
Eli Bendersky17233942013-01-15 22:59:42 +00004072 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004073 }
4074
Nirav Davea645433c2016-07-18 15:24:03 +00004075 if (parseToken(AsmToken::EndOfStatement,
4076 "unexpected token in '" + Twine(IDVal) + "' directive"))
4077 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004078
Eli Bendersky17233942013-01-15 22:59:42 +00004079 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004080 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004081
4082 return false;
4083}
4084
Jim Grosbach4b905842013-09-20 23:08:21 +00004085/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004086/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004087bool AsmParser::parseDirectiveLEB128(bool Signed) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004088 checkForValidSection();
Eli Bendersky17233942013-01-15 22:59:42 +00004089 const MCExpr *Value;
4090
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004091 for (;;) {
4092 if (parseExpression(Value))
4093 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004094
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004095 if (Signed)
4096 getStreamer().EmitSLEB128Value(Value);
4097 else
4098 getStreamer().EmitULEB128Value(Value);
Eli Bendersky17233942013-01-15 22:59:42 +00004099
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004100 if (getLexer().is(AsmToken::EndOfStatement))
4101 break;
4102
Nirav Davea645433c2016-07-18 15:24:03 +00004103 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
4104 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004105 }
Nirav Davea645433c2016-07-18 15:24:03 +00004106 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004107
4108 return false;
4109}
4110
Jim Grosbach4b905842013-09-20 23:08:21 +00004111/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004112/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004113bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004114 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbara5508c82009-06-30 00:33:19 +00004115 for (;;) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004116 StringRef Name;
Jim Grosbachebdf32f2011-09-15 17:56:49 +00004117 SMLoc Loc = getTok().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004118
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004119 if (parseIdentifier(Name))
Jim Grosbachebdf32f2011-09-15 17:56:49 +00004120 return Error(Loc, "expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004121
Jim Grosbach6f482002015-05-18 18:43:14 +00004122 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbara5508c82009-06-30 00:33:19 +00004123
Jim Grosbachebdf32f2011-09-15 17:56:49 +00004124 // Assembler local symbols don't make any sense here. Complain loudly.
4125 if (Sym->isTemporary())
4126 return Error(Loc, "non-local symbol required in directive");
4127
Saleem Abdulrasool4208b612013-08-09 01:52:03 +00004128 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4129 return Error(Loc, "unable to emit symbol attribute");
Daniel Dunbara5508c82009-06-30 00:33:19 +00004130
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004131 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara5508c82009-06-30 00:33:19 +00004132 break;
4133
Nirav Davea645433c2016-07-18 15:24:03 +00004134 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
4135 return true;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004136 }
4137 }
4138
Sean Callanan686ed8d2010-01-19 20:22:31 +00004139 Lex();
Jan Wen Voungc7682872010-09-30 01:09:20 +00004140 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004141}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004142
Jim Grosbach4b905842013-09-20 23:08:21 +00004143/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004144/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004145bool AsmParser::parseDirectiveComm(bool IsLocal) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004146 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00004147
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004148 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004149 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004150 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004151 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004152
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004153 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004154 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004155
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004156 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004157 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004158 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004159
4160 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004161 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004162 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004163 return true;
4164
4165 int64_t Pow2Alignment = 0;
4166 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004167 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004168 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004169 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004170 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004171 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004172
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004173 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4174 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004175 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4176
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004177 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004178 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4179 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004180 if (!isPowerOf2_64(Pow2Alignment))
4181 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4182 Pow2Alignment = Log2_64(Pow2Alignment);
4183 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004184 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004185
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004186 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner28ad7542009-07-09 17:25:12 +00004187 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004188
Sean Callanan686ed8d2010-01-19 20:22:31 +00004189 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004190
Chris Lattner28ad7542009-07-09 17:25:12 +00004191 // NOTE: a size of zero for a .comm should create a undefined symbol
4192 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004193 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004194 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004195 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004196
Eric Christopherbc818852010-05-14 01:38:54 +00004197 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004198 // may internally end up wanting an alignment in bytes.
4199 // FIXME: Diagnose overflow.
4200 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004201 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004202 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004203
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004204 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004205 return Error(IDLoc, "invalid symbol redefinition");
4206
Chris Lattner28ad7542009-07-09 17:25:12 +00004207 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004208 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004209 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004210 return false;
4211 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004212
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004213 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004214 return false;
4215}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004216
Jim Grosbach4b905842013-09-20 23:08:21 +00004217/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004218/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004219bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004220 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004221 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004222
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004223 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004224 if (parseToken(AsmToken::EndOfStatement,
4225 "unexpected token in '.abort' directive"))
4226 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004227
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004228 if (Str.empty())
4229 Error(Loc, ".abort detected. Assembly stopping.");
4230 else
4231 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004232 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004233
4234 return false;
4235}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004236
Jim Grosbach4b905842013-09-20 23:08:21 +00004237/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004238/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004239bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004240 // Allow the strings to have escaped octal character sequence.
4241 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004242 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004243
Nirav Davea645433c2016-07-18 15:24:03 +00004244 if (check(getTok().isNot(AsmToken::String),
4245 "expected string in '.include' directive") ||
4246 parseEscapedString(Filename) ||
4247 check(getTok().isNot(AsmToken::EndOfStatement),
4248 "unexpected token in '.include' directive") ||
4249 // Attempt to switch the lexer to the included file before consuming the
4250 // end of statement to avoid losing it when we switch.
4251 check(enterIncludeFile(Filename), IncludeLoc,
4252 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004253 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004254
4255 return false;
4256}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004257
Jim Grosbach4b905842013-09-20 23:08:21 +00004258/// parseDirectiveIncbin
Kevin Enderby109f25c2011-12-14 21:47:48 +00004259/// ::= .incbin "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004260bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004261 // Allow the strings to have escaped octal character sequence.
4262 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004263 SMLoc IncbinLoc = getTok().getLoc();
4264 if (check(getTok().isNot(AsmToken::String),
4265 "expected string in '.incbin' directive") ||
4266 parseEscapedString(Filename) ||
4267 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004268 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004269 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004270
4271 // Attempt to process the included file.
4272 if (processIncbinFile(Filename))
4273 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004274 return false;
4275}
4276
Jim Grosbach4b905842013-09-20 23:08:21 +00004277/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004278/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4279bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004280 TheCondStack.push_back(TheCondState);
4281 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004282 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004283 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004284 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004285 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004286 if (parseAbsoluteExpression(ExprValue) ||
4287 parseToken(AsmToken::EndOfStatement,
4288 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004289 return true;
4290
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004291 switch (DirKind) {
4292 default:
4293 llvm_unreachable("unsupported directive");
4294 case DK_IF:
4295 case DK_IFNE:
4296 break;
4297 case DK_IFEQ:
4298 ExprValue = ExprValue == 0;
4299 break;
4300 case DK_IFGE:
4301 ExprValue = ExprValue >= 0;
4302 break;
4303 case DK_IFGT:
4304 ExprValue = ExprValue > 0;
4305 break;
4306 case DK_IFLE:
4307 ExprValue = ExprValue <= 0;
4308 break;
4309 case DK_IFLT:
4310 ExprValue = ExprValue < 0;
4311 break;
4312 }
4313
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004314 TheCondState.CondMet = ExprValue;
4315 TheCondState.Ignore = !TheCondState.CondMet;
4316 }
4317
4318 return false;
4319}
4320
Jim Grosbach4b905842013-09-20 23:08:21 +00004321/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004322/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004323bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004324 TheCondStack.push_back(TheCondState);
4325 TheCondState.TheCond = AsmCond::IfCond;
4326
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004327 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004328 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004329 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004330 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004331
Nirav Davea645433c2016-07-18 15:24:03 +00004332 if (parseToken(AsmToken::EndOfStatement,
4333 "unexpected token in '.ifb' directive"))
4334 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004335
4336 TheCondState.CondMet = ExpectBlank == Str.empty();
4337 TheCondState.Ignore = !TheCondState.CondMet;
4338 }
4339
4340 return false;
4341}
4342
Jim Grosbach4b905842013-09-20 23:08:21 +00004343/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004344/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004345/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004346bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004347 TheCondStack.push_back(TheCondState);
4348 TheCondState.TheCond = AsmCond::IfCond;
4349
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004350 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004351 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004352 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004353 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004354
Nirav Davea645433c2016-07-18 15:24:03 +00004355 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4356 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004357
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004358 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004359
Nirav Davea645433c2016-07-18 15:24:03 +00004360 if (parseToken(AsmToken::EndOfStatement,
4361 "unexpected token in '.ifc' directive"))
4362 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004363
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004364 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004365 TheCondState.Ignore = !TheCondState.CondMet;
4366 }
4367
4368 return false;
4369}
4370
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004371/// parseDirectiveIfeqs
4372/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004373bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004374 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004375 if (ExpectEqual)
4376 TokError("expected string parameter for '.ifeqs' directive");
4377 else
4378 TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004379 eatToEndOfStatement();
4380 return true;
4381 }
4382
4383 StringRef String1 = getTok().getStringContents();
4384 Lex();
4385
4386 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004387 if (ExpectEqual)
4388 TokError("expected comma after first string for '.ifeqs' directive");
4389 else
4390 TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004391 eatToEndOfStatement();
4392 return true;
4393 }
4394
4395 Lex();
4396
4397 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004398 if (ExpectEqual)
4399 TokError("expected string parameter for '.ifeqs' directive");
4400 else
4401 TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004402 eatToEndOfStatement();
4403 return true;
4404 }
4405
4406 StringRef String2 = getTok().getStringContents();
4407 Lex();
4408
4409 TheCondStack.push_back(TheCondState);
4410 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004411 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004412 TheCondState.Ignore = !TheCondState.CondMet;
4413
4414 return false;
4415}
4416
Jim Grosbach4b905842013-09-20 23:08:21 +00004417/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004418/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004419bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004420 StringRef Name;
4421 TheCondStack.push_back(TheCondState);
4422 TheCondState.TheCond = AsmCond::IfCond;
4423
4424 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004425 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004426 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00004427 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4428 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4429 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004430
Jim Grosbach6f482002015-05-18 18:43:14 +00004431 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004432
4433 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004434 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004435 else
Craig Topper353eda42014-04-24 06:44:33 +00004436 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004437 TheCondState.Ignore = !TheCondState.CondMet;
4438 }
4439
4440 return false;
4441}
4442
Jim Grosbach4b905842013-09-20 23:08:21 +00004443/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004444/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004445bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004446 if (TheCondState.TheCond != AsmCond::IfCond &&
4447 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper2172ad62013-04-22 04:24:02 +00004448 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4449 " an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004450 TheCondState.TheCond = AsmCond::ElseIfCond;
4451
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004452 bool LastIgnoreState = false;
4453 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004454 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004455 if (LastIgnoreState || TheCondState.CondMet) {
4456 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004457 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004458 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004459 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004460 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004461 return true;
4462
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004463 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004464 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004465
Sean Callanan686ed8d2010-01-19 20:22:31 +00004466 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004467 TheCondState.CondMet = ExprValue;
4468 TheCondState.Ignore = !TheCondState.CondMet;
4469 }
4470
4471 return false;
4472}
4473
Jim Grosbach4b905842013-09-20 23:08:21 +00004474/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004475/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004476bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004477 if (parseToken(AsmToken::EndOfStatement,
4478 "unexpected token in '.else' directive"))
4479 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004480
4481 if (TheCondState.TheCond != AsmCond::IfCond &&
4482 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper2172ad62013-04-22 04:24:02 +00004483 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4484 ".elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004485 TheCondState.TheCond = AsmCond::ElseCond;
4486 bool LastIgnoreState = false;
4487 if (!TheCondStack.empty())
4488 LastIgnoreState = TheCondStack.back().Ignore;
4489 if (LastIgnoreState || TheCondState.CondMet)
4490 TheCondState.Ignore = true;
4491 else
4492 TheCondState.Ignore = false;
4493
4494 return false;
4495}
4496
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004497/// parseDirectiveEnd
4498/// ::= .end
4499bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004500 if (parseToken(AsmToken::EndOfStatement,
4501 "unexpected token in '.end' directive"))
4502 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004503
4504 while (Lexer.isNot(AsmToken::Eof))
4505 Lex();
4506
4507 return false;
4508}
4509
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004510/// parseDirectiveError
4511/// ::= .err
4512/// ::= .error [string]
4513bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4514 if (!TheCondStack.empty()) {
4515 if (TheCondStack.back().Ignore) {
4516 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004517 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004518 }
4519 }
4520
4521 if (!WithMessage)
4522 return Error(L, ".err encountered");
4523
4524 StringRef Message = ".error directive invoked in source file";
4525 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4526 if (Lexer.isNot(AsmToken::String)) {
4527 TokError(".error argument must be a string");
4528 eatToEndOfStatement();
4529 return true;
4530 }
4531
4532 Message = getTok().getStringContents();
4533 Lex();
4534 }
4535
4536 Error(L, Message);
4537 return true;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004538}
4539
Nico Weber404012b2014-07-24 16:26:06 +00004540/// parseDirectiveWarning
4541/// ::= .warning [string]
4542bool AsmParser::parseDirectiveWarning(SMLoc L) {
4543 if (!TheCondStack.empty()) {
4544 if (TheCondStack.back().Ignore) {
4545 eatToEndOfStatement();
4546 return false;
4547 }
4548 }
4549
4550 StringRef Message = ".warning directive invoked in source file";
4551 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4552 if (Lexer.isNot(AsmToken::String)) {
4553 TokError(".warning argument must be a string");
4554 eatToEndOfStatement();
4555 return true;
4556 }
4557
4558 Message = getTok().getStringContents();
4559 Lex();
4560 }
4561
4562 Warning(L, Message);
4563 return false;
4564}
4565
Jim Grosbach4b905842013-09-20 23:08:21 +00004566/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004567/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00004568bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004569 if (parseToken(AsmToken::EndOfStatement,
4570 "unexpected token in '.endif' directive"))
4571 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004572
Jim Grosbach4b905842013-09-20 23:08:21 +00004573 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004574 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4575 ".else");
4576 if (!TheCondStack.empty()) {
4577 TheCondState = TheCondStack.back();
4578 TheCondStack.pop_back();
4579 }
4580
4581 return false;
4582}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00004583
Eli Bendersky17233942013-01-15 22:59:42 +00004584void AsmParser::initializeDirectiveKindMap() {
4585 DirectiveKindMap[".set"] = DK_SET;
4586 DirectiveKindMap[".equ"] = DK_EQU;
4587 DirectiveKindMap[".equiv"] = DK_EQUIV;
4588 DirectiveKindMap[".ascii"] = DK_ASCII;
4589 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4590 DirectiveKindMap[".string"] = DK_STRING;
4591 DirectiveKindMap[".byte"] = DK_BYTE;
4592 DirectiveKindMap[".short"] = DK_SHORT;
4593 DirectiveKindMap[".value"] = DK_VALUE;
4594 DirectiveKindMap[".2byte"] = DK_2BYTE;
4595 DirectiveKindMap[".long"] = DK_LONG;
4596 DirectiveKindMap[".int"] = DK_INT;
4597 DirectiveKindMap[".4byte"] = DK_4BYTE;
4598 DirectiveKindMap[".quad"] = DK_QUAD;
4599 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00004600 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00004601 DirectiveKindMap[".single"] = DK_SINGLE;
4602 DirectiveKindMap[".float"] = DK_FLOAT;
4603 DirectiveKindMap[".double"] = DK_DOUBLE;
4604 DirectiveKindMap[".align"] = DK_ALIGN;
4605 DirectiveKindMap[".align32"] = DK_ALIGN32;
4606 DirectiveKindMap[".balign"] = DK_BALIGN;
4607 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4608 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4609 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4610 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4611 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4612 DirectiveKindMap[".org"] = DK_ORG;
4613 DirectiveKindMap[".fill"] = DK_FILL;
4614 DirectiveKindMap[".zero"] = DK_ZERO;
4615 DirectiveKindMap[".extern"] = DK_EXTERN;
4616 DirectiveKindMap[".globl"] = DK_GLOBL;
4617 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00004618 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4619 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4620 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4621 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4622 DirectiveKindMap[".reference"] = DK_REFERENCE;
4623 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4624 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4625 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4626 DirectiveKindMap[".comm"] = DK_COMM;
4627 DirectiveKindMap[".common"] = DK_COMMON;
4628 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4629 DirectiveKindMap[".abort"] = DK_ABORT;
4630 DirectiveKindMap[".include"] = DK_INCLUDE;
4631 DirectiveKindMap[".incbin"] = DK_INCBIN;
4632 DirectiveKindMap[".code16"] = DK_CODE16;
4633 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4634 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004635 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00004636 DirectiveKindMap[".irp"] = DK_IRP;
4637 DirectiveKindMap[".irpc"] = DK_IRPC;
4638 DirectiveKindMap[".endr"] = DK_ENDR;
4639 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4640 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4641 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4642 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004643 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4644 DirectiveKindMap[".ifge"] = DK_IFGE;
4645 DirectiveKindMap[".ifgt"] = DK_IFGT;
4646 DirectiveKindMap[".ifle"] = DK_IFLE;
4647 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00004648 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00004649 DirectiveKindMap[".ifb"] = DK_IFB;
4650 DirectiveKindMap[".ifnb"] = DK_IFNB;
4651 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004652 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00004653 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00004654 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00004655 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4656 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4657 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4658 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4659 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004660 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00004661 DirectiveKindMap[".endif"] = DK_ENDIF;
4662 DirectiveKindMap[".skip"] = DK_SKIP;
4663 DirectiveKindMap[".space"] = DK_SPACE;
4664 DirectiveKindMap[".file"] = DK_FILE;
4665 DirectiveKindMap[".line"] = DK_LINE;
4666 DirectiveKindMap[".loc"] = DK_LOC;
4667 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004668 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
4669 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
4670 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00004671 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
David Majnemer408b5e62016-02-05 01:55:49 +00004672 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004673 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
4674 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Eli Bendersky17233942013-01-15 22:59:42 +00004675 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4676 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4677 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4678 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4679 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4680 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4681 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4682 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4683 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4684 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4685 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4686 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4687 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4688 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4689 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4690 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4691 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4692 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4693 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4694 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4695 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00004696 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00004697 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4698 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4699 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00004700 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00004701 DirectiveKindMap[".endm"] = DK_ENDM;
4702 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4703 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004704 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004705 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00004706 DirectiveKindMap[".warning"] = DK_WARNING;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00004707 DirectiveKindMap[".reloc"] = DK_RELOC;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00004708}
4709
Jim Grosbach4b905842013-09-20 23:08:21 +00004710MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004711 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004712
Rafael Espindola34b9c512012-06-03 23:57:14 +00004713 unsigned NestLevel = 0;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004714 for (;;) {
4715 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00004716 if (getLexer().is(AsmToken::Eof)) {
4717 Error(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00004718 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004719 }
4720
Rafael Espindola34b9c512012-06-03 23:57:14 +00004721 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00004722 (getTok().getIdentifier() == ".rept" ||
4723 getTok().getIdentifier() == ".irp" ||
4724 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004725 ++NestLevel;
4726 }
4727
4728 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00004729 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004730 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004731 EndToken = getTok();
4732 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004733 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4734 TokError("unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00004735 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004736 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004737 break;
4738 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004739 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004740 }
4741
Rafael Espindola34b9c512012-06-03 23:57:14 +00004742 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004743 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004744 }
4745
4746 const char *BodyStart = StartToken.getLoc().getPointer();
4747 const char *BodyEnd = EndToken.getLoc().getPointer();
4748 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4749
Rafael Espindola34b9c512012-06-03 23:57:14 +00004750 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004751 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00004752 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004753}
4754
Jim Grosbach4b905842013-09-20 23:08:21 +00004755void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00004756 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004757 OS << ".endr\n";
4758
Rafael Espindola3560ff22014-08-27 20:03:13 +00004759 std::unique_ptr<MemoryBuffer> Instantiation =
4760 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004761
Rafael Espindola34b9c512012-06-03 23:57:14 +00004762 // Create the macro instantiation object and add to the current macro
4763 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00004764 MacroInstantiation *MI = new MacroInstantiation(
4765 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00004766 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004767
Rafael Espindola34b9c512012-06-03 23:57:14 +00004768 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00004769 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00004770 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00004771 Lex();
4772}
4773
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004774/// parseDirectiveRept
4775/// ::= .rep | .rept count
4776bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004777 const MCExpr *CountExpr;
4778 SMLoc CountLoc = getTok().getLoc();
4779 if (parseExpression(CountExpr))
4780 return true;
4781
Rafael Espindola34b9c512012-06-03 23:57:14 +00004782 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00004783 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004784 eatToEndOfStatement();
4785 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4786 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004787
Nirav Davea645433c2016-07-18 15:24:03 +00004788 if (check(Count < 0, CountLoc, "Count is negative") ||
4789 parseToken(AsmToken::EndOfStatement,
4790 "unexpected token in '" + Dir + "' directive"))
4791 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004792
4793 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004794 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00004795 if (!M)
4796 return true;
4797
4798 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4799 // to hold the macro body with substitutions.
4800 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004801 raw_svector_ostream OS(Buf);
4802 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00004803 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4804 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00004805 return true;
4806 }
Jim Grosbach4b905842013-09-20 23:08:21 +00004807 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004808
4809 return false;
4810}
4811
Jim Grosbach4b905842013-09-20 23:08:21 +00004812/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00004813/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00004814bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00004815 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00004816 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00004817 if (check(parseIdentifier(Parameter.Name),
4818 "expected identifier in '.irp' directive") ||
4819 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
4820 parseMacroArguments(nullptr, A) ||
4821 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004822 return true;
4823
Rafael Espindola768b41c2012-06-15 14:02:34 +00004824 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004825 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00004826 if (!M)
4827 return true;
4828
4829 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4830 // to hold the macro body with substitutions.
4831 SmallString<256> Buf;
4832 raw_svector_ostream OS(Buf);
4833
Craig Topper84008482015-10-10 05:38:14 +00004834 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00004835 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4836 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00004837 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004838 return true;
4839 }
4840
Jim Grosbach4b905842013-09-20 23:08:21 +00004841 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00004842
4843 return false;
4844}
4845
Jim Grosbach4b905842013-09-20 23:08:21 +00004846/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004847/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00004848bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00004849 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00004850 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00004851
4852 if (check(parseIdentifier(Parameter.Name),
4853 "expected identifier in '.irpc' directive") ||
4854 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
4855 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004856 return true;
4857
4858 if (A.size() != 1 || A.front().size() != 1)
4859 return TokError("unexpected token in '.irpc' directive");
4860
4861 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00004862 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
4863 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004864
4865 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004866 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004867 if (!M)
4868 return true;
4869
4870 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4871 // to hold the macro body with substitutions.
4872 SmallString<256> Buf;
4873 raw_svector_ostream OS(Buf);
4874
4875 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004876 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00004877 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004878 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004879
Toma Tabacu217116e2015-04-27 10:50:29 +00004880 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
4881 // This is undocumented, but GAS seems to support it.
4882 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004883 return true;
4884 }
4885
Jim Grosbach4b905842013-09-20 23:08:21 +00004886 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004887
4888 return false;
4889}
4890
Jim Grosbach4b905842013-09-20 23:08:21 +00004891bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004892 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00004893 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004894
4895 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00004896 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004897 assert(getLexer().is(AsmToken::EndOfStatement));
4898
Jim Grosbach4b905842013-09-20 23:08:21 +00004899 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004900 return false;
4901}
Rafael Espindola12d73d12010-09-11 16:45:15 +00004902
Jim Grosbach4b905842013-09-20 23:08:21 +00004903bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00004904 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00004905 const MCExpr *Value;
4906 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004907 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00004908 return true;
4909 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4910 if (!MCE)
4911 return Error(ExprLoc, "unexpected expression in _emit");
4912 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00004913 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00004914 return Error(ExprLoc, "literal value out of range for directive");
4915
Craig Topper7d5b2312015-10-10 05:25:02 +00004916 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00004917 return false;
4918}
4919
Jim Grosbach4b905842013-09-20 23:08:21 +00004920bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00004921 const MCExpr *Value;
4922 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004923 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00004924 return true;
4925 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4926 if (!MCE)
4927 return Error(ExprLoc, "unexpected expression in align");
4928 uint64_t IntValue = MCE->getValue();
4929 if (!isPowerOf2_64(IntValue))
4930 return Error(ExprLoc, "literal value not a power of two greater then zero");
4931
Craig Topper7d5b2312015-10-10 05:25:02 +00004932 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00004933 return false;
4934}
4935
Chad Rosierf43fcf52013-02-13 21:27:17 +00004936// We are comparing pointers, but the pointers are relative to a single string.
4937// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00004938static int rewritesSort(const AsmRewrite *AsmRewriteA,
4939 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00004940 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4941 return -1;
4942 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4943 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004944
Chad Rosierfce4fab2013-04-08 17:43:47 +00004945 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4946 // rewrite to the same location. Make sure the SizeDirective rewrite is
4947 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4948 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00004949 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4950 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004951 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00004952
Jim Grosbach4b905842013-09-20 23:08:21 +00004953 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4954 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004955 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00004956 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00004957}
4958
Jim Grosbach4b905842013-09-20 23:08:21 +00004959bool AsmParser::parseMSInlineAsm(
4960 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4961 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4962 SmallVectorImpl<std::string> &Constraints,
4963 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4964 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00004965 SmallVector<void *, 4> InputDecls;
4966 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00004967 SmallVector<bool, 4> InputDeclsAddressOf;
4968 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00004969 SmallVector<std::string, 4> InputConstraints;
4970 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00004971 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00004972
Benjamin Kramer1a136112013-02-15 20:37:21 +00004973 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00004974
4975 // Prime the lexer.
4976 Lex();
4977
4978 // While we have input, parse each statement.
4979 unsigned InputIdx = 0;
4980 unsigned OutputIdx = 0;
4981 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00004982 // Parse curly braces marking block start/end
4983 if (parseCurlyBlockScope(AsmStrRewrites))
4984 continue;
4985
Eli Friedman0f4871d2012-10-22 23:58:19 +00004986 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00004987 if (parseStatement(Info, &SI))
Chad Rosierf1f6a722012-10-19 22:57:33 +00004988 return true;
Chad Rosier8bce6642012-10-18 15:49:34 +00004989
Chad Rosier149e8e02012-12-12 22:45:52 +00004990 if (Info.ParseError)
4991 return true;
4992
Benjamin Kramer1a136112013-02-15 20:37:21 +00004993 if (Info.Opcode == ~0U)
4994 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00004995
Benjamin Kramer1a136112013-02-15 20:37:21 +00004996 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00004997
Benjamin Kramer1a136112013-02-15 20:37:21 +00004998 // Build the list of clobbers, outputs and inputs.
4999 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005000 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005001
Benjamin Kramer1a136112013-02-15 20:37:21 +00005002 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005003 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005004 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005005
Benjamin Kramer1a136112013-02-15 20:37:21 +00005006 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005007 if (Operand.isReg() && !Operand.needAddressOf() &&
5008 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005009 unsigned NumDefs = Desc.getNumDefs();
5010 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005011 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5012 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005013 continue;
5014 }
5015
5016 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005017 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005018 if (SymName.empty())
5019 continue;
5020
David Blaikie960ea3f2014-06-08 16:18:35 +00005021 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005022 if (!OpDecl)
5023 continue;
5024
5025 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005026 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005027 if (isOutput) {
5028 ++InputIdx;
5029 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005030 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005031 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005032 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005033 } else {
5034 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005035 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5036 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005037 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005038 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005039 }
Reid Kleckneree088972013-12-10 18:27:32 +00005040
5041 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005042 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5043 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005044 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005045 }
5046
5047 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005048 NumOutputs = OutputDecls.size();
5049 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005050
5051 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005052 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5053 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5054 ClobberRegs.end());
5055 Clobbers.assign(ClobberRegs.size(), std::string());
5056 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5057 raw_string_ostream OS(Clobbers[I]);
5058 IP->printRegName(OS, ClobberRegs[I]);
5059 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005060
5061 // Merge the various outputs and inputs. Output are expected first.
5062 if (NumOutputs || NumInputs) {
5063 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005064 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005065 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005066 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005067 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005068 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005069 }
5070 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005071 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005072 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005073 }
5074 }
5075
5076 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005077 std::string AsmStringIR;
5078 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005079 StringRef ASMString =
5080 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5081 const char *AsmStart = ASMString.begin();
5082 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005083 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005084 for (const AsmRewrite &AR : AsmStrRewrites) {
5085 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005086 if (Kind == AOK_Delete)
5087 continue;
5088
David Majnemer8114c1a2014-06-23 02:17:16 +00005089 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005090 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005091
Chad Rosier120eefd2013-03-19 17:32:17 +00005092 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005093 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005094 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005095
Chad Rosier37e755c2012-10-23 17:43:43 +00005096 // Skip the original expression.
5097 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005098 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005099 continue;
5100 }
5101
Chad Rosierff10ed12013-04-12 16:26:42 +00005102 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005103 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005104 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005105 default:
5106 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005107 case AOK_Imm:
David Majnemer8114c1a2014-06-23 02:17:16 +00005108 OS << "$$" << AR.Val;
Chad Rosier11c42f22012-10-26 18:04:20 +00005109 break;
5110 case AOK_ImmPrefix:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005111 OS << "$$";
Chad Rosier8bce6642012-10-18 15:49:34 +00005112 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005113 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005114 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005115 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005116 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005117 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005118 break;
5119 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005120 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005121 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005122 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005123 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005124 default: break;
5125 case 8: OS << "byte ptr "; break;
5126 case 16: OS << "word ptr "; break;
5127 case 32: OS << "dword ptr "; break;
5128 case 64: OS << "qword ptr "; break;
5129 case 80: OS << "xword ptr "; break;
5130 case 128: OS << "xmmword ptr "; break;
5131 case 256: OS << "ymmword ptr "; break;
5132 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005133 break;
5134 case AOK_Emit:
5135 OS << ".byte";
5136 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005137 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005138 // MS alignment directives are measured in bytes. If the native assembler
5139 // measures alignment in bytes, we can pass it straight through.
5140 OS << ".align";
5141 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5142 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005143
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005144 // Alignment is in log2 form, so print that instead and skip the original
5145 // immediate.
5146 unsigned Val = AR.Val;
5147 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005148 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005149 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5150 break;
5151 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005152 case AOK_EVEN:
5153 OS << ".even";
5154 break;
Chad Rosierf0e87202012-10-25 20:41:34 +00005155 case AOK_DotOperator:
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005156 // Insert the dot if the user omitted it.
Alp Tokere69170a2014-06-26 22:52:05 +00005157 OS.flush();
5158 if (AsmStringIR.back() != '.')
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005159 OS << '.';
David Majnemer8114c1a2014-06-23 02:17:16 +00005160 OS << AR.Val;
Chad Rosierf0e87202012-10-25 20:41:34 +00005161 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005162 case AOK_EndOfStatement:
5163 OS << "\n\t";
5164 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005165 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005166
Chad Rosier8bce6642012-10-18 15:49:34 +00005167 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005168 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005169 }
5170
5171 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005172 if (AsmStart != AsmEnd)
5173 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005174
5175 AsmString = OS.str();
5176 return false;
5177}
5178
Pete Cooper80d21cb2015-06-22 19:35:57 +00005179namespace llvm {
5180namespace MCParserUtils {
5181
5182/// Returns whether the given symbol is used anywhere in the given expression,
5183/// or subexpressions.
5184static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5185 switch (Value->getKind()) {
5186 case MCExpr::Binary: {
5187 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5188 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5189 isSymbolUsedInExpression(Sym, BE->getRHS());
5190 }
5191 case MCExpr::Target:
5192 case MCExpr::Constant:
5193 return false;
5194 case MCExpr::SymbolRef: {
5195 const MCSymbol &S =
5196 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5197 if (S.isVariable())
5198 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5199 return &S == Sym;
5200 }
5201 case MCExpr::Unary:
5202 return isSymbolUsedInExpression(
5203 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5204 }
5205
5206 llvm_unreachable("Unknown expr kind!");
5207}
5208
5209bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5210 MCAsmParser &Parser, MCSymbol *&Sym,
5211 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005212
5213 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005214 SMLoc EqualLoc = Parser.getTok().getLoc();
Pete Cooper80d21cb2015-06-22 19:35:57 +00005215
5216 if (Parser.parseExpression(Value)) {
5217 Parser.TokError("missing expression");
5218 Parser.eatToEndOfStatement();
5219 return true;
5220 }
5221
5222 // Note: we don't count b as used in "a = b". This is to allow
5223 // a = b
5224 // b = c
5225
Nirav Davefd910412016-06-17 16:06:17 +00005226 if (Parser.getTok().isNot(AsmToken::EndOfStatement))
Pete Cooper80d21cb2015-06-22 19:35:57 +00005227 return Parser.TokError("unexpected token in assignment");
5228
5229 // Eat the end of statement marker.
5230 Parser.Lex();
5231
5232 // Validate that the LHS is allowed to be a variable (either it has not been
5233 // used as a symbol, or it is an absolute symbol).
5234 Sym = Parser.getContext().lookupSymbol(Name);
5235 if (Sym) {
5236 // Diagnose assignment to a label.
5237 //
5238 // FIXME: Diagnostics. Note the location of the definition as a label.
5239 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5240 if (isSymbolUsedInExpression(Sym, Value))
5241 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005242 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5243 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005244 ; // Allow redefinitions of undefined symbols only used in directives.
5245 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5246 ; // Allow redefinitions of variables that haven't yet been used.
5247 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5248 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5249 else if (!Sym->isVariable())
5250 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5251 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5252 return Parser.Error(EqualLoc,
5253 "invalid reassignment of non-absolute variable '" +
5254 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005255 } else if (Name == ".") {
Rafael Espindola7ae65d82015-11-04 23:59:18 +00005256 Parser.getStreamer().emitValueToOffset(Value, 0);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005257 return false;
5258 } else
5259 Sym = Parser.getContext().getOrCreateSymbol(Name);
5260
5261 Sym->setRedefinable(allow_redef);
5262
5263 return false;
5264}
5265
5266} // namespace MCParserUtils
5267} // namespace llvm
5268
Daniel Dunbar01e36072010-07-17 02:26:10 +00005269/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005270MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
5271 MCStreamer &Out, const MCAsmInfo &MAI) {
Jim Grosbach345768c2011-08-16 18:33:49 +00005272 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005273}