blob: 8f2ee7f116368de6e2ed879c02f9edebf488b9b6 [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"
Benjamin Kramer4efe5062012-01-28 15:28:41 +000037#include "llvm/Support/ErrorHandling.h"
Jim Grosbach76346c32011-06-29 16:05:14 +000038#include "llvm/Support/MathExtras.h"
Kevin Enderbye233dda2010-06-28 21:45:58 +000039#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000040#include "llvm/Support/SourceMgr.h"
Chris Lattner36e02122009-06-21 20:54:55 +000041#include "llvm/Support/raw_ostream.h"
Nick Lewycky0de20af2010-12-19 20:43:38 +000042#include <cctype>
Benjamin Kramerd59664f2014-04-29 23:26:49 +000043#include <deque>
Chad Rosier8bce6642012-10-18 15:49:34 +000044#include <string>
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000045#include <vector>
Chris Lattnerb0133452009-06-21 20:16:42 +000046using namespace llvm;
47
Eric Christophera7c32732012-12-18 00:30:54 +000048MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
Nick Lewyckyac612272012-10-19 07:00:09 +000049
Daniel Dunbar86033402010-07-12 17:54:38 +000050namespace {
Eli Benderskya313ae62013-01-16 18:56:50 +000051/// \brief Helper types for tracking macro definitions.
52typedef std::vector<AsmToken> MCAsmMacroArgument;
53typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000054
55struct MCAsmMacroParameter {
56 StringRef Name;
57 MCAsmMacroArgument Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000058 bool Required;
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +000059 bool Vararg;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000060
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +000061 MCAsmMacroParameter() : Required(false), Vararg(false) {}
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000062};
63
Eli Benderskya313ae62013-01-16 18:56:50 +000064typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
65
66struct MCAsmMacro {
67 StringRef Name;
68 StringRef Body;
69 MCAsmMacroParameters Parameters;
70
71public:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +000072 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
73 : Name(N), Body(B), Parameters(std::move(P)) {}
Eli Benderskya313ae62013-01-16 18:56:50 +000074};
75
Daniel Dunbar43235712010-07-18 18:54:11 +000076/// \brief Helper class for storing information about an active macro
77/// instantiation.
78struct MacroInstantiation {
Daniel Dunbar43235712010-07-18 18:54:11 +000079 /// The location of the instantiation.
80 SMLoc InstantiationLoc;
81
Daniel Dunbar40f1d852012-12-01 01:38:48 +000082 /// The buffer where parsing should resume upon instantiation completion.
83 int ExitBuffer;
84
Daniel Dunbar43235712010-07-18 18:54:11 +000085 /// The location where parsing should resume upon instantiation completion.
86 SMLoc ExitLoc;
87
Nico Weber155dccd12014-07-24 17:08:39 +000088 /// The depth of TheCondStack at the start of the instantiation.
89 size_t CondStackDepth;
90
Daniel Dunbar43235712010-07-18 18:54:11 +000091public:
Rafael Espindola9eef18c2014-08-27 19:49:03 +000092 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
Daniel Dunbar43235712010-07-18 18:54:11 +000093};
94
Eli Friedman0f4871d2012-10-22 23:58:19 +000095struct ParseStatementInfo {
Jim Grosbach4b905842013-09-20 23:08:21 +000096 /// \brief The parsed operands from the last parsed statement.
David Blaikie960ea3f2014-06-08 16:18:35 +000097 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
Eli Friedman0f4871d2012-10-22 23:58:19 +000098
Jim Grosbach4b905842013-09-20 23:08:21 +000099 /// \brief The opcode from the last parsed instruction.
Eli Friedman0f4871d2012-10-22 23:58:19 +0000100 unsigned Opcode;
101
Jim Grosbach4b905842013-09-20 23:08:21 +0000102 /// \brief Was there an error parsing the inline assembly?
Chad Rosier149e8e02012-12-12 22:45:52 +0000103 bool ParseError;
104
Eli Friedman0f4871d2012-10-22 23:58:19 +0000105 SmallVectorImpl<AsmRewrite> *AsmRewrites;
106
Craig Topper353eda42014-04-24 06:44:33 +0000107 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000108 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier149e8e02012-12-12 22:45:52 +0000109 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000110};
111
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000112/// \brief The concrete assembly parser instance.
113class AsmParser : public MCAsmParser {
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000114 AsmParser(const AsmParser &) = delete;
115 void operator=(const AsmParser &) = delete;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000116private:
117 AsmLexer Lexer;
118 MCContext &Ctx;
119 MCStreamer &Out;
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000120 const MCAsmInfo &MAI;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000121 SourceMgr &SrcMgr;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000122 SourceMgr::DiagHandlerTy SavedDiagHandler;
123 void *SavedDiagContext;
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000124 std::unique_ptr<MCAsmParserExtension> PlatformParser;
Rafael Espindola82065cb2011-04-11 21:49:50 +0000125
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000126 /// This is the current buffer index we're lexing from as managed by the
127 /// SourceMgr object.
Alp Tokera55b95b2014-07-06 10:33:31 +0000128 unsigned CurBuffer;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000129
130 AsmCond TheCondState;
131 std::vector<AsmCond> TheCondStack;
132
Jim Grosbach4b905842013-09-20 23:08:21 +0000133 /// \brief maps directive names to handler methods in parser
Eli Bendersky17233942013-01-15 22:59:42 +0000134 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000135 /// addDirectiveHandler.
Eli Bendersky17233942013-01-15 22:59:42 +0000136 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000137
Jim Grosbach4b905842013-09-20 23:08:21 +0000138 /// \brief Map of currently defined macros.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000139 StringMap<MCAsmMacro> MacroMap;
Daniel Dunbarc1f58ec2010-07-18 18:47:21 +0000140
Jim Grosbach4b905842013-09-20 23:08:21 +0000141 /// \brief Stack of active macro instantiations.
Daniel Dunbar43235712010-07-18 18:54:11 +0000142 std::vector<MacroInstantiation*> ActiveMacros;
143
Jim Grosbach4b905842013-09-20 23:08:21 +0000144 /// \brief List of bodies of anonymous macros.
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +0000145 std::deque<MCAsmMacro> MacroLikeBodies;
146
Daniel Dunbar828984f2010-07-18 18:38:02 +0000147 /// Boolean tracking whether macro substitution is enabled.
Eli Benderskyc2f6f922013-01-14 18:08:41 +0000148 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000149
Toma Tabacu217116e2015-04-27 10:50:29 +0000150 /// \brief Keeps track of how many .macro's have been instantiated.
151 unsigned NumOfMacroInstantiations;
152
Daniel Dunbar43325c42010-09-09 22:42:56 +0000153 /// Flag tracking whether any errors have been encountered.
154 unsigned HadError : 1;
155
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000156 /// The values from the last parsed cpp hash file line comment if any.
Tim Northoverc0bef992016-04-13 19:46:54 +0000157 struct CppHashInfoTy {
158 StringRef Filename;
Andrew Kaylorca196472016-04-21 20:09:35 +0000159 int64_t LineNumber = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000160 SMLoc Loc;
Andrew Kaylorca196472016-04-21 20:09:35 +0000161 unsigned Buf = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000162 };
163 CppHashInfoTy CppHashInfo;
164
165 /// \brief List of forward directional labels for diagnosis at the end.
166 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
167
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000168 /// When generating dwarf for assembly source files we need to calculate the
169 /// logical line number based on the last parsed cpp hash file line comment
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000170 /// and current line. Since this is slow and messes up the SourceMgr's
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000171 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
172 SMLoc LastQueryIDLoc;
Alp Tokera55b95b2014-07-06 10:33:31 +0000173 unsigned LastQueryBuffer;
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000174 unsigned LastQueryLine;
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000175
Devang Patela173ee52012-01-31 18:14:05 +0000176 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
177 unsigned AssemblerDialect;
178
Jim Grosbach4b905842013-09-20 23:08:21 +0000179 /// \brief is Darwin compatibility enabled?
Preston Gurd05500642012-09-19 20:36:12 +0000180 bool IsDarwin;
181
Jim Grosbach4b905842013-09-20 23:08:21 +0000182 /// \brief Are we parsing ms-style inline assembly?
Chad Rosier49963552012-10-13 00:26:04 +0000183 bool ParsingInlineAsm;
184
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000185public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000186 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000187 const MCAsmInfo &MAI);
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000188 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000189
Craig Topper59be68f2014-03-08 07:14:16 +0000190 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000191
Craig Topper59be68f2014-03-08 07:14:16 +0000192 void addDirectiveHandler(StringRef Directive,
193 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000194 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000195 }
196
Toma Tabacu11e14a92015-04-21 11:50:52 +0000197 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
198 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
199 }
200
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000201public:
202 /// @name MCAsmParser Interface
203 /// {
204
Craig Topper59be68f2014-03-08 07:14:16 +0000205 SourceMgr &getSourceManager() override { return SrcMgr; }
206 MCAsmLexer &getLexer() override { return Lexer; }
207 MCContext &getContext() override { return Ctx; }
208 MCStreamer &getStreamer() override { return Out; }
209 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000210 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000211 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000212 else
213 return AssemblerDialect;
214 }
Craig Topper59be68f2014-03-08 07:14:16 +0000215 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000216 AssemblerDialect = i;
217 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000218
Craig Topper59be68f2014-03-08 07:14:16 +0000219 void Note(SMLoc L, const Twine &Msg,
220 ArrayRef<SMRange> Ranges = None) override;
221 bool Warning(SMLoc L, const Twine &Msg,
222 ArrayRef<SMRange> Ranges = None) override;
223 bool Error(SMLoc L, const Twine &Msg,
224 ArrayRef<SMRange> Ranges = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000225
Craig Topper59be68f2014-03-08 07:14:16 +0000226 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000227
Craig Topper59be68f2014-03-08 07:14:16 +0000228 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
229 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000230
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000231 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000232 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier37e755c2012-10-23 17:43:43 +0000233 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000234 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000235 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000236 const MCInstrInfo *MII, const MCInstPrinter *IP,
237 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000238
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000239 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000240 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
241 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
242 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000243 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
244 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000245 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000246
Jim Grosbach4b905842013-09-20 23:08:21 +0000247 /// \brief Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000248 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000249 bool parseIdentifier(StringRef &Res) override;
250 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000251
Craig Topper59be68f2014-03-08 07:14:16 +0000252 void checkForValidSection() override;
Nirav Davea645433c2016-07-18 15:24:03 +0000253
254 bool getTokenLoc(SMLoc &Loc) {
255 Loc = getTok().getLoc();
256 return false;
257 }
258
259 /// parseToken - If current token has the specified kind, eat it and
260 /// return success. Otherwise, emit the specified error and return failure.
261 bool parseToken(AsmToken::TokenKind T, const Twine &ErrMsg) {
262 if (getTok().getKind() != T)
263 return TokError(ErrMsg);
264 Lex();
265 return false;
266 }
267
268 bool parseIntToken(int64_t &V, const Twine &ErrMsg) {
269 if (getTok().getKind() != AsmToken::Integer)
270 return TokError(ErrMsg);
271 V = getTok().getIntVal();
272 Lex();
273 return false;
274 }
275
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000276 /// }
277
278private:
Daniel Dunbare5444a82010-09-09 22:42:59 +0000279
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000280 bool parseStatement(ParseStatementInfo &Info,
281 MCAsmParserSemaCallback *SI);
Marina Yatsina5f5de9f2016-03-07 18:11:16 +0000282 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
Craig Topper3c76c522015-09-20 23:35:59 +0000283 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000284
Jim Grosbach4b905842013-09-20 23:08:21 +0000285 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000286 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000287 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000288 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000289 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000290 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000291
Eli Benderskya313ae62013-01-16 18:56:50 +0000292 /// \brief Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000293 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000294
295 /// \brief Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000296 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000297
298 /// \brief Lookup a previously defined macro.
299 /// \param Name Macro name.
300 /// \returns Pointer to macro. NULL if no such macro was defined.
Jim Grosbach4b905842013-09-20 23:08:21 +0000301 const MCAsmMacro* lookupMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000302
303 /// \brief Define a new macro with the given name and information.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000304 void defineMacro(StringRef Name, MCAsmMacro Macro);
Eli Benderskya313ae62013-01-16 18:56:50 +0000305
306 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
Jim Grosbach4b905842013-09-20 23:08:21 +0000307 void undefineMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000308
309 /// \brief Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000310 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000311
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000312 /// \brief Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000313 ///
314 /// \param M The macro.
315 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000316 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000317
318 /// \brief Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000319 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000320
David Majnemer91fc4c22014-01-29 18:57:46 +0000321 /// \brief Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000322 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000323
324 /// \brief Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000325 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000326
Jim Grosbach4b905842013-09-20 23:08:21 +0000327 void printMacroInstantiations();
328 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Dmitri Gribenko3238fb72013-05-05 00:40:33 +0000329 ArrayRef<SMRange> Ranges = None) const {
Chris Lattner72845262011-10-16 05:47:55 +0000330 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000331 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000332 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000333
Nirav Davea645433c2016-07-18 15:24:03 +0000334 bool check(bool P, SMLoc Loc, const Twine &Msg) {
335 if (P)
336 return Error(Loc, Msg);
337 return false;
338 }
339
340 bool check(bool P, const Twine &Msg) {
341 if (P)
342 return TokError(Msg);
343 return false;
344 }
345
Jim Grosbach4b905842013-09-20 23:08:21 +0000346 /// \brief Enter the specified file. This returns true on failure.
347 bool enterIncludeFile(const std::string &Filename);
348
349 /// \brief Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000350 /// This returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000351 bool processIncbinFile(const std::string &Filename);
Daniel Dunbar43235712010-07-18 18:54:11 +0000352
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000353 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000354 /// current token is not set; clients should ensure Lex() is called
355 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000356 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000357 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000358 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000359 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000360
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000361 /// \brief Parse up to the end of statement and a return the contents from the
362 /// current token until the end of the statement; the current token on exit
363 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000364 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000365
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000366 /// \brief Parse until the end of a statement or a comma is encountered,
367 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000368 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000369
Jim Grosbach4b905842013-09-20 23:08:21 +0000370 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +0000371 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000372
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000373 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
374 MCBinaryExpr::Opcode &Kind);
375
Jim Grosbach4b905842013-09-20 23:08:21 +0000376 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
377 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
378 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000379
Jim Grosbach4b905842013-09-20 23:08:21 +0000380 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000381
Eli Bendersky17233942013-01-15 22:59:42 +0000382 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000383 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000384 DK_NO_DIRECTIVE, // Placeholder
385 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000386 DK_RELOC,
David Woodhoused6de0d92014-02-01 16:20:59 +0000387 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
388 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky96522722013-01-11 22:55:28 +0000389 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000390 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
Kevin Enderby3aeada22013-08-28 17:50:59 +0000391 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
Lang Hamesf9033bb2016-04-11 18:33:45 +0000392 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER,
Lang Hames1b640e02016-03-15 01:43:05 +0000393 DK_PRIVATE_EXTERN, DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000394 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
395 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000396 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
Sid Manning51c35602015-03-18 14:20:54 +0000397 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
398 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
Eli Bendersky17233942013-01-15 22:59:42 +0000399 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000400 DK_CV_FILE, DK_CV_LOC, DK_CV_LINETABLE, DK_CV_INLINE_LINETABLE,
David Majnemer408b5e62016-02-05 01:55:49 +0000401 DK_CV_DEF_RANGE, DK_CV_STRINGTABLE, DK_CV_FILECHECKSUMS,
Eli Bendersky17233942013-01-15 22:59:42 +0000402 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
403 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
404 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
405 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
406 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000407 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
Nico Weber155dccd12014-07-24 17:08:39 +0000408 DK_MACROS_ON, DK_MACROS_OFF,
409 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000410 DK_SLEB128, DK_ULEB128,
Nico Weber404012b2014-07-24 16:26:06 +0000411 DK_ERR, DK_ERROR, DK_WARNING,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000412 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000413 };
414
Jim Grosbach4b905842013-09-20 23:08:21 +0000415 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000416 /// directives parsed by this class.
417 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000418
419 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000420 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000421 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Jim Grosbach4b905842013-09-20 23:08:21 +0000422 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
David Woodhoused6de0d92014-02-01 16:20:59 +0000423 bool parseDirectiveOctaValue(); // ".octa"
Jim Grosbach4b905842013-09-20 23:08:21 +0000424 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
425 bool parseDirectiveFill(); // ".fill"
426 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000427 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000428 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
429 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000430 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000431 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000432
Eli Bendersky17233942013-01-15 22:59:42 +0000433 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000434 bool parseDirectiveFile(SMLoc DirectiveLoc);
435 bool parseDirectiveLine();
436 bool parseDirectiveLoc();
437 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000438
David Majnemer408b5e62016-02-05 01:55:49 +0000439 // ".cv_file", ".cv_loc", ".cv_linetable", "cv_inline_linetable",
440 // ".cv_def_range"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000441 bool parseDirectiveCVFile();
442 bool parseDirectiveCVLoc();
443 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000444 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000445 bool parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000446 bool parseDirectiveCVStringTable();
447 bool parseDirectiveCVFileChecksums();
448
Eli Bendersky17233942013-01-15 22:59:42 +0000449 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000450 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000451 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000452 bool parseDirectiveCFISections();
453 bool parseDirectiveCFIStartProc();
454 bool parseDirectiveCFIEndProc();
455 bool parseDirectiveCFIDefCfaOffset();
456 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
457 bool parseDirectiveCFIAdjustCfaOffset();
458 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
459 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
460 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
461 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
462 bool parseDirectiveCFIRememberState();
463 bool parseDirectiveCFIRestoreState();
464 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
465 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
466 bool parseDirectiveCFIEscape();
467 bool parseDirectiveCFISignalFrame();
468 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000469
470 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000471 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000472 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000473 bool parseDirectiveEndMacro(StringRef Directive);
474 bool parseDirectiveMacro(SMLoc DirectiveLoc);
475 bool parseDirectiveMacrosOnOff(StringRef Directive);
Eli Bendersky17233942013-01-15 22:59:42 +0000476
Eli Benderskyf483ff92012-12-20 19:05:53 +0000477 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000478 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000479 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000480 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000481 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000482 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000483
Eli Bendersky17233942013-01-15 22:59:42 +0000484 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000485 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000486
487 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000488 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000489
Jim Grosbach4b905842013-09-20 23:08:21 +0000490 /// \brief Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000491 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000492 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000493
Jim Grosbach4b905842013-09-20 23:08:21 +0000494 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000495
Jim Grosbach4b905842013-09-20 23:08:21 +0000496 bool parseDirectiveAbort(); // ".abort"
497 bool parseDirectiveInclude(); // ".include"
498 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000499
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000500 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
501 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000502 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000503 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000504 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000505 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000506 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
507 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000508 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000509 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
510 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
511 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
512 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000513 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000514
Jim Grosbach4b905842013-09-20 23:08:21 +0000515 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000516 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000517
Rafael Espindola34b9c512012-06-03 23:57:14 +0000518 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000519 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
520 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000521 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000522 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000523 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
524 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
525 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000526
Chad Rosierc7f552c2013-02-12 21:33:51 +0000527 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000528 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000529 size_t Len);
530
531 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000532 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000533
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000534 // "end"
535 bool parseDirectiveEnd(SMLoc DirectiveLoc);
536
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000537 // ".err" or ".error"
538 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000539
Nico Weber404012b2014-07-24 16:26:06 +0000540 // ".warning"
541 bool parseDirectiveWarning(SMLoc DirectiveLoc);
542
Eli Bendersky17233942013-01-15 22:59:42 +0000543 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000544};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000545}
Daniel Dunbar86033402010-07-12 17:54:38 +0000546
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000547namespace llvm {
548
549extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000550extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000551extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000552
553}
554
Chris Lattnerc35681b2010-01-19 19:46:13 +0000555enum { DEFAULT_ADDRSPACE = 0 };
556
David Blaikie9f380a32015-03-16 18:06:57 +0000557AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
558 const MCAsmInfo &MAI)
559 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
560 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
Tim Northoverc0bef992016-04-13 19:46:54 +0000561 MacrosEnabledFlag(true), HadError(false), CppHashInfo(),
Oliver Stannardcf6bfb12014-11-03 12:19:03 +0000562 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000563 // Save the old handler.
564 SavedDiagHandler = SrcMgr.getDiagHandler();
565 SavedDiagContext = SrcMgr.getDiagContext();
566 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000567 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000568 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000569
Daniel Dunbarc5011082010-07-12 18:12:02 +0000570 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000571 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
572 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000573 PlatformParser.reset(createCOFFAsmParser());
574 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000575 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000576 PlatformParser.reset(createDarwinAsmParser());
577 IsDarwin = true;
578 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000579 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000580 PlatformParser.reset(createELFAsmParser());
581 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000582 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000583
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000584 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000585 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000586
587 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000588}
589
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000590AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000591 assert((HadError || ActiveMacros.empty()) &&
592 "Unexpected active macro instantiation!");
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000593}
594
Jim Grosbach4b905842013-09-20 23:08:21 +0000595void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000596 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000597 for (std::vector<MacroInstantiation *>::const_reverse_iterator
598 it = ActiveMacros.rbegin(),
599 ie = ActiveMacros.rend();
600 it != ie; ++it)
601 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000602 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000603}
604
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000605void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
606 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
607 printMacroInstantiations();
608}
609
Chris Lattnera3a06812011-10-16 04:47:35 +0000610bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000611 if(getTargetParser().getTargetOptions().MCNoWarn)
612 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000613 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Chris Lattnera3a06812011-10-16 04:47:35 +0000614 return Error(L, Msg, Ranges);
Jim Grosbach4b905842013-09-20 23:08:21 +0000615 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
616 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000617 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000618}
619
Chris Lattnera3a06812011-10-16 04:47:35 +0000620bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000621 HadError = true;
Jim Grosbach4b905842013-09-20 23:08:21 +0000622 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
623 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000624 return true;
625}
626
Jim Grosbach4b905842013-09-20 23:08:21 +0000627bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000628 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000629 unsigned NewBuf =
630 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
631 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000632 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000633
Sean Callanan7a77eae2010-01-21 00:19:58 +0000634 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000635 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000636 return false;
637}
Daniel Dunbar43235712010-07-18 18:54:11 +0000638
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000639/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000640/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000641/// returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000642bool AsmParser::processIncbinFile(const std::string &Filename) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000643 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000644 unsigned NewBuf =
645 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
646 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000647 return true;
648
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000649 // Pick up the bytes from the file and emit them.
Rafael Espindola64e1af82013-07-02 15:49:13 +0000650 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
Kevin Enderby109f25c2011-12-14 21:47:48 +0000651 return false;
652}
653
Alp Tokera55b95b2014-07-06 10:33:31 +0000654void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
655 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000656 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
657 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000658}
659
Sean Callanan7a77eae2010-01-21 00:19:58 +0000660const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000661 if (Lexer.getTok().is(AsmToken::Error))
662 Error(Lexer.getErrLoc(), Lexer.getErr());
663
Nirav Dave53a72f42016-07-11 12:42:14 +0000664 // if it's a end of statement with a comment in it
665 if (getTok().is(AsmToken::EndOfStatement)) {
666 // if this is a line comment output it.
667 if (getTok().getString().front() != '\n' &&
668 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
669 Out.addExplicitComment(Twine(getTok().getString()));
670 }
671
Sean Callanan7a77eae2010-01-21 00:19:58 +0000672 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000673
674 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000675 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000676 if (MAI.preserveAsmComments())
677 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000678 tok = &Lexer.Lex();
679 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000680
Sean Callanan7a77eae2010-01-21 00:19:58 +0000681 if (tok->is(AsmToken::Eof)) {
682 // If this is the end of an included file, pop the parent file off the
683 // include stack.
684 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
685 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000686 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000687 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000688 }
689 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000690
Michael J. Spencer530ce852010-10-09 11:00:50 +0000691
Sean Callanan7a77eae2010-01-21 00:19:58 +0000692 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000693}
694
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000695bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000696 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000697 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000698 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000699
Chris Lattner36e02122009-06-21 20:54:55 +0000700 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000701 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000702
703 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000704 AsmCond StartingCondState = TheCondState;
705
Kevin Enderby6469fc22011-11-01 22:27:22 +0000706 // If we are generating dwarf for assembly source files save the initial text
707 // section and generate a .file directive.
708 if (getContext().getGenDwarfForAssembly()) {
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000709 MCSection *Sec = getStreamer().getCurrentSection().first;
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000710 if (!Sec->getBeginSymbol()) {
711 MCSymbol *SectionStartSym = getContext().createTempSymbol();
712 getStreamer().EmitLabel(SectionStartSym);
713 Sec->setBeginSymbol(SectionStartSym);
714 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000715 bool InsertResult = getContext().addGenDwarfSection(Sec);
716 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000717 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000718 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
719 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000720 }
721
Chris Lattner73f36112009-07-02 21:53:43 +0000722 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000723 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman0f4871d2012-10-22 23:58:19 +0000724 ParseStatementInfo Info;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000725 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000726 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000727
Nirav Dave1180e6892016-06-02 17:15:05 +0000728 // If we've failed, but on a Error Token, but did not consume it in
729 // favor of a better message, emit it now.
730 if (Lexer.getTok().is(AsmToken::Error)) {
731 Lex();
732 }
733
Daniel Dunbar43325c42010-09-09 22:42:56 +0000734 // We had an error, validate that one was emitted and recover by skipping to
735 // the next line.
736 assert(HadError && "Parse statement returned an error, but none emitted!");
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000737 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000738 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000739
Oliver Stannard21718282016-07-26 14:19:47 +0000740 getTargetParser().flushPendingInstructions(getStreamer());
741
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000742 if (TheCondState.TheCond != StartingCondState.TheCond ||
743 TheCondState.Ignore != StartingCondState.Ignore)
744 return TokError("unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000745
746 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000747 const auto &LineTables = getContext().getMCDwarfLineTables();
748 if (!LineTables.empty()) {
749 unsigned Index = 0;
750 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
751 if (File.Name.empty() && Index != 0)
752 TokError("unassigned file number: " + Twine(Index) +
753 " for .file directives");
754 ++Index;
755 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000756 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000757
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000758 // Check to see that all assembler local symbols were actually defined.
759 // Targets that don't do subsections via symbols may not want this, though,
760 // so conservatively exclude them. Only do this if we're finalizing, though,
761 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000762 if (!NoFinalize) {
763 if (MAI.hasSubsectionsViaSymbols()) {
764 for (const auto &TableEntry : getContext().getSymbols()) {
765 MCSymbol *Sym = TableEntry.getValue();
766 // Variable symbols may not be marked as defined, so check those
767 // explicitly. If we know it's a variable, we have a definition for
768 // the purposes of this check.
769 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
770 // FIXME: We would really like to refer back to where the symbol was
771 // first referenced for a source location. We need to add something
772 // to track that. Currently, we just point to the end of the file.
773 HadError |=
Nirav Davefd910412016-06-17 16:06:17 +0000774 Error(getTok().getLoc(), "assembler local symbol '" +
775 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000776 }
777 }
778
779 // Temporary symbols like the ones for directional jumps don't go in the
780 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000781 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
782 if (std::get<2>(LocSym)->isUndefined()) {
783 // Reset the state of any "# line file" directives we've seen to the
784 // context as it was at the diagnostic site.
785 CppHashInfo = std::get<1>(LocSym);
786 HadError |= Error(std::get<0>(LocSym), "directional label undefined");
787 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000788 }
789 }
790
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000791 // Finalize the output stream if there are no errors and if the client wants
792 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000793 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000794 Out.Finish();
795
Oliver Stannard07b43d32015-11-17 09:58:07 +0000796 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000797}
798
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000799void AsmParser::checkForValidSection() {
Peter Collingbourne2f495b92013-04-17 21:18:16 +0000800 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
Daniel Dunbare5444a82010-09-09 22:42:59 +0000801 TokError("expected section directive before assembly directive");
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000802 Out.InitSections(false);
Daniel Dunbare5444a82010-09-09 22:42:59 +0000803 }
804}
805
Jim Grosbach4b905842013-09-20 23:08:21 +0000806/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000807void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000808 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000809 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000810
Chris Lattnere5074c42009-06-22 01:29:09 +0000811 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000812 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000813 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000814}
815
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000816StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000817 const char *Start = getTok().getLoc().getPointer();
818
Jim Grosbach4b905842013-09-20 23:08:21 +0000819 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000820 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000821
822 const char *End = getTok().getLoc().getPointer();
823 return StringRef(Start, End - Start);
824}
Chris Lattner78db3622009-06-22 05:51:26 +0000825
Jim Grosbach4b905842013-09-20 23:08:21 +0000826StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000827 const char *Start = getTok().getLoc().getPointer();
828
829 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000830 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000831 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000832
833 const char *End = getTok().getLoc().getPointer();
834 return StringRef(Start, End - Start);
835}
836
Jim Grosbach4b905842013-09-20 23:08:21 +0000837/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000838/// NOTE: This assumes the leading '(' has already been consumed.
839///
840/// parenexpr ::= expr)
841///
Jim Grosbach4b905842013-09-20 23:08:21 +0000842bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
843 if (parseExpression(Res))
844 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000845 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +0000846 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000847 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000848 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +0000849 return false;
850}
Chris Lattner78db3622009-06-22 05:51:26 +0000851
Jim Grosbach4b905842013-09-20 23:08:21 +0000852/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000853/// NOTE: This assumes the leading '[' has already been consumed.
854///
855/// bracketexpr ::= expr]
856///
Jim Grosbach4b905842013-09-20 23:08:21 +0000857bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
858 if (parseExpression(Res))
859 return true;
Nirav Davea645433c2016-07-18 15:24:03 +0000860 EndLoc = getTok().getEndLoc();
861 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
862 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000863 return false;
864}
865
Jim Grosbach4b905842013-09-20 23:08:21 +0000866/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000867/// primaryexpr ::= (parenexpr
868/// primaryexpr ::= symbol
869/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +0000870/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +0000871/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +0000872bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000873 SMLoc FirstTokenLoc = getLexer().getLoc();
874 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
875 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +0000876 default:
877 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +0000878 // If we have an error assume that we've already handled it.
879 case AsmToken::Error:
880 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000881 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000882 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000883 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000884 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000885 Res = MCUnaryExpr::createLNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000886 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +0000887 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +0000888 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +0000889 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +0000890 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +0000891 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000892 if (parseIdentifier(Identifier)) {
David Majnemer0c58bc62013-09-25 10:47:21 +0000893 if (FirstTokenKind == AsmToken::Dollar) {
894 if (Lexer.getMAI().getDollarIsPC()) {
895 // This is a '$' reference, which references the current PC. Emit a
896 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000897 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +0000898 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000899 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +0000900 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +0000901 EndLoc = FirstTokenLoc;
902 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +0000903 }
904 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +0000905 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000906 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000907 // Parse symbol variant
908 std::pair<StringRef, StringRef> Split;
909 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +0000910 if (FirstTokenKind == AsmToken::String) {
911 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +0000912 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +0000913 SMLoc AtLoc = getLexer().getLoc();
914 StringRef VName;
915 if (parseIdentifier(VName))
916 return Error(AtLoc, "expected symbol variant after '@'");
917
918 Split = std::make_pair(Identifier, VName);
919 }
920 } else {
921 Split = Identifier.split('@');
922 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000923 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +0000924 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +0000925 StringRef VName;
926 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +0000927 // eat ')'.
928 if (parseToken(AsmToken::RParen,
929 "unexpected token in variant, expected ')'"))
930 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +0000931 Split = std::make_pair(Identifier, VName);
932 }
Daniel Dunbar24764322010-08-24 19:13:42 +0000933
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000934 EndLoc = SMLoc::getFromPointer(Identifier.end());
935
Daniel Dunbard20cda02009-10-16 01:34:54 +0000936 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +0000937 StringRef SymbolName = Identifier;
938 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +0000939
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000940 // Lookup the symbol variant if used.
David Peixotto8ad70b32013-12-04 22:43:20 +0000941 if (Split.second.size()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000942 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +0000943 if (Variant != MCSymbolRefExpr::VK_Invalid) {
944 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +0000945 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +0000946 Variant = MCSymbolRefExpr::VK_None;
947 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +0000948 return Error(SMLoc::getFromPointer(Split.second.begin()),
949 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000950 }
951 }
Daniel Dunbar55992562010-03-15 23:51:06 +0000952
Jim Grosbach6f482002015-05-18 18:43:14 +0000953 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +0000954
Daniel Dunbard20cda02009-10-16 01:34:54 +0000955 // If this is an absolute variable reference, substitute it now to preserve
956 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +0000957 if (Sym->isVariable() &&
958 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +0000959 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +0000960 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +0000961
Vedant Kumar86dbd922015-08-31 17:44:53 +0000962 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +0000963 return false;
964 }
965
966 // Otherwise create a symbol ref.
Jim Grosbach13760bd2015-05-30 01:25:56 +0000967 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Chris Lattner78db3622009-06-22 05:51:26 +0000968 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +0000969 }
David Woodhousef42a6662014-02-01 16:20:54 +0000970 case AsmToken::BigNum:
971 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +0000972 case AsmToken::Integer: {
973 SMLoc Loc = getTok().getLoc();
974 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +0000975 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000976 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000977 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +0000978 // Look for 'b' or 'f' following an Integer as a directional label
979 if (Lexer.getKind() == AsmToken::Identifier) {
980 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +0000981 // Lookup the symbol variant if used.
982 std::pair<StringRef, StringRef> Split = IDVal.split('@');
983 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
984 if (Split.first.size() != IDVal.size()) {
985 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +0000986 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +0000987 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000988 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +0000989 }
Jim Grosbach4b905842013-09-20 23:08:21 +0000990 if (IDVal == "f" || IDVal == "b") {
991 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +0000992 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +0000993 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +0000994 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +0000995 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000996 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000997 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +0000998 Lex(); // Eat identifier.
999 }
1000 }
Chris Lattner78db3622009-06-22 05:51:26 +00001001 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001002 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001003 case AsmToken::Real: {
1004 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001005 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001006 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001007 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001008 Lex(); // Eat token.
1009 return false;
1010 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001011 case AsmToken::Dot: {
1012 // This is a '.' reference, which references the current PC. Emit a
1013 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001014 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001015 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001016 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001017 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001018 Lex(); // Eat identifier.
1019 return false;
1020 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001021 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001022 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001023 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001024 case AsmToken::LBrac:
1025 if (!PlatformParser->HasBracketExpressions())
1026 return TokError("brackets expression not supported on this target");
1027 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001028 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001029 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001030 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001031 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001032 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001033 Res = MCUnaryExpr::createMinus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001034 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001035 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001036 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001037 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001038 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001039 Res = MCUnaryExpr::createPlus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001040 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001041 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001042 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001043 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001044 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001045 Res = MCUnaryExpr::createNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001046 return false;
Chris Lattner78db3622009-06-22 05:51:26 +00001047 }
1048}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001049
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001050bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001051 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001052 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001053}
1054
Daniel Dunbar55f16672010-09-17 02:47:07 +00001055const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001056AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001057 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001058 // Ask the target implementation about this expression first.
1059 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1060 if (NewE)
1061 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001062 // Recurse over the given expression, rebuilding it to apply the given variant
1063 // if there is exactly one symbol.
1064 switch (E->getKind()) {
1065 case MCExpr::Target:
1066 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001067 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001068
1069 case MCExpr::SymbolRef: {
1070 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1071
1072 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001073 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1074 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001075 return E;
1076 }
1077
Jim Grosbach13760bd2015-05-30 01:25:56 +00001078 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001079 }
1080
1081 case MCExpr::Unary: {
1082 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001083 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001084 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001085 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001086 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001087 }
1088
1089 case MCExpr::Binary: {
1090 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001091 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1092 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001093
1094 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001095 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001096
Jim Grosbach4b905842013-09-20 23:08:21 +00001097 if (!LHS)
1098 LHS = BE->getLHS();
1099 if (!RHS)
1100 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001101
Jim Grosbach13760bd2015-05-30 01:25:56 +00001102 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001103 }
1104 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001105
Craig Toppera2886c22012-02-07 05:05:23 +00001106 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001107}
1108
Jim Grosbach4b905842013-09-20 23:08:21 +00001109/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001110///
Jim Grosbachbd164242011-08-20 16:24:13 +00001111/// expr ::= expr &&,|| expr -> lowest.
1112/// expr ::= expr |,^,&,! expr
1113/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1114/// expr ::= expr <<,>> expr
1115/// expr ::= expr +,- expr
1116/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001117/// expr ::= primaryexpr
1118///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001119bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001120 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001121 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001122 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001123 return true;
1124
Daniel Dunbar55f16672010-09-17 02:47:07 +00001125 // As a special case, we support 'a op b @ modifier' by rewriting the
1126 // expression to include the modifier. This is inefficient, but in general we
1127 // expect users to use 'a@modifier op b'.
1128 if (Lexer.getKind() == AsmToken::At) {
1129 Lex();
1130
1131 if (Lexer.isNot(AsmToken::Identifier))
1132 return TokError("unexpected symbol modifier following '@'");
1133
1134 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001135 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001136 if (Variant == MCSymbolRefExpr::VK_Invalid)
1137 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1138
Jim Grosbach4b905842013-09-20 23:08:21 +00001139 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001140 if (!ModifiedRes) {
1141 return TokError("invalid modifier '" + getTok().getIdentifier() +
1142 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001143 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001144
Daniel Dunbar55f16672010-09-17 02:47:07 +00001145 Res = ModifiedRes;
1146 Lex();
1147 }
1148
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001149 // Try to constant fold it up front, if possible.
1150 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001151 if (Res->evaluateAsAbsolute(Value))
1152 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001153
1154 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001155}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001156
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001157bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001158 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001159 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001160}
1161
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001162bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1163 SMLoc &EndLoc) {
1164 if (parseParenExpr(Res, EndLoc))
1165 return true;
1166
1167 for (; ParenDepth > 0; --ParenDepth) {
1168 if (parseBinOpRHS(1, Res, EndLoc))
1169 return true;
1170
1171 // We don't Lex() the last RParen.
1172 // This is the same behavior as parseParenExpression().
1173 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001174 EndLoc = getTok().getEndLoc();
1175 if (parseToken(AsmToken::RParen,
1176 "expected ')' in parentheses expression"))
1177 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001178 }
1179 }
1180 return false;
1181}
1182
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001183bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001184 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001185
Daniel Dunbar75630b32009-06-30 02:10:03 +00001186 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001187 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001188 return true;
1189
Jim Grosbach13760bd2015-05-30 01:25:56 +00001190 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001191 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001192
1193 return false;
1194}
1195
David Majnemer0993e0b2015-10-26 03:15:34 +00001196static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1197 MCBinaryExpr::Opcode &Kind,
1198 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001199 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001200 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001201 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001202
Jim Grosbach4b905842013-09-20 23:08:21 +00001203 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001204 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001205 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001206 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001207 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001208 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001209 return 1;
1210
Jim Grosbach4b905842013-09-20 23:08:21 +00001211 // Low Precedence: |, &, ^
1212 //
1213 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001214 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001215 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001216 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001217 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001218 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001219 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001220 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001221 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001222 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001223
Jim Grosbach4b905842013-09-20 23:08:21 +00001224 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001225 case AsmToken::EqualEqual:
1226 Kind = MCBinaryExpr::EQ;
1227 return 3;
1228 case AsmToken::ExclaimEqual:
1229 case AsmToken::LessGreater:
1230 Kind = MCBinaryExpr::NE;
1231 return 3;
1232 case AsmToken::Less:
1233 Kind = MCBinaryExpr::LT;
1234 return 3;
1235 case AsmToken::LessEqual:
1236 Kind = MCBinaryExpr::LTE;
1237 return 3;
1238 case AsmToken::Greater:
1239 Kind = MCBinaryExpr::GT;
1240 return 3;
1241 case AsmToken::GreaterEqual:
1242 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001243 return 3;
1244
Jim Grosbach4b905842013-09-20 23:08:21 +00001245 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001246 case AsmToken::LessLess:
1247 Kind = MCBinaryExpr::Shl;
1248 return 4;
1249 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001250 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001251 return 4;
1252
Jim Grosbach4b905842013-09-20 23:08:21 +00001253 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001254 case AsmToken::Plus:
1255 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001256 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001257 case AsmToken::Minus:
1258 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001259 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001260
Jim Grosbach4b905842013-09-20 23:08:21 +00001261 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001262 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001263 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001264 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001265 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001266 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001267 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001268 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001269 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001270 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001271 }
1272}
1273
David Majnemer0993e0b2015-10-26 03:15:34 +00001274static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1275 MCBinaryExpr::Opcode &Kind,
1276 bool ShouldUseLogicalShr) {
1277 switch (K) {
1278 default:
1279 return 0; // not a binop.
1280
1281 // Lowest Precedence: &&, ||
1282 case AsmToken::AmpAmp:
1283 Kind = MCBinaryExpr::LAnd;
1284 return 2;
1285 case AsmToken::PipePipe:
1286 Kind = MCBinaryExpr::LOr;
1287 return 1;
1288
1289 // Low Precedence: ==, !=, <>, <, <=, >, >=
1290 case AsmToken::EqualEqual:
1291 Kind = MCBinaryExpr::EQ;
1292 return 3;
1293 case AsmToken::ExclaimEqual:
1294 case AsmToken::LessGreater:
1295 Kind = MCBinaryExpr::NE;
1296 return 3;
1297 case AsmToken::Less:
1298 Kind = MCBinaryExpr::LT;
1299 return 3;
1300 case AsmToken::LessEqual:
1301 Kind = MCBinaryExpr::LTE;
1302 return 3;
1303 case AsmToken::Greater:
1304 Kind = MCBinaryExpr::GT;
1305 return 3;
1306 case AsmToken::GreaterEqual:
1307 Kind = MCBinaryExpr::GTE;
1308 return 3;
1309
1310 // Low Intermediate Precedence: +, -
1311 case AsmToken::Plus:
1312 Kind = MCBinaryExpr::Add;
1313 return 4;
1314 case AsmToken::Minus:
1315 Kind = MCBinaryExpr::Sub;
1316 return 4;
1317
1318 // High Intermediate Precedence: |, &, ^
1319 //
1320 // FIXME: gas seems to support '!' as an infix operator?
1321 case AsmToken::Pipe:
1322 Kind = MCBinaryExpr::Or;
1323 return 5;
1324 case AsmToken::Caret:
1325 Kind = MCBinaryExpr::Xor;
1326 return 5;
1327 case AsmToken::Amp:
1328 Kind = MCBinaryExpr::And;
1329 return 5;
1330
1331 // Highest Precedence: *, /, %, <<, >>
1332 case AsmToken::Star:
1333 Kind = MCBinaryExpr::Mul;
1334 return 6;
1335 case AsmToken::Slash:
1336 Kind = MCBinaryExpr::Div;
1337 return 6;
1338 case AsmToken::Percent:
1339 Kind = MCBinaryExpr::Mod;
1340 return 6;
1341 case AsmToken::LessLess:
1342 Kind = MCBinaryExpr::Shl;
1343 return 6;
1344 case AsmToken::GreaterGreater:
1345 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1346 return 6;
1347 }
1348}
1349
1350unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1351 MCBinaryExpr::Opcode &Kind) {
1352 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1353 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1354 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1355}
1356
Jim Grosbach4b905842013-09-20 23:08:21 +00001357/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001358/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001359bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001360 SMLoc &EndLoc) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001361 while (1) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001362 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001363 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001364
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001365 // If the next token is lower precedence than we are allowed to eat, return
1366 // successfully with what we ate already.
1367 if (TokPrec < Precedence)
1368 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001369
Sean Callanan686ed8d2010-01-19 20:22:31 +00001370 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001371
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001372 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001373 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001374 if (parsePrimaryExpr(RHS, EndLoc))
1375 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001376
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001377 // If BinOp binds less tightly with RHS than the operator after RHS, let
1378 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001379 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001380 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001381 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1382 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001383
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001384 // Merge LHS and RHS according to operator.
Jim Grosbach13760bd2015-05-30 01:25:56 +00001385 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001386 }
1387}
1388
Chris Lattner36e02122009-06-21 20:54:55 +00001389/// ParseStatement:
1390/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001391/// ::= Label* Directive ...Operands... EndOfStatement
1392/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001393bool AsmParser::parseStatement(ParseStatementInfo &Info,
1394 MCAsmParserSemaCallback *SI) {
Nirav Davefd910412016-06-17 16:06:17 +00001395 // Eat initial spaces and comments
1396 while (Lexer.is(AsmToken::Space))
1397 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001398 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001399 // if this is a line comment we can drop it safely
1400 if (getTok().getString().front() == '\r' ||
1401 getTok().getString().front() == '\n')
1402 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001403 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001404 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001405 }
Nirav Davefd910412016-06-17 16:06:17 +00001406 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001407 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001408 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001409 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001410 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001411 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001412 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001413 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001414 if (Lexer.is(AsmToken::Integer)) {
1415 LocalLabelVal = getTok().getIntVal();
1416 if (LocalLabelVal < 0) {
1417 if (!TheCondState.Ignore)
1418 return TokError("unexpected token at start of statement");
1419 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001420 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001421 IDVal = getTok().getString();
1422 Lex(); // Consume the integer token to be used as an identifier token.
1423 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands41b4a6b2010-07-12 08:16:59 +00001424 if (!TheCondState.Ignore)
1425 return TokError("unexpected token at start of statement");
Kevin Enderby0510b482010-05-17 23:08:19 +00001426 }
1427 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001428 } else if (Lexer.is(AsmToken::Dot)) {
1429 // Treat '.' as a valid identifier in this context.
1430 Lex();
1431 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001432 } else if (Lexer.is(AsmToken::LCurly)) {
1433 // Treat '{' as a valid identifier in this context.
1434 Lex();
1435 IDVal = "{";
1436
1437 } else if (Lexer.is(AsmToken::RCurly)) {
1438 // Treat '}' as a valid identifier in this context.
1439 Lex();
1440 IDVal = "}";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001441 } else if (parseIdentifier(IDVal)) {
Chris Lattner926885c2010-04-17 18:14:27 +00001442 if (!TheCondState.Ignore)
1443 return TokError("unexpected token at start of statement");
1444 IDVal = "";
1445 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001446
Chris Lattner926885c2010-04-17 18:14:27 +00001447 // Handle conditional assembly here before checking for skipping. We
1448 // have to do this so that .endif isn't skipped in a ".if 0" block for
1449 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001450 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001451 DirectiveKindMap.find(IDVal);
1452 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1453 ? DK_NO_DIRECTIVE
1454 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001455 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001456 default:
1457 break;
1458 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001459 case DK_IFEQ:
1460 case DK_IFGE:
1461 case DK_IFGT:
1462 case DK_IFLE:
1463 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001464 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001465 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001466 case DK_IFB:
1467 return parseDirectiveIfb(IDLoc, true);
1468 case DK_IFNB:
1469 return parseDirectiveIfb(IDLoc, false);
1470 case DK_IFC:
1471 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001472 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001473 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001474 case DK_IFNC:
1475 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001476 case DK_IFNES:
1477 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001478 case DK_IFDEF:
1479 return parseDirectiveIfdef(IDLoc, true);
1480 case DK_IFNDEF:
1481 case DK_IFNOTDEF:
1482 return parseDirectiveIfdef(IDLoc, false);
1483 case DK_ELSEIF:
1484 return parseDirectiveElseIf(IDLoc);
1485 case DK_ELSE:
1486 return parseDirectiveElse(IDLoc);
1487 case DK_ENDIF:
1488 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001489 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001490
Eli Bendersky88024712013-01-16 19:32:36 +00001491 // Ignore the statement if in the middle of inactive conditional
1492 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001493 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001494 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001495 return false;
1496 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001497
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001498 // FIXME: Recurse on local labels?
1499
1500 // See what kind of statement we have.
1501 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001502 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001503 if (!getTargetParser().isLabel(ID))
1504 break;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001505 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00001506
Chris Lattner36e02122009-06-21 20:54:55 +00001507 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001508 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001509
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001510 // Diagnose attempt to use '.' as a label.
1511 if (IDVal == ".")
1512 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1513
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001514 // Diagnose attempt to use a variable as a label.
1515 //
1516 // FIXME: Diagnostics. Note the location of the definition as a label.
1517 // FIXME: This doesn't diagnose assignment to a symbol which has been
1518 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001519 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001520 if (LocalLabelVal == -1) {
1521 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001522 StringRef RewrittenLabel =
1523 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1524 assert(RewrittenLabel.size() &&
1525 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001526 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1527 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001528 IDVal = RewrittenLabel;
1529 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001530 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001531 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001532 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
David Majnemer58cb80c2014-12-24 10:27:50 +00001533
1534 Sym->redefineIfPossible();
1535
Daniel Dunbardeb7ba92010-05-05 19:01:00 +00001536 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001537 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencer530ce852010-10-09 11:00:50 +00001538
Nirav Dave8ea792d2016-07-13 14:03:12 +00001539 // Consume any end of statement token, if present, to avoid spurious
1540 // AddBlankLine calls().
1541 if (getTok().is(AsmToken::EndOfStatement)) {
1542 Lex();
1543 }
1544
Daniel Dunbare73b2672009-08-26 22:13:22 +00001545 // Emit the label.
Chad Rosierf3feab32013-01-07 20:34:12 +00001546 if (!ParsingInlineAsm)
1547 Out.EmitLabel(Sym);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001548
Kevin Enderbye7739d42011-12-09 18:09:40 +00001549 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001550 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001551 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001552 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1553 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001554
Tim Northover1744d0a2013-10-25 12:49:50 +00001555 getTargetParser().onLabelParsed(Sym);
1556
Nirav Dave8ea792d2016-07-13 14:03:12 +00001557
Daniel Dunbar8271d1bb2010-05-23 18:36:34 +00001558
Eli Friedman0f4871d2012-10-22 23:58:19 +00001559 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001560 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001561
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001562 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001563 if (!getTargetParser().equalIsAsmAssignment())
1564 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001565 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001566 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001567
Jim Grosbach4b905842013-09-20 23:08:21 +00001568 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001569
1570 default: // Normal instruction or directive.
1571 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001572 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001573
1574 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001575 if (areMacrosEnabled())
1576 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1577 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001578 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001579
Michael J. Spencer530ce852010-10-09 11:00:50 +00001580 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001581
Eli Bendersky17233942013-01-15 22:59:42 +00001582 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001583 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001584 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001585 //
Eli Bendersky17233942013-01-15 22:59:42 +00001586 // 1. The target-specific assembly parser. Some directives are target
1587 // specific or may potentially behave differently on certain targets.
1588 // 2. Asm parser extensions. For example, platform-specific parsers
1589 // (like the ELF parser) register themselves as extensions.
1590 // 3. The generic directive parser implemented by this class. These are
1591 // all the directives that behave in a target and platform independent
1592 // manner, or at least have a default behavior that's shared between
1593 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001594
Oliver Stannard21718282016-07-26 14:19:47 +00001595 getTargetParser().flushPendingInstructions(getStreamer());
1596
Eli Bendersky17233942013-01-15 22:59:42 +00001597 // First query the target-specific parser. It will return 'true' if it
1598 // isn't interested in this directive.
Akira Hatanakad3590752012-07-05 19:09:33 +00001599 if (!getTargetParser().ParseDirective(ID))
1600 return false;
1601
Alp Tokercb402912014-01-24 17:20:08 +00001602 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001603 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001604 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1605 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001606 if (Handler.first)
1607 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1608
1609 // Finally, if no one else is interested in this directive, it must be
1610 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001611 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001612 default:
1613 break;
1614 case DK_SET:
1615 case DK_EQU:
1616 return parseDirectiveSet(IDVal, true);
1617 case DK_EQUIV:
1618 return parseDirectiveSet(IDVal, false);
1619 case DK_ASCII:
1620 return parseDirectiveAscii(IDVal, false);
1621 case DK_ASCIZ:
1622 case DK_STRING:
1623 return parseDirectiveAscii(IDVal, true);
1624 case DK_BYTE:
1625 return parseDirectiveValue(1);
1626 case DK_SHORT:
1627 case DK_VALUE:
1628 case DK_2BYTE:
1629 return parseDirectiveValue(2);
1630 case DK_LONG:
1631 case DK_INT:
1632 case DK_4BYTE:
1633 return parseDirectiveValue(4);
1634 case DK_QUAD:
1635 case DK_8BYTE:
1636 return parseDirectiveValue(8);
David Woodhoused6de0d92014-02-01 16:20:59 +00001637 case DK_OCTA:
1638 return parseDirectiveOctaValue();
Jim Grosbach4b905842013-09-20 23:08:21 +00001639 case DK_SINGLE:
1640 case DK_FLOAT:
1641 return parseDirectiveRealValue(APFloat::IEEEsingle);
1642 case DK_DOUBLE:
1643 return parseDirectiveRealValue(APFloat::IEEEdouble);
1644 case DK_ALIGN: {
1645 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1646 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1647 }
1648 case DK_ALIGN32: {
1649 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1650 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1651 }
1652 case DK_BALIGN:
1653 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1654 case DK_BALIGNW:
1655 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1656 case DK_BALIGNL:
1657 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1658 case DK_P2ALIGN:
1659 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1660 case DK_P2ALIGNW:
1661 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1662 case DK_P2ALIGNL:
1663 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1664 case DK_ORG:
1665 return parseDirectiveOrg();
1666 case DK_FILL:
1667 return parseDirectiveFill();
1668 case DK_ZERO:
1669 return parseDirectiveZero();
1670 case DK_EXTERN:
1671 eatToEndOfStatement(); // .extern is the default, ignore it.
1672 return false;
1673 case DK_GLOBL:
1674 case DK_GLOBAL:
1675 return parseDirectiveSymbolAttribute(MCSA_Global);
1676 case DK_LAZY_REFERENCE:
1677 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1678 case DK_NO_DEAD_STRIP:
1679 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1680 case DK_SYMBOL_RESOLVER:
1681 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1682 case DK_PRIVATE_EXTERN:
1683 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1684 case DK_REFERENCE:
1685 return parseDirectiveSymbolAttribute(MCSA_Reference);
1686 case DK_WEAK_DEFINITION:
1687 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1688 case DK_WEAK_REFERENCE:
1689 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1690 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1691 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1692 case DK_COMM:
1693 case DK_COMMON:
1694 return parseDirectiveComm(/*IsLocal=*/false);
1695 case DK_LCOMM:
1696 return parseDirectiveComm(/*IsLocal=*/true);
1697 case DK_ABORT:
1698 return parseDirectiveAbort();
1699 case DK_INCLUDE:
1700 return parseDirectiveInclude();
1701 case DK_INCBIN:
1702 return parseDirectiveIncbin();
1703 case DK_CODE16:
1704 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001705 return TokError(Twine(IDVal) +
1706 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001707 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001708 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001709 case DK_IRP:
1710 return parseDirectiveIrp(IDLoc);
1711 case DK_IRPC:
1712 return parseDirectiveIrpc(IDLoc);
1713 case DK_ENDR:
1714 return parseDirectiveEndr(IDLoc);
1715 case DK_BUNDLE_ALIGN_MODE:
1716 return parseDirectiveBundleAlignMode();
1717 case DK_BUNDLE_LOCK:
1718 return parseDirectiveBundleLock();
1719 case DK_BUNDLE_UNLOCK:
1720 return parseDirectiveBundleUnlock();
1721 case DK_SLEB128:
1722 return parseDirectiveLEB128(true);
1723 case DK_ULEB128:
1724 return parseDirectiveLEB128(false);
1725 case DK_SPACE:
1726 case DK_SKIP:
1727 return parseDirectiveSpace(IDVal);
1728 case DK_FILE:
1729 return parseDirectiveFile(IDLoc);
1730 case DK_LINE:
1731 return parseDirectiveLine();
1732 case DK_LOC:
1733 return parseDirectiveLoc();
1734 case DK_STABS:
1735 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001736 case DK_CV_FILE:
1737 return parseDirectiveCVFile();
1738 case DK_CV_LOC:
1739 return parseDirectiveCVLoc();
1740 case DK_CV_LINETABLE:
1741 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00001742 case DK_CV_INLINE_LINETABLE:
1743 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00001744 case DK_CV_DEF_RANGE:
1745 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001746 case DK_CV_STRINGTABLE:
1747 return parseDirectiveCVStringTable();
1748 case DK_CV_FILECHECKSUMS:
1749 return parseDirectiveCVFileChecksums();
Jim Grosbach4b905842013-09-20 23:08:21 +00001750 case DK_CFI_SECTIONS:
1751 return parseDirectiveCFISections();
1752 case DK_CFI_STARTPROC:
1753 return parseDirectiveCFIStartProc();
1754 case DK_CFI_ENDPROC:
1755 return parseDirectiveCFIEndProc();
1756 case DK_CFI_DEF_CFA:
1757 return parseDirectiveCFIDefCfa(IDLoc);
1758 case DK_CFI_DEF_CFA_OFFSET:
1759 return parseDirectiveCFIDefCfaOffset();
1760 case DK_CFI_ADJUST_CFA_OFFSET:
1761 return parseDirectiveCFIAdjustCfaOffset();
1762 case DK_CFI_DEF_CFA_REGISTER:
1763 return parseDirectiveCFIDefCfaRegister(IDLoc);
1764 case DK_CFI_OFFSET:
1765 return parseDirectiveCFIOffset(IDLoc);
1766 case DK_CFI_REL_OFFSET:
1767 return parseDirectiveCFIRelOffset(IDLoc);
1768 case DK_CFI_PERSONALITY:
1769 return parseDirectiveCFIPersonalityOrLsda(true);
1770 case DK_CFI_LSDA:
1771 return parseDirectiveCFIPersonalityOrLsda(false);
1772 case DK_CFI_REMEMBER_STATE:
1773 return parseDirectiveCFIRememberState();
1774 case DK_CFI_RESTORE_STATE:
1775 return parseDirectiveCFIRestoreState();
1776 case DK_CFI_SAME_VALUE:
1777 return parseDirectiveCFISameValue(IDLoc);
1778 case DK_CFI_RESTORE:
1779 return parseDirectiveCFIRestore(IDLoc);
1780 case DK_CFI_ESCAPE:
1781 return parseDirectiveCFIEscape();
1782 case DK_CFI_SIGNAL_FRAME:
1783 return parseDirectiveCFISignalFrame();
1784 case DK_CFI_UNDEFINED:
1785 return parseDirectiveCFIUndefined(IDLoc);
1786 case DK_CFI_REGISTER:
1787 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00001788 case DK_CFI_WINDOW_SAVE:
1789 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00001790 case DK_MACROS_ON:
1791 case DK_MACROS_OFF:
1792 return parseDirectiveMacrosOnOff(IDVal);
1793 case DK_MACRO:
1794 return parseDirectiveMacro(IDLoc);
Nico Weber155dccd12014-07-24 17:08:39 +00001795 case DK_EXITM:
1796 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001797 case DK_ENDM:
1798 case DK_ENDMACRO:
1799 return parseDirectiveEndMacro(IDVal);
1800 case DK_PURGEM:
1801 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00001802 case DK_END:
1803 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00001804 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00001805 return parseDirectiveError(IDLoc, false);
1806 case DK_ERROR:
1807 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00001808 case DK_WARNING:
1809 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00001810 case DK_RELOC:
1811 return parseDirectiveReloc(IDLoc);
Eli Friedman20b02642010-07-19 04:17:25 +00001812 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00001813
Jim Grosbach758e0cc2012-05-01 18:38:27 +00001814 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00001815 }
Chris Lattner36e02122009-06-21 20:54:55 +00001816
Chad Rosierc7f552c2013-02-12 21:33:51 +00001817 // __asm _emit or __asm __emit
1818 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1819 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001820 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00001821
1822 // __asm align
1823 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001824 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00001825
Michael Zuckerman02ecd432015-12-13 17:07:23 +00001826 if (ParsingInlineAsm && (IDVal == "even"))
1827 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001828 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00001829
Chris Lattner7cbfa442010-05-19 23:34:33 +00001830 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00001831 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00001832 ParseInstructionInfo IInfo(Info.AsmRewrites);
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001833 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001834 Info.ParsedOperands);
Chad Rosier149e8e02012-12-12 22:45:52 +00001835 Info.ParseError = HadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00001836
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001837 // Dump the parsed representation, if requested.
1838 if (getShowParsedOperands()) {
1839 SmallString<256> Str;
1840 raw_svector_ostream OS(Str);
1841 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001842 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001843 if (i != 0)
1844 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001845 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001846 }
1847 OS << "]";
1848
Jim Grosbach4b905842013-09-20 23:08:21 +00001849 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001850 }
1851
Oliver Stannard8b273082014-06-19 15:52:37 +00001852 // If we are generating dwarf for the current section then generate a .loc
1853 // directive for the instruction.
Kevin Enderby6469fc22011-11-01 22:27:22 +00001854 if (!HadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00001855 getContext().getGenDwarfSectionSyms().count(
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00001856 getStreamer().getCurrentSection().first)) {
1857 unsigned Line;
1858 if (ActiveMacros.empty())
1859 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1860 else
Frederic Riss16238d92015-06-25 21:57:33 +00001861 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
1862 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001863
Eli Bendersky88024712013-01-16 19:32:36 +00001864 // If we previously parsed a cpp hash file line comment then make sure the
1865 // current Dwarf File is for the CppHashFilename if not then emit the
1866 // Dwarf File table for it and adjust the line number for the .loc.
Tim Northoverc0bef992016-04-13 19:46:54 +00001867 if (CppHashInfo.Filename.size()) {
David Blaikiec714ef42014-03-17 01:52:11 +00001868 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00001869 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00001870 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001871
Jim Grosbach4b905842013-09-20 23:08:21 +00001872 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1873 // cache with the different Loc from the call above we save the last
1874 // info we queried here with SrcMgr.FindLineNumber().
1875 unsigned CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00001876 if (LastQueryIDLoc == CppHashInfo.Loc &&
1877 LastQueryBuffer == CppHashInfo.Buf)
Jim Grosbach4b905842013-09-20 23:08:21 +00001878 CppHashLocLineNo = LastQueryLine;
1879 else {
Tim Northoverc0bef992016-04-13 19:46:54 +00001880 CppHashLocLineNo =
1881 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Jim Grosbach4b905842013-09-20 23:08:21 +00001882 LastQueryLine = CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00001883 LastQueryIDLoc = CppHashInfo.Loc;
1884 LastQueryBuffer = CppHashInfo.Buf;
Jim Grosbach4b905842013-09-20 23:08:21 +00001885 }
Tim Northoverc0bef992016-04-13 19:46:54 +00001886 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00001887 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001888
Jim Grosbach4b905842013-09-20 23:08:21 +00001889 getStreamer().EmitDwarfLocDirective(
1890 getContext().getGenDwarfFileNumber(), Line, 0,
1891 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1892 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00001893 }
1894
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00001895 // If parsing succeeded, match the instruction.
Chad Rosier49963552012-10-13 00:26:04 +00001896 if (!HadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00001897 uint64_t ErrorInfo;
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001898 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1899 Info.ParsedOperands, Out,
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00001900 ErrorInfo, ParsingInlineAsm);
Chad Rosier49963552012-10-13 00:26:04 +00001901 }
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001902
Chris Lattnera2a9d162010-09-11 16:18:25 +00001903 // Don't skip the rest of the line, the instruction parser is responsible for
1904 // that.
1905 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00001906}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00001907
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00001908// Parse and erase curly braces marking block start/end
1909bool
1910AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
1911 // Identify curly brace marking block start/end
1912 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
1913 return false;
1914
1915 SMLoc StartLoc = Lexer.getLoc();
1916 Lex(); // Eat the brace
1917 if (Lexer.is(AsmToken::EndOfStatement))
1918 Lex(); // Eat EndOfStatement following the brace
1919
1920 // Erase the block start/end brace from the output asm string
1921 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
1922 StartLoc.getPointer());
1923 return true;
1924}
1925
Jim Grosbach4b905842013-09-20 23:08:21 +00001926/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00001927/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00001928bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00001929 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00001930 // Lexer only ever emits HashDirective if it fully formed if it's
1931 // done the checking already so this is an internal error.
1932 assert(getTok().is(AsmToken::Integer) &&
1933 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00001934 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00001935 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00001936 assert(getTok().is(AsmToken::String) &&
1937 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00001938 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00001939 Lex();
Kevin Enderby72553612011-09-13 23:45:18 +00001940 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00001941 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00001942
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001943 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00001944 CppHashInfo.Loc = L;
1945 CppHashInfo.Filename = Filename;
1946 CppHashInfo.LineNumber = LineNumber;
1947 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00001948 return false;
1949}
1950
Jim Grosbach4b905842013-09-20 23:08:21 +00001951/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001952/// for the Filename and LineNo if any in the diagnostic.
1953void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001954 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001955 raw_ostream &OS = errs();
1956
1957 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00001958 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00001959 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1960 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00001961 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001962
Jim Grosbach4b905842013-09-20 23:08:21 +00001963 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001964 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00001965 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1966 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1967 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001968 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1969 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001970 }
1971
Eric Christophera7c32732012-12-18 00:30:54 +00001972 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001973 // manager changed or buffer changed (like in a nested include) then just
1974 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00001975 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001976 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00001977 if (Parser->SavedDiagHandler)
1978 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1979 else
Craig Topper353eda42014-04-24 06:44:33 +00001980 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001981 return;
1982 }
1983
Eric Christophera7c32732012-12-18 00:30:54 +00001984 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00001985 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
1986 // for the diagnostic.
1987 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001988
1989 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1990 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00001991 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00001992 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00001993 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001994
Jim Grosbach4b905842013-09-20 23:08:21 +00001995 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1996 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00001997 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001998
Benjamin Kramer47f5e302011-10-16 10:48:29 +00001999 if (Parser->SavedDiagHandler)
2000 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2001 else
Craig Topper353eda42014-04-24 06:44:33 +00002002 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002003}
2004
Rafael Espindola2c064482012-08-21 18:29:30 +00002005// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2006// difference being that that function accepts '@' as part of identifiers and
2007// we can't do that. AsmLexer.cpp should probably be changed to handle
2008// '@' as a special case when needed.
2009static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002010 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2011 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002012}
2013
Rafael Espindola34b9c512012-06-03 23:57:14 +00002014bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002015 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002016 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002017 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002018 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002019 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002020 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002021 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002022
Preston Gurd05500642012-09-19 20:36:12 +00002023 // A macro without parameters is handled differently on Darwin:
2024 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002025 while (!Body.empty()) {
2026 // Scan for the next substitution.
2027 std::size_t End = Body.size(), Pos = 0;
2028 for (; Pos != End; ++Pos) {
2029 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002030 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002031 // This macro has no parameters, look for $0, $1, etc.
2032 if (Body[Pos] != '$' || Pos + 1 == End)
2033 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002034
Rafael Espindola1134ab232011-06-05 02:43:45 +00002035 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002036 if (Next == '$' || Next == 'n' ||
2037 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002038 break;
2039 } else {
2040 // This macro has parameters, look for \foo, \bar, etc.
2041 if (Body[Pos] == '\\' && Pos + 1 != End)
2042 break;
2043 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002044 }
2045
2046 // Add the prefix.
2047 OS << Body.slice(0, Pos);
2048
2049 // Check if we reached the end.
2050 if (Pos == End)
2051 break;
2052
Benjamin Kramer513e7442014-02-20 13:36:32 +00002053 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002054 switch (Body[Pos + 1]) {
2055 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002056 case '$':
2057 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002058 break;
2059
Jim Grosbach4b905842013-09-20 23:08:21 +00002060 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002061 case 'n':
2062 OS << A.size();
2063 break;
2064
Jim Grosbach4b905842013-09-20 23:08:21 +00002065 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002066 default: {
2067 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002068 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002069 if (Index >= A.size())
2070 break;
2071
2072 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002073 for (const AsmToken &Token : A[Index])
2074 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002075 break;
2076 }
2077 }
2078 Pos += 2;
2079 } else {
2080 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002081
2082 // Check for the \@ pseudo-variable.
2083 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002084 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002085 else
2086 while (isIdentifierChar(Body[I]) && I + 1 != End)
2087 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002088
Jim Grosbach4b905842013-09-20 23:08:21 +00002089 const char *Begin = Body.data() + Pos + 1;
2090 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002091 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002092
Toma Tabacu217116e2015-04-27 10:50:29 +00002093 if (Argument == "@") {
2094 OS << NumOfMacroInstantiations;
2095 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002096 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002097 for (; Index < NParameters; ++Index)
2098 if (Parameters[Index].Name == Argument)
2099 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002100
Toma Tabacu217116e2015-04-27 10:50:29 +00002101 if (Index == NParameters) {
2102 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2103 Pos += 3;
2104 else {
2105 OS << '\\' << Argument;
2106 Pos = I;
2107 }
2108 } else {
2109 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002110 for (const AsmToken &Token : A[Index])
Toma Tabacu217116e2015-04-27 10:50:29 +00002111 // We expect no quotes around the string's contents when
2112 // parsing for varargs.
Craig Topper84008482015-10-10 05:38:14 +00002113 if (Token.getKind() != AsmToken::String || VarargParameter)
2114 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002115 else
Craig Topper84008482015-10-10 05:38:14 +00002116 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002117
2118 Pos += 1 + Argument.size();
2119 }
Preston Gurd05500642012-09-19 20:36:12 +00002120 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002121 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002122 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002123 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002124 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002125
Rafael Espindola1134ab232011-06-05 02:43:45 +00002126 return false;
2127}
Daniel Dunbar43235712010-07-18 18:54:11 +00002128
Nico Weber2a8f9222014-07-24 16:29:04 +00002129MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002130 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002131 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002132 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002133
Jim Grosbach4b905842013-09-20 23:08:21 +00002134static bool isOperator(AsmToken::TokenKind kind) {
2135 switch (kind) {
2136 default:
2137 return false;
2138 case AsmToken::Plus:
2139 case AsmToken::Minus:
2140 case AsmToken::Tilde:
2141 case AsmToken::Slash:
2142 case AsmToken::Star:
2143 case AsmToken::Dot:
2144 case AsmToken::Equal:
2145 case AsmToken::EqualEqual:
2146 case AsmToken::Pipe:
2147 case AsmToken::PipePipe:
2148 case AsmToken::Caret:
2149 case AsmToken::Amp:
2150 case AsmToken::AmpAmp:
2151 case AsmToken::Exclaim:
2152 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002153 case AsmToken::Less:
2154 case AsmToken::LessEqual:
2155 case AsmToken::LessLess:
2156 case AsmToken::LessGreater:
2157 case AsmToken::Greater:
2158 case AsmToken::GreaterEqual:
2159 case AsmToken::GreaterGreater:
2160 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002161 }
2162}
2163
David Majnemer16252452014-01-29 00:07:39 +00002164namespace {
2165class AsmLexerSkipSpaceRAII {
2166public:
2167 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2168 Lexer.setSkipSpace(SkipSpace);
2169 }
2170
2171 ~AsmLexerSkipSpaceRAII() {
2172 Lexer.setSkipSpace(true);
2173 }
2174
2175private:
2176 AsmLexer &Lexer;
2177};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002178}
David Majnemer16252452014-01-29 00:07:39 +00002179
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002180bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2181
2182 if (Vararg) {
2183 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2184 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002185 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002186 }
2187 return false;
2188 }
2189
Rafael Espindola768b41c2012-06-15 14:02:34 +00002190 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002191
David Majnemer16252452014-01-29 00:07:39 +00002192 // Darwin doesn't use spaces to delmit arguments.
2193 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002194
Scott Egertona1fa68a2016-02-11 13:48:49 +00002195 bool SpaceEaten;
2196
Rafael Espindola768b41c2012-06-15 14:02:34 +00002197 for (;;) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002198 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002199 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002200 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002201
Scott Egertona1fa68a2016-02-11 13:48:49 +00002202 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002203
Scott Egertona1fa68a2016-02-11 13:48:49 +00002204 if (Lexer.is(AsmToken::Comma))
2205 break;
2206
2207 if (Lexer.is(AsmToken::Space)) {
2208 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002209 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002210 }
Preston Gurd05500642012-09-19 20:36:12 +00002211
2212 // Spaces can delimit parameters, but could also be part an expression.
2213 // If the token after a space is an operator, add the token and the next
2214 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002215 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002216 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002217 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002218 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002219
Scott Egertona1fa68a2016-02-11 13:48:49 +00002220 // Whitespace after an operator can be ignored.
2221 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002222 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002223
2224 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002225 }
2226 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002227 if (SpaceEaten)
2228 break;
Preston Gurd05500642012-09-19 20:36:12 +00002229 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002230
Jim Grosbach4b905842013-09-20 23:08:21 +00002231 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002232 // to be able to fill in the remaining default parameter values
2233 if (Lexer.is(AsmToken::EndOfStatement))
2234 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002235
2236 // Adjust the current parentheses level.
2237 if (Lexer.is(AsmToken::LParen))
2238 ++ParenLevel;
2239 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2240 --ParenLevel;
2241
2242 // Append the token to the current argument list.
2243 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002244 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002245 }
Preston Gurd05500642012-09-19 20:36:12 +00002246
Rafael Espindola768b41c2012-06-15 14:02:34 +00002247 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002248 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002249 return false;
2250}
2251
2252// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002253bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002254 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002255 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002256 bool NamedParametersFound = false;
2257 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002258
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002259 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002260 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002261
Rafael Espindola768b41c2012-06-15 14:02:34 +00002262 // Parse two kinds of macro invocations:
2263 // - macros defined without any parameters accept an arbitrary number of them
2264 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002265 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002266 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2267 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002268 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002269 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002270
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002271 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002272 if (parseIdentifier(FA.Name)) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002273 Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002274 eatToEndOfStatement();
2275 return true;
2276 }
2277
Nirav Davea645433c2016-07-18 15:24:03 +00002278 if (Lexer.isNot(AsmToken::Equal)) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002279 TokError("expected '=' after formal parameter identifier");
2280 eatToEndOfStatement();
2281 return true;
2282 }
2283 Lex();
2284
2285 NamedParametersFound = true;
2286 }
2287
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002288 if (NamedParametersFound && FA.Name.empty()) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002289 Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002290 eatToEndOfStatement();
2291 return true;
2292 }
2293
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002294 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2295 if (parseMacroArgument(FA.Value, Vararg))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002296 return true;
2297
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002298 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002299 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002300 unsigned FAI = 0;
2301 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002302 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002303 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002304
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002305 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002306 assert(M && "expected macro to be defined");
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002307 Error(IDLoc,
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002308 "parameter named '" + FA.Name + "' does not exist for macro '" +
Saleem Abdulrasool3f44cd72014-03-17 17:13:57 +00002309 M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002310 return true;
2311 }
2312 PI = FAI;
2313 }
2314
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002315 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002316 if (A.size() <= PI)
2317 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002318 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002319
2320 if (FALocs.size() <= PI)
2321 FALocs.resize(PI + 1);
2322
2323 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002324 }
Jim Grosbach206661622012-07-30 22:44:17 +00002325
Preston Gurd242ed3152012-09-19 20:29:04 +00002326 // At the end of the statement, fill in remaining arguments that have
2327 // default values. If there aren't any, then the next argument is
2328 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002329 if (Lexer.is(AsmToken::EndOfStatement)) {
2330 bool Failure = false;
2331 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2332 if (A[FAI].empty()) {
2333 if (M->Parameters[FAI].Required) {
2334 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2335 "missing value for required parameter "
2336 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2337 Failure = true;
2338 }
2339
2340 if (!M->Parameters[FAI].Value.empty())
2341 A[FAI] = M->Parameters[FAI].Value;
2342 }
2343 }
2344 return Failure;
2345 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002346
2347 if (Lexer.is(AsmToken::Comma))
2348 Lex();
2349 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002350
2351 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002352}
2353
Jim Grosbach4b905842013-09-20 23:08:21 +00002354const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002355 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2356 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002357}
2358
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002359void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2360 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002361}
2362
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002363void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002364
Jim Grosbach4b905842013-09-20 23:08:21 +00002365bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbar43235712010-07-18 18:54:11 +00002366 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2367 // this, although we should protect against infinite loops.
2368 if (ActiveMacros.size() == 20)
2369 return TokError("macros cannot be nested more than 20 levels deep");
2370
Eli Bendersky38274122013-01-14 23:22:36 +00002371 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002372 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002373 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002374
Rafael Espindola1134ab232011-06-05 02:43:45 +00002375 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2376 // to hold the macro body with substitutions.
2377 SmallString<256> Buf;
2378 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002379 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002380
Toma Tabacu217116e2015-04-27 10:50:29 +00002381 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002382 return true;
2383
Eli Bendersky38274122013-01-14 23:22:36 +00002384 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002385 // instantiation.
2386 OS << ".endmacro\n";
2387
Rafael Espindola3560ff22014-08-27 20:03:13 +00002388 std::unique_ptr<MemoryBuffer> Instantiation =
2389 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002390
Daniel Dunbar43235712010-07-18 18:54:11 +00002391 // Create the macro instantiation object and add to the current macro
2392 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002393 MacroInstantiation *MI = new MacroInstantiation(
2394 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002395 ActiveMacros.push_back(MI);
2396
Toma Tabacu217116e2015-04-27 10:50:29 +00002397 ++NumOfMacroInstantiations;
2398
Daniel Dunbar43235712010-07-18 18:54:11 +00002399 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002400 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002401 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002402 Lex();
2403
2404 return false;
2405}
2406
Jim Grosbach4b905842013-09-20 23:08:21 +00002407void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002408 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002409 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002410 Lex();
2411
2412 // Pop the instantiation entry.
2413 delete ActiveMacros.back();
2414 ActiveMacros.pop_back();
2415}
2416
Jim Grosbach4b905842013-09-20 23:08:21 +00002417bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002418 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002419 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002420 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002421 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2422 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002423 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002424
Pete Cooper80d21cb2015-06-22 19:35:57 +00002425 if (!Sym) {
2426 // In the case where we parse an expression starting with a '.', we will
2427 // not generate an error, nor will we create a symbol. In this case we
2428 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002429 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002430 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002431
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002432 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002433 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002434 if (NoDeadStrip)
2435 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2436
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002437 return false;
2438}
2439
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002440/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002441/// ::= identifier
2442/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002443bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002444 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002445 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2446 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002447 // handle this as a context dependent token, instead we detect adjacent tokens
2448 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002449 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2450 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002451
Hans Wennborgce69d772013-10-18 20:46:28 +00002452 // Consume the prefix character, and check for a following identifier.
Nirav Dave1180e6892016-06-02 17:15:05 +00002453 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002454 if (Lexer.isNot(AsmToken::Identifier))
2455 return true;
2456
Hans Wennborgce69d772013-10-18 20:46:28 +00002457 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2458 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002459 return true;
2460
2461 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002462 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002463 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002464 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002465 return false;
2466 }
2467
Jim Grosbach4b905842013-09-20 23:08:21 +00002468 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002469 return true;
2470
Sean Callanan936b0d32010-01-19 21:44:56 +00002471 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002472
Sean Callanan686ed8d2010-01-19 20:22:31 +00002473 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002474
2475 return false;
2476}
2477
Jim Grosbach4b905842013-09-20 23:08:21 +00002478/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002479/// ::= .equ identifier ',' expression
2480/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002481/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002482bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002483 StringRef Name;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002484
Nirav Davea645433c2016-07-18 15:24:03 +00002485 if (check(parseIdentifier(Name),
2486 "expected identifier after '" + Twine(IDVal) + "'") ||
2487 parseToken(AsmToken::Comma, "unexpected token in '" + Twine(IDVal) + "'"))
2488 return true;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002489
Jim Grosbach4b905842013-09-20 23:08:21 +00002490 return parseAssignment(Name, allow_redef, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002491}
2492
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002493bool AsmParser::parseEscapedString(std::string &Data) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002494 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbaref668c12009-08-14 18:19:52 +00002495
2496 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002497 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002498 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2499 if (Str[i] != '\\') {
2500 Data += Str[i];
2501 continue;
2502 }
2503
2504 // Recognize escaped characters. Note that this escape semantics currently
2505 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2506 ++i;
2507 if (i == e)
2508 return TokError("unexpected backslash at end of string");
2509
2510 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002511 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002512 // Consume up to three octal characters.
2513 unsigned Value = Str[i] - '0';
2514
Jim Grosbach4b905842013-09-20 23:08:21 +00002515 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002516 ++i;
2517 Value = Value * 8 + (Str[i] - '0');
2518
Jim Grosbach4b905842013-09-20 23:08:21 +00002519 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002520 ++i;
2521 Value = Value * 8 + (Str[i] - '0');
2522 }
2523 }
2524
2525 if (Value > 255)
2526 return TokError("invalid octal escape sequence (out of range)");
2527
Jim Grosbach4b905842013-09-20 23:08:21 +00002528 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002529 continue;
2530 }
2531
2532 // Otherwise recognize individual escapes.
2533 switch (Str[i]) {
2534 default:
2535 // Just reject invalid escape sequences for now.
2536 return TokError("invalid escape sequence (unrecognized character)");
2537
2538 case 'b': Data += '\b'; break;
2539 case 'f': Data += '\f'; break;
2540 case 'n': Data += '\n'; break;
2541 case 'r': Data += '\r'; break;
2542 case 't': Data += '\t'; break;
2543 case '"': Data += '"'; break;
2544 case '\\': Data += '\\'; break;
2545 }
2546 }
2547
Nirav Davea645433c2016-07-18 15:24:03 +00002548 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002549 return false;
2550}
2551
Jim Grosbach4b905842013-09-20 23:08:21 +00002552/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002553/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002554bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002555 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002556 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002557
Daniel Dunbara10e5192009-06-24 23:30:00 +00002558 for (;;) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002559 std::string Data;
Nirav Davea645433c2016-07-18 15:24:03 +00002560 if (check(getTok().isNot(AsmToken::String),
2561 "expected string in '" + Twine(IDVal) + "' directive") ||
2562 parseEscapedString(Data))
Daniel Dunbaref668c12009-08-14 18:19:52 +00002563 return true;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002564
Rafael Espindola64e1af82013-07-02 15:49:13 +00002565 getStreamer().EmitBytes(Data);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002566 if (ZeroTerminated)
Rafael Espindola64e1af82013-07-02 15:49:13 +00002567 getStreamer().EmitBytes(StringRef("\0", 1));
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002568
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002569 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002570 break;
2571
Nirav Davea645433c2016-07-18 15:24:03 +00002572 if (parseToken(AsmToken::Comma,
2573 "unexpected token in '" + Twine(IDVal) + "' directive"))
2574 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002575 }
2576 }
2577
Sean Callanan686ed8d2010-01-19 20:22:31 +00002578 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002579 return false;
2580}
2581
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002582/// parseDirectiveReloc
2583/// ::= .reloc expression , identifier [ , expression ]
2584bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2585 const MCExpr *Offset;
2586 const MCExpr *Expr = nullptr;
2587
2588 SMLoc OffsetLoc = Lexer.getTok().getLoc();
2589 if (parseExpression(Offset))
2590 return true;
2591
2592 // We can only deal with constant expressions at the moment.
2593 int64_t OffsetValue;
Nirav Davea645433c2016-07-18 15:24:03 +00002594 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2595 "expression is not a constant value") ||
2596 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2597 parseToken(AsmToken::Comma, "expected comma") ||
2598 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2599 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002600
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002601 SMLoc NameLoc = Lexer.getTok().getLoc();
2602 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002603 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002604
2605 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002606 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002607 SMLoc ExprLoc = Lexer.getLoc();
2608 if (parseExpression(Expr))
2609 return true;
2610
2611 MCValue Value;
2612 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2613 return Error(ExprLoc, "expression must be relocatable");
2614 }
2615
Nirav Davea645433c2016-07-18 15:24:03 +00002616 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002617 "unexpected token in .reloc directive"))
2618 return true;
2619
2620 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2621 return Error(NameLoc, "unknown relocation name");
2622
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002623 return false;
2624}
2625
Jim Grosbach4b905842013-09-20 23:08:21 +00002626/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002627/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002628bool AsmParser::parseDirectiveValue(unsigned Size) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002629 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002630 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002631
Daniel Dunbara10e5192009-06-24 23:30:00 +00002632 for (;;) {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002633 const MCExpr *Value;
Jim Grosbach76346c32011-06-29 16:05:14 +00002634 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002635 if (parseExpression(Value))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002636 return true;
2637
Daniel Dunbar6738a2e2010-05-23 18:36:38 +00002638 // Special case constant expressions to match code generator.
Jim Grosbach76346c32011-06-29 16:05:14 +00002639 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2640 assert(Size <= 8 && "Invalid size");
2641 uint64_t IntValue = MCE->getValue();
2642 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2643 return Error(ExprLoc, "literal value out of range for directive");
Rafael Espindola64e1af82013-07-02 15:49:13 +00002644 getStreamer().EmitIntValue(IntValue, Size);
Jim Grosbach76346c32011-06-29 16:05:14 +00002645 } else
Kevin Enderby96918bc2014-04-22 17:27:29 +00002646 getStreamer().EmitValue(Value, Size, ExprLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002647
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002648 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002649 break;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002650
Daniel Dunbara10e5192009-06-24 23:30:00 +00002651 // FIXME: Improve diagnostic.
Nirav Davea645433c2016-07-18 15:24:03 +00002652 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
2653 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002654 }
2655 }
2656
Sean Callanan686ed8d2010-01-19 20:22:31 +00002657 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002658 return false;
2659}
2660
David Woodhoused6de0d92014-02-01 16:20:59 +00002661/// ParseDirectiveOctaValue
2662/// ::= .octa [ hexconstant (, hexconstant)* ]
2663bool AsmParser::parseDirectiveOctaValue() {
2664 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2665 checkForValidSection();
2666
2667 for (;;) {
Nirav Davea645433c2016-07-18 15:24:03 +00002668 if (getTok().is(AsmToken::Error))
David Woodhoused6de0d92014-02-01 16:20:59 +00002669 return true;
Nirav Davea645433c2016-07-18 15:24:03 +00002670 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
David Woodhoused6de0d92014-02-01 16:20:59 +00002671 return TokError("unknown token in expression");
2672
2673 SMLoc ExprLoc = getLexer().getLoc();
2674 APInt IntValue = getTok().getAPIntVal();
2675 Lex();
2676
2677 uint64_t hi, lo;
2678 if (IntValue.isIntN(64)) {
2679 hi = 0;
2680 lo = IntValue.getZExtValue();
2681 } else if (IntValue.isIntN(128)) {
David Woodhouse6c9a6f92014-02-01 16:52:33 +00002682 // It might actually have more than 128 bits, but the top ones are zero.
2683 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002684 lo = IntValue.getLoBits(64).getZExtValue();
2685 } else
2686 return Error(ExprLoc, "literal value out of range for directive");
2687
2688 if (MAI.isLittleEndian()) {
2689 getStreamer().EmitIntValue(lo, 8);
2690 getStreamer().EmitIntValue(hi, 8);
2691 } else {
2692 getStreamer().EmitIntValue(hi, 8);
2693 getStreamer().EmitIntValue(lo, 8);
2694 }
2695
2696 if (getLexer().is(AsmToken::EndOfStatement))
2697 break;
2698
2699 // FIXME: Improve diagnostic.
Nirav Davea645433c2016-07-18 15:24:03 +00002700 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
2701 return true;
David Woodhoused6de0d92014-02-01 16:20:59 +00002702 }
2703 }
2704
2705 Lex();
2706 return false;
2707}
2708
Jim Grosbach4b905842013-09-20 23:08:21 +00002709/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00002710/// ::= (.single | .double) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002711bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
Daniel Dunbar2af16532010-09-24 01:59:56 +00002712 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002713 checkForValidSection();
Daniel Dunbar2af16532010-09-24 01:59:56 +00002714
2715 for (;;) {
2716 // We don't truly support arithmetic on floating point expressions, so we
2717 // have to manually parse unary prefixes.
2718 bool IsNeg = false;
2719 if (getLexer().is(AsmToken::Minus)) {
Nirav Dave1180e6892016-06-02 17:15:05 +00002720 Lexer.Lex();
Daniel Dunbar2af16532010-09-24 01:59:56 +00002721 IsNeg = true;
2722 } else if (getLexer().is(AsmToken::Plus))
Nirav Dave1180e6892016-06-02 17:15:05 +00002723 Lexer.Lex();
Daniel Dunbar2af16532010-09-24 01:59:56 +00002724
Nirav Dave1180e6892016-06-02 17:15:05 +00002725 if (Lexer.is(AsmToken::Error))
2726 return TokError(Lexer.getErr());
2727 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
2728 Lexer.isNot(AsmToken::Identifier))
Daniel Dunbar2af16532010-09-24 01:59:56 +00002729 return TokError("unexpected token in directive");
2730
2731 // Convert to an APFloat.
2732 APFloat Value(Semantics);
Kevin Enderby5bbe9572011-03-29 21:11:52 +00002733 StringRef IDVal = getTok().getString();
2734 if (getLexer().is(AsmToken::Identifier)) {
2735 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2736 Value = APFloat::getInf(Semantics);
2737 else if (!IDVal.compare_lower("nan"))
2738 Value = APFloat::getNaN(Semantics, false, ~0);
2739 else
2740 return TokError("invalid floating point literal");
2741 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Jim Grosbach4b905842013-09-20 23:08:21 +00002742 APFloat::opInvalidOp)
Daniel Dunbar2af16532010-09-24 01:59:56 +00002743 return TokError("invalid floating point literal");
2744 if (IsNeg)
2745 Value.changeSign();
2746
2747 // Consume the numeric token.
2748 Lex();
2749
2750 // Emit the value as an integer.
2751 APInt AsInt = Value.bitcastToAPInt();
2752 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
Rafael Espindola64e1af82013-07-02 15:49:13 +00002753 AsInt.getBitWidth() / 8);
Daniel Dunbar2af16532010-09-24 01:59:56 +00002754
Nirav Dave1180e6892016-06-02 17:15:05 +00002755 if (Lexer.is(AsmToken::EndOfStatement))
Daniel Dunbar2af16532010-09-24 01:59:56 +00002756 break;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002757
Nirav Davea645433c2016-07-18 15:24:03 +00002758 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
2759 return true;
Daniel Dunbar2af16532010-09-24 01:59:56 +00002760 }
2761 }
2762
2763 Lex();
2764 return false;
2765}
2766
Jim Grosbach4b905842013-09-20 23:08:21 +00002767/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00002768/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002769bool AsmParser::parseDirectiveZero() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002770 checkForValidSection();
Rafael Espindola922e3f42010-09-16 15:03:59 +00002771
Petr Hosek67a94a72016-05-28 05:57:48 +00002772 SMLoc NumBytesLoc = Lexer.getLoc();
2773 const MCExpr *NumBytes;
2774 if (parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00002775 return true;
2776
Rafael Espindolab91bac62010-10-05 19:42:57 +00002777 int64_t Val = 0;
2778 if (getLexer().is(AsmToken::Comma)) {
2779 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002780 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00002781 return true;
2782 }
2783
Nirav Davea645433c2016-07-18 15:24:03 +00002784 if (parseToken(AsmToken::EndOfStatement,
2785 "unexpected token in '.zero' directive"))
2786 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00002787 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00002788
2789 return false;
2790}
2791
Jim Grosbach4b905842013-09-20 23:08:21 +00002792/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00002793/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002794bool AsmParser::parseDirectiveFill() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002795 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002796
Petr Hosek67a94a72016-05-28 05:57:48 +00002797 SMLoc NumValuesLoc = Lexer.getLoc();
2798 const MCExpr *NumValues;
2799 if (parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002800 return true;
2801
Roman Divackye33098f2013-09-24 17:44:41 +00002802 int64_t FillSize = 1;
2803 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002804
David Majnemer522d3db2014-02-01 07:19:38 +00002805 SMLoc SizeLoc, ExprLoc;
Roman Divackye33098f2013-09-24 17:44:41 +00002806 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbara10e5192009-06-24 23:30:00 +00002807
Nirav Davea645433c2016-07-18 15:24:03 +00002808 if (parseToken(AsmToken::Comma, "unexpected token in '.fill' directive") ||
2809 getTokenLoc(SizeLoc) || parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00002810 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002811
Roman Divackye33098f2013-09-24 17:44:41 +00002812 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00002813 if (parseToken(AsmToken::Comma,
2814 "unexpected token in '.fill' directive") ||
2815 getTokenLoc(ExprLoc) || parseAbsoluteExpression(FillExpr) ||
2816 parseToken(AsmToken::EndOfStatement,
2817 "unexpected token in '.fill' directive"))
Roman Divackye33098f2013-09-24 17:44:41 +00002818 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00002819 }
2820 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002821
David Majnemer522d3db2014-02-01 07:19:38 +00002822 if (FillSize < 0) {
2823 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00002824 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00002825 }
2826 if (FillSize > 8) {
2827 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2828 FillSize = 8;
2829 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002830
David Majnemer522d3db2014-02-01 07:19:38 +00002831 if (!isUInt<32>(FillExpr) && FillSize > 4)
2832 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2833
Petr Hosek67a94a72016-05-28 05:57:48 +00002834 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002835
2836 return false;
2837}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002838
Jim Grosbach4b905842013-09-20 23:08:21 +00002839/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002840/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002841bool AsmParser::parseDirectiveOrg() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002842 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002843
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002844 const MCExpr *Offset;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002845 if (parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002846 return true;
2847
2848 // Parse optional fill expression.
2849 int64_t FillExpr = 0;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002850 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00002851 if (parseToken(AsmToken::Comma, "unexpected token in '.org' directive") ||
2852 parseAbsoluteExpression(FillExpr))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002853 return true;
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002854 }
2855
Nirav Davea645433c2016-07-18 15:24:03 +00002856 if (parseToken(AsmToken::EndOfStatement,
2857 "unexpected token in '.org' directive"))
2858 return true;
2859
Rafael Espindola7ae65d82015-11-04 23:59:18 +00002860 getStreamer().emitValueToOffset(Offset, FillExpr);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002861 return false;
2862}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002863
Jim Grosbach4b905842013-09-20 23:08:21 +00002864/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002865/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00002866bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002867 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002868
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002869 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002870 int64_t Alignment;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002871 if (parseAbsoluteExpression(Alignment))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002872 return true;
2873
2874 SMLoc MaxBytesLoc;
2875 bool HasFillExpr = false;
2876 int64_t FillExpr = 0;
2877 int64_t MaxBytesToFill = 0;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002878 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00002879 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
2880 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002881
2882 // The fill expression can be omitted while specifying a maximum number of
2883 // alignment bytes, e.g:
2884 // .align 3,,4
Nirav Davea645433c2016-07-18 15:24:03 +00002885 if (getTok().isNot(AsmToken::Comma)) {
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002886 HasFillExpr = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002887 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002888 return true;
2889 }
2890
Nirav Davea645433c2016-07-18 15:24:03 +00002891 if (getTok().isNot(AsmToken::EndOfStatement)) {
2892 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
2893 getTokenLoc(MaxBytesLoc) || parseAbsoluteExpression(MaxBytesToFill))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002894 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002895 }
2896 }
2897
Nirav Davea645433c2016-07-18 15:24:03 +00002898 if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
2899 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002900
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002901 if (!HasFillExpr)
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002902 FillExpr = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002903
2904 // Compute alignment in bytes.
2905 if (IsPow2) {
2906 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002907 if (Alignment >= 32) {
2908 Error(AlignmentLoc, "invalid alignment value");
2909 Alignment = 31;
2910 }
2911
Benjamin Kramer63951ad2009-09-06 09:35:10 +00002912 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00002913 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00002914 // Reject alignments that aren't either a power of two or zero,
2915 // for gas compatibility. Alignment of zero is silently rounded
2916 // up to one.
2917 if (Alignment == 0)
2918 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00002919 if (!isPowerOf2_64(Alignment))
2920 Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002921 }
2922
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002923 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002924 if (MaxBytesLoc.isValid()) {
2925 if (MaxBytesToFill < 1) {
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002926 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00002927 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00002928 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002929 }
2930
2931 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00002932 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00002933 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002934 MaxBytesToFill = 0;
2935 }
2936 }
2937
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002938 // Check whether we should use optimal code alignment for this .align
2939 // directive.
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00002940 const MCSection *Section = getStreamer().getCurrentSection().first;
2941 assert(Section && "must have section to emit alignment");
2942 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002943 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2944 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002945 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002946 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00002947 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00002948 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2949 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002950 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002951
2952 return false;
2953}
2954
Jim Grosbach4b905842013-09-20 23:08:21 +00002955/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00002956/// ::= .file [number] filename
2957/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00002958bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00002959 // FIXME: I'm not sure what this is.
2960 int64_t FileNumber = -1;
2961 SMLoc FileNumberLoc = getLexer().getLoc();
2962 if (getLexer().is(AsmToken::Integer)) {
2963 FileNumber = getTok().getIntVal();
2964 Lex();
2965
2966 if (FileNumber < 1)
2967 return TokError("file number less than one");
2968 }
2969
Nirav Davea645433c2016-07-18 15:24:03 +00002970 std::string Path = getTok().getString();
Eli Bendersky17233942013-01-15 22:59:42 +00002971
2972 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002973 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00002974 if (check(getTok().isNot(AsmToken::String),
2975 "unexpected token in '.file' directive") ||
2976 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002977 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00002978
2979 StringRef Directory;
2980 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002981 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00002982 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00002983 if (check(FileNumber == -1,
2984 "explicit path specified, but no file number") ||
2985 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002986 return true;
2987 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00002988 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00002989 } else {
2990 Filename = Path;
2991 }
2992
Nirav Davea645433c2016-07-18 15:24:03 +00002993 if (parseToken(AsmToken::EndOfStatement,
2994 "unexpected token in '.file' directive"))
2995 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00002996
2997 if (FileNumber == -1)
2998 getStreamer().EmitFileDirective(Filename);
2999 else {
David Blaikie22748082016-05-26 00:22:26 +00003000 // If there is -g option as well as debug info from directive file,
3001 // we turn off -g option, directly use the existing debug info instead.
David Blaikiedc3f01e2015-03-09 01:57:13 +00003002 if (getContext().getGenDwarfForAssembly())
David Blaikie22748082016-05-26 00:22:26 +00003003 getContext().setGenDwarfForAssembly(false);
3004 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
David Blaikiec714ef42014-03-17 01:52:11 +00003005 0)
Eli Bendersky17233942013-01-15 22:59:42 +00003006 Error(FileNumberLoc, "file number already allocated");
3007 }
3008
3009 return false;
3010}
3011
Jim Grosbach4b905842013-09-20 23:08:21 +00003012/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003013/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003014bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003015 int64_t LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003016 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003017 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3018 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003019 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003020 // FIXME: Do something with the .line.
3021 }
Nirav Davea645433c2016-07-18 15:24:03 +00003022 if (parseToken(AsmToken::EndOfStatement,
3023 "unexpected token in '.line' directive"))
3024 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003025
3026 return false;
3027}
3028
Jim Grosbach4b905842013-09-20 23:08:21 +00003029/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003030/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3031/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3032/// The first number is a file number, must have been previously assigned with
3033/// a .file directive, the second number is the line number and optionally the
3034/// third number is a column position (zero if not specified). The remaining
3035/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003036bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003037 int64_t FileNumber = 0, LineNumber = 0;
3038 SMLoc Loc = getTok().getLoc();
3039 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3040 check(FileNumber < 1, Loc,
3041 "file number less than one in '.loc' directive") ||
3042 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3043 "unassigned file number in '.loc' directive"))
3044 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003045
Nirav Davea645433c2016-07-18 15:24:03 +00003046 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003047 if (getLexer().is(AsmToken::Integer)) {
3048 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003049 if (LineNumber < 0)
3050 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003051 Lex();
3052 }
3053
3054 int64_t ColumnPos = 0;
3055 if (getLexer().is(AsmToken::Integer)) {
3056 ColumnPos = getTok().getIntVal();
3057 if (ColumnPos < 0)
3058 return TokError("column position less than zero in '.loc' directive");
3059 Lex();
3060 }
3061
3062 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3063 unsigned Isa = 0;
3064 int64_t Discriminator = 0;
3065 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3066 for (;;) {
3067 if (getLexer().is(AsmToken::EndOfStatement))
3068 break;
3069
3070 StringRef Name;
3071 SMLoc Loc = getTok().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003072 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003073 return TokError("unexpected token in '.loc' directive");
3074
3075 if (Name == "basic_block")
3076 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3077 else if (Name == "prologue_end")
3078 Flags |= DWARF2_FLAG_PROLOGUE_END;
3079 else if (Name == "epilogue_begin")
3080 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3081 else if (Name == "is_stmt") {
3082 Loc = getTok().getLoc();
3083 const MCExpr *Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003084 if (parseExpression(Value))
Eli Bendersky17233942013-01-15 22:59:42 +00003085 return true;
3086 // The expression must be the constant 0 or 1.
3087 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3088 int Value = MCE->getValue();
3089 if (Value == 0)
3090 Flags &= ~DWARF2_FLAG_IS_STMT;
3091 else if (Value == 1)
3092 Flags |= DWARF2_FLAG_IS_STMT;
3093 else
3094 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003095 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003096 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3097 }
Craig Topperf15655b2013-04-22 04:22:40 +00003098 } else if (Name == "isa") {
Eli Bendersky17233942013-01-15 22:59:42 +00003099 Loc = getTok().getLoc();
3100 const MCExpr *Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003101 if (parseExpression(Value))
Eli Bendersky17233942013-01-15 22:59:42 +00003102 return true;
3103 // The expression must be a constant greater or equal to 0.
3104 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3105 int Value = MCE->getValue();
3106 if (Value < 0)
3107 return Error(Loc, "isa number less than zero");
3108 Isa = Value;
Craig Topperf15655b2013-04-22 04:22:40 +00003109 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003110 return Error(Loc, "isa number not a constant value");
3111 }
Craig Topperf15655b2013-04-22 04:22:40 +00003112 } else if (Name == "discriminator") {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003113 if (parseAbsoluteExpression(Discriminator))
Eli Bendersky17233942013-01-15 22:59:42 +00003114 return true;
Craig Topperf15655b2013-04-22 04:22:40 +00003115 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003116 return Error(Loc, "unknown sub-directive in '.loc' directive");
3117 }
3118
3119 if (getLexer().is(AsmToken::EndOfStatement))
3120 break;
3121 }
3122 }
Nirav Davea645433c2016-07-18 15:24:03 +00003123 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003124
3125 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3126 Isa, Discriminator, StringRef());
3127
3128 return false;
3129}
3130
Jim Grosbach4b905842013-09-20 23:08:21 +00003131/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003132/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003133bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003134 return TokError("unsupported directive '.stabs'");
3135}
3136
Reid Kleckner2214ed82016-01-29 00:49:42 +00003137/// parseDirectiveCVFile
3138/// ::= .cv_file number filename
3139bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003140 SMLoc FileNumberLoc = getTok().getLoc();
3141 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003142 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00003143
3144 if (parseIntToken(FileNumber,
3145 "expected file number in '.cv_file' directive") ||
3146 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3147 check(getTok().isNot(AsmToken::String),
3148 "unexpected token in '.cv_file' directive") ||
3149 // Usually directory and filename are together, otherwise just
3150 // directory. Allow the strings to have escaped octal character sequence.
3151 parseEscapedString(Filename) ||
3152 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00003153 "unexpected token in '.cv_file' directive"))
3154 return true;
3155
3156 if (getStreamer().EmitCVFileDirective(FileNumber, Filename) == 0)
3157 Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003158
3159 return false;
3160}
3161
3162/// parseDirectiveCVLoc
3163/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3164/// [is_stmt VALUE]
3165/// The first number is a file number, must have been previously assigned with
3166/// a .file directive, the second number is the line number and optionally the
3167/// third number is a column position (zero if not specified). The remaining
3168/// optional items are .loc sub-directives.
3169bool AsmParser::parseDirectiveCVLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003170 SMLoc Loc;
3171 int64_t FunctionId, FileNumber;
3172 if (getTokenLoc(Loc) ||
3173 parseIntToken(FunctionId, "unexpected token in '.cv_loc' directive") ||
3174 check(FunctionId < 0, Loc,
3175 "function id less than zero in '.cv_loc' directive") ||
3176 getTokenLoc(Loc) ||
3177 parseIntToken(FileNumber, "expected integer in '.cv_loc' directive") ||
3178 check(FileNumber < 1, Loc,
3179 "file number less than one in '.cv_loc' directive") ||
3180 check(!getContext().isValidCVFileNumber(FileNumber), Loc,
3181 "unassigned file number in '.cv_loc' directive"))
3182 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003183
3184 int64_t LineNumber = 0;
3185 if (getLexer().is(AsmToken::Integer)) {
3186 LineNumber = getTok().getIntVal();
3187 if (LineNumber < 0)
3188 return TokError("line number less than zero in '.cv_loc' directive");
3189 Lex();
3190 }
3191
3192 int64_t ColumnPos = 0;
3193 if (getLexer().is(AsmToken::Integer)) {
3194 ColumnPos = getTok().getIntVal();
3195 if (ColumnPos < 0)
3196 return TokError("column position less than zero in '.cv_loc' directive");
3197 Lex();
3198 }
3199
3200 bool PrologueEnd = false;
3201 uint64_t IsStmt = 0;
3202 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3203 StringRef Name;
3204 SMLoc Loc = getTok().getLoc();
3205 if (parseIdentifier(Name))
3206 return TokError("unexpected token in '.cv_loc' directive");
3207
3208 if (Name == "prologue_end")
3209 PrologueEnd = true;
3210 else if (Name == "is_stmt") {
3211 Loc = getTok().getLoc();
3212 const MCExpr *Value;
3213 if (parseExpression(Value))
3214 return true;
3215 // The expression must be the constant 0 or 1.
3216 IsStmt = ~0ULL;
3217 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3218 IsStmt = MCE->getValue();
3219
3220 if (IsStmt > 1)
3221 return Error(Loc, "is_stmt value not 0 or 1");
3222 } else {
3223 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3224 }
3225 }
Nirav Davea645433c2016-07-18 15:24:03 +00003226 Lex();
Reid Kleckner2214ed82016-01-29 00:49:42 +00003227
3228 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
3229 ColumnPos, PrologueEnd, IsStmt, StringRef());
3230 return false;
3231}
3232
3233/// parseDirectiveCVLinetable
3234/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3235bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003236 int64_t FunctionId;
3237 StringRef FnStartName, FnEndName;
3238 SMLoc Loc = getTok().getLoc();
3239 if (parseIntToken(FunctionId,
3240 "expected Integer in '.cv_linetable' directive") ||
3241 check(FunctionId < 0, Loc,
3242 "function id less than zero in '.cv_linetable' directive") ||
3243 parseToken(AsmToken::Comma,
3244 "unexpected token in '.cv_linetable' directive") ||
3245 getTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3246 "expected identifier in directive") ||
3247 parseToken(AsmToken::Comma,
3248 "unexpected token in '.cv_linetable' directive") ||
3249 getTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3250 "expected identifier in directive"))
3251 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003252
3253 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3254 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3255
3256 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3257 return false;
3258}
3259
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003260/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003261/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003262/// ("contains" SecondaryFunctionId+)?
3263bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003264 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3265 StringRef FnStartName, FnEndName;
3266 SMLoc Loc = getTok().getLoc();
3267 if (parseIntToken(
3268 PrimaryFunctionId,
3269 "expected PrimaryFunctionId in '.cv_inline_linetable' directive") ||
3270 check(PrimaryFunctionId < 0, Loc,
3271 "function id less than zero in '.cv_inline_linetable' directive") ||
3272 getTokenLoc(Loc) ||
3273 parseIntToken(
3274 SourceFileId,
3275 "expected SourceField in '.cv_inline_linetable' directive") ||
3276 check(SourceFileId <= 0, Loc,
3277 "File id less than zero in '.cv_inline_linetable' directive") ||
3278 getTokenLoc(Loc) ||
3279 parseIntToken(
3280 SourceLineNum,
3281 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3282 check(SourceLineNum < 0, Loc,
3283 "Line number less than zero in '.cv_inline_linetable' directive") ||
3284 getTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3285 "expected identifier in directive") ||
3286 getTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3287 "expected identifier in directive"))
3288 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003289
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003290 SmallVector<unsigned, 8> SecondaryFunctionIds;
3291 if (getLexer().is(AsmToken::Identifier)) {
3292 if (getTok().getIdentifier() != "contains")
3293 return TokError(
3294 "unexpected identifier in '.cv_inline_linetable' directive");
3295 Lex();
3296
3297 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3298 int64_t SecondaryFunctionId = getTok().getIntVal();
3299 if (SecondaryFunctionId < 0)
3300 return TokError(
3301 "function id less than zero in '.cv_inline_linetable' directive");
3302 Lex();
3303
3304 SecondaryFunctionIds.push_back(SecondaryFunctionId);
3305 }
3306 }
3307
Nirav Davea645433c2016-07-18 15:24:03 +00003308 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3309 return true;
3310
3311 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3312 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003313 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3314 SourceLineNum, FnStartSym,
David Majnemerc9911f22016-02-02 19:22:34 +00003315 FnEndSym, SecondaryFunctionIds);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003316 return false;
3317}
3318
David Majnemer408b5e62016-02-05 01:55:49 +00003319/// parseDirectiveCVDefRange
3320/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3321bool AsmParser::parseDirectiveCVDefRange() {
3322 SMLoc Loc;
3323 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3324 while (getLexer().is(AsmToken::Identifier)) {
3325 Loc = getLexer().getLoc();
3326 StringRef GapStartName;
3327 if (parseIdentifier(GapStartName))
3328 return Error(Loc, "expected identifier in directive");
3329 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3330
3331 Loc = getLexer().getLoc();
3332 StringRef GapEndName;
3333 if (parseIdentifier(GapEndName))
3334 return Error(Loc, "expected identifier in directive");
3335 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3336
3337 Ranges.push_back({GapStartSym, GapEndSym});
3338 }
3339
David Majnemer408b5e62016-02-05 01:55:49 +00003340 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003341 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3342 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003343 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003344
3345 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3346 return false;
3347}
3348
Reid Kleckner2214ed82016-01-29 00:49:42 +00003349/// parseDirectiveCVStringTable
3350/// ::= .cv_stringtable
3351bool AsmParser::parseDirectiveCVStringTable() {
3352 getStreamer().EmitCVStringTableDirective();
3353 return false;
3354}
3355
3356/// parseDirectiveCVFileChecksums
3357/// ::= .cv_filechecksums
3358bool AsmParser::parseDirectiveCVFileChecksums() {
3359 getStreamer().EmitCVFileChecksumsDirective();
3360 return false;
3361}
3362
Jim Grosbach4b905842013-09-20 23:08:21 +00003363/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003364/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003365bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003366 StringRef Name;
3367 bool EH = false;
3368 bool Debug = false;
3369
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003370 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003371 return TokError("Expected an identifier");
3372
3373 if (Name == ".eh_frame")
3374 EH = true;
3375 else if (Name == ".debug_frame")
3376 Debug = true;
3377
3378 if (getLexer().is(AsmToken::Comma)) {
3379 Lex();
3380
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003381 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003382 return TokError("Expected an identifier");
3383
3384 if (Name == ".eh_frame")
3385 EH = true;
3386 else if (Name == ".debug_frame")
3387 Debug = true;
3388 }
3389
3390 getStreamer().EmitCFISections(EH, Debug);
3391 return false;
3392}
3393
Jim Grosbach4b905842013-09-20 23:08:21 +00003394/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003395/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003396bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003397 StringRef Simple;
3398 if (getLexer().isNot(AsmToken::EndOfStatement))
3399 if (parseIdentifier(Simple) || Simple != "simple")
3400 return TokError("unexpected token in .cfi_startproc directive");
3401
Nirav Davea645433c2016-07-18 15:24:03 +00003402 if (parseToken(AsmToken::EndOfStatement, "Expected end of statement"))
3403 return true;
3404
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003405 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003406 return false;
3407}
3408
Jim Grosbach4b905842013-09-20 23:08:21 +00003409/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003410/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003411bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003412 getStreamer().EmitCFIEndProc();
3413 return false;
3414}
3415
Jim Grosbach4b905842013-09-20 23:08:21 +00003416/// \brief parse register name or number.
3417bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003418 SMLoc DirectiveLoc) {
3419 unsigned RegNo;
3420
3421 if (getLexer().isNot(AsmToken::Integer)) {
3422 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3423 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003424 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003425 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003426 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003427
3428 return false;
3429}
3430
Jim Grosbach4b905842013-09-20 23:08:21 +00003431/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003432/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003433bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003434 int64_t Register = 0, Offset = 0;
3435 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3436 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3437 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003438 return true;
3439
3440 getStreamer().EmitCFIDefCfa(Register, Offset);
3441 return false;
3442}
3443
Jim Grosbach4b905842013-09-20 23:08:21 +00003444/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003445/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003446bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003447 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003448 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003449 return true;
3450
3451 getStreamer().EmitCFIDefCfaOffset(Offset);
3452 return false;
3453}
3454
Jim Grosbach4b905842013-09-20 23:08:21 +00003455/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003456/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003457bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003458 int64_t Register1 = 0, Register2 = 0;
3459 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3460 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3461 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003462 return true;
3463
3464 getStreamer().EmitCFIRegister(Register1, Register2);
3465 return false;
3466}
3467
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003468/// parseDirectiveCFIWindowSave
3469/// ::= .cfi_window_save
3470bool AsmParser::parseDirectiveCFIWindowSave() {
3471 getStreamer().EmitCFIWindowSave();
3472 return false;
3473}
3474
Jim Grosbach4b905842013-09-20 23:08:21 +00003475/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003476/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003477bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003478 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003479 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003480 return true;
3481
3482 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3483 return false;
3484}
3485
Jim Grosbach4b905842013-09-20 23:08:21 +00003486/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003487/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003488bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003489 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003490 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003491 return true;
3492
3493 getStreamer().EmitCFIDefCfaRegister(Register);
3494 return false;
3495}
3496
Jim Grosbach4b905842013-09-20 23:08:21 +00003497/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003498/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003499bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003500 int64_t Register = 0;
3501 int64_t Offset = 0;
3502
Nirav Davea645433c2016-07-18 15:24:03 +00003503 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3504 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3505 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003506 return true;
3507
3508 getStreamer().EmitCFIOffset(Register, Offset);
3509 return false;
3510}
3511
Jim Grosbach4b905842013-09-20 23:08:21 +00003512/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003513/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003514bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003515 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003516
Nirav Davea645433c2016-07-18 15:24:03 +00003517 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3518 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3519 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003520 return true;
3521
3522 getStreamer().EmitCFIRelOffset(Register, Offset);
3523 return false;
3524}
3525
3526static bool isValidEncoding(int64_t Encoding) {
3527 if (Encoding & ~0xff)
3528 return false;
3529
3530 if (Encoding == dwarf::DW_EH_PE_omit)
3531 return true;
3532
3533 const unsigned Format = Encoding & 0xf;
3534 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3535 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3536 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3537 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3538 return false;
3539
3540 const unsigned Application = Encoding & 0x70;
3541 if (Application != dwarf::DW_EH_PE_absptr &&
3542 Application != dwarf::DW_EH_PE_pcrel)
3543 return false;
3544
3545 return true;
3546}
3547
Jim Grosbach4b905842013-09-20 23:08:21 +00003548/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003549/// IsPersonality true for cfi_personality, false for cfi_lsda
3550/// ::= .cfi_personality encoding, [symbol_name]
3551/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003552bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003553 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003554 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003555 return true;
3556 if (Encoding == dwarf::DW_EH_PE_omit)
3557 return false;
3558
Eli Bendersky17233942013-01-15 22:59:42 +00003559 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00003560 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
3561 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3562 check(parseIdentifier(Name), "expected identifier in directive"))
3563 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003564
Jim Grosbach6f482002015-05-18 18:43:14 +00003565 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003566
3567 if (IsPersonality)
3568 getStreamer().EmitCFIPersonality(Sym, Encoding);
3569 else
3570 getStreamer().EmitCFILsda(Sym, Encoding);
3571 return false;
3572}
3573
Jim Grosbach4b905842013-09-20 23:08:21 +00003574/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00003575/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003576bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003577 getStreamer().EmitCFIRememberState();
3578 return false;
3579}
3580
Jim Grosbach4b905842013-09-20 23:08:21 +00003581/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00003582/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003583bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003584 getStreamer().EmitCFIRestoreState();
3585 return false;
3586}
3587
Jim Grosbach4b905842013-09-20 23:08:21 +00003588/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00003589/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00003590bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003591 int64_t Register = 0;
3592
Jim Grosbach4b905842013-09-20 23:08:21 +00003593 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003594 return true;
3595
3596 getStreamer().EmitCFISameValue(Register);
3597 return false;
3598}
3599
Jim Grosbach4b905842013-09-20 23:08:21 +00003600/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00003601/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00003602bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003603 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003604 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003605 return true;
3606
3607 getStreamer().EmitCFIRestore(Register);
3608 return false;
3609}
3610
Jim Grosbach4b905842013-09-20 23:08:21 +00003611/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00003612/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003613bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00003614 std::string Values;
3615 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003616 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003617 return true;
3618
3619 Values.push_back((uint8_t)CurrValue);
3620
3621 while (getLexer().is(AsmToken::Comma)) {
3622 Lex();
3623
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003624 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003625 return true;
3626
3627 Values.push_back((uint8_t)CurrValue);
3628 }
3629
3630 getStreamer().EmitCFIEscape(Values);
3631 return false;
3632}
3633
Jim Grosbach4b905842013-09-20 23:08:21 +00003634/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00003635/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00003636bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00003637 if (parseToken(AsmToken::EndOfStatement,
3638 "unexpected token in '.cfi_signal_frame'"))
3639 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003640
3641 getStreamer().EmitCFISignalFrame();
3642 return false;
3643}
3644
Jim Grosbach4b905842013-09-20 23:08:21 +00003645/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00003646/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00003647bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003648 int64_t Register = 0;
3649
Jim Grosbach4b905842013-09-20 23:08:21 +00003650 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003651 return true;
3652
3653 getStreamer().EmitCFIUndefined(Register);
3654 return false;
3655}
3656
Jim Grosbach4b905842013-09-20 23:08:21 +00003657/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00003658/// ::= .macros_on
3659/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00003660bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00003661 if (parseToken(AsmToken::EndOfStatement,
3662 "unexpected token in '" + Directive + "' directive"))
3663 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003664
Jim Grosbach4b905842013-09-20 23:08:21 +00003665 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00003666 return false;
3667}
3668
Jim Grosbach4b905842013-09-20 23:08:21 +00003669/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003670/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00003671bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003672 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003673 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003674 return TokError("expected identifier in '.macro' directive");
3675
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003676 if (getLexer().is(AsmToken::Comma))
3677 Lex();
3678
Eli Bendersky17233942013-01-15 22:59:42 +00003679 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00003680 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003681
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003682 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003683 return Error(Lexer.getLoc(),
3684 "Vararg parameter '" + Parameters.back().Name +
3685 "' should be last one in the list of parameters.");
3686
David Majnemer91fc4c22014-01-29 18:57:46 +00003687 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003688 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00003689 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003690
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003691 if (Lexer.is(AsmToken::Colon)) {
3692 Lex(); // consume ':'
3693
3694 SMLoc QualLoc;
3695 StringRef Qualifier;
3696
3697 QualLoc = Lexer.getLoc();
3698 if (parseIdentifier(Qualifier))
3699 return Error(QualLoc, "missing parameter qualifier for "
3700 "'" + Parameter.Name + "' in macro '" + Name + "'");
3701
3702 if (Qualifier == "req")
3703 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00003704 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003705 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003706 else
3707 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3708 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3709 }
3710
David Majnemer91fc4c22014-01-29 18:57:46 +00003711 if (getLexer().is(AsmToken::Equal)) {
3712 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003713
3714 SMLoc ParamLoc;
3715
3716 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003717 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00003718 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003719
3720 if (Parameter.Required)
3721 Warning(ParamLoc, "pointless default value for required parameter "
3722 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00003723 }
David Majnemer91fc4c22014-01-29 18:57:46 +00003724
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003725 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00003726
3727 if (getLexer().is(AsmToken::Comma))
3728 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003729 }
3730
Nirav Dave1180e6892016-06-02 17:15:05 +00003731 // Eat just the end of statement.
3732 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003733
Nirav Dave1180e6892016-06-02 17:15:05 +00003734 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00003735 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003736 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003737 // Lex the macro definition.
3738 for (;;) {
Nirav Dave1180e6892016-06-02 17:15:05 +00003739 // Ignore Lexing errors in macros.
3740 while (Lexer.is(AsmToken::Error)) {
3741 Lexer.Lex();
3742 }
3743
Eli Bendersky17233942013-01-15 22:59:42 +00003744 // Check whether we have reached the end of the file.
3745 if (getLexer().is(AsmToken::Eof))
3746 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3747
3748 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003749 if (getLexer().is(AsmToken::Identifier)) {
3750 if (getTok().getIdentifier() == ".endm" ||
3751 getTok().getIdentifier() == ".endmacro") {
3752 if (MacroDepth == 0) { // Outermost macro.
3753 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00003754 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003755 if (getLexer().isNot(AsmToken::EndOfStatement))
3756 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3757 "' directive");
3758 break;
3759 } else {
3760 // Otherwise we just found the end of an inner macro.
3761 --MacroDepth;
3762 }
3763 } else if (getTok().getIdentifier() == ".macro") {
3764 // We allow nested macros. Those aren't instantiated until the outermost
3765 // macro is expanded so just ignore them for now.
3766 ++MacroDepth;
3767 }
Eli Bendersky17233942013-01-15 22:59:42 +00003768 }
3769
3770 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003771 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00003772 }
3773
Jim Grosbach4b905842013-09-20 23:08:21 +00003774 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00003775 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3776 }
3777
3778 const char *BodyStart = StartToken.getLoc().getPointer();
3779 const char *BodyEnd = EndToken.getLoc().getPointer();
3780 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00003781 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003782 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00003783 return false;
3784}
3785
Jim Grosbach4b905842013-09-20 23:08:21 +00003786/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00003787///
3788/// With the support added for named parameters there may be code out there that
3789/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00003790/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00003791/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00003792/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00003793/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3794/// warning that the positional parameter found in body which have no effect.
3795/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00003796/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00003797/// intended or change the macro to use the named parameters. It is possible
3798/// this warning will trigger when the none of the named parameters are used
3799/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00003800void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00003801 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00003802 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00003803 // If this macro is not defined with named parameters the warning we are
3804 // checking for here doesn't apply.
3805 unsigned NParameters = Parameters.size();
3806 if (NParameters == 0)
3807 return;
3808
3809 bool NamedParametersFound = false;
3810 bool PositionalParametersFound = false;
3811
3812 // Look at the body of the macro for use of both the named parameters and what
3813 // are likely to be positional parameters. This is what expandMacro() is
3814 // doing when it finds the parameters in the body.
3815 while (!Body.empty()) {
3816 // Scan for the next possible parameter.
3817 std::size_t End = Body.size(), Pos = 0;
3818 for (; Pos != End; ++Pos) {
3819 // Check for a substitution or escape.
3820 // This macro is defined with parameters, look for \foo, \bar, etc.
3821 if (Body[Pos] == '\\' && Pos + 1 != End)
3822 break;
3823
3824 // This macro should have parameters, but look for $0, $1, ..., $n too.
3825 if (Body[Pos] != '$' || Pos + 1 == End)
3826 continue;
3827 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00003828 if (Next == '$' || Next == 'n' ||
3829 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00003830 break;
3831 }
3832
3833 // Check if we reached the end.
3834 if (Pos == End)
3835 break;
3836
3837 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00003838 switch (Body[Pos + 1]) {
3839 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00003840 case '$':
3841 break;
3842
Jim Grosbach4b905842013-09-20 23:08:21 +00003843 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00003844 case 'n':
3845 PositionalParametersFound = true;
3846 break;
3847
Jim Grosbach4b905842013-09-20 23:08:21 +00003848 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00003849 default: {
3850 PositionalParametersFound = true;
3851 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00003852 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00003853 }
3854 Pos += 2;
3855 } else {
3856 unsigned I = Pos + 1;
3857 while (isIdentifierChar(Body[I]) && I + 1 != End)
3858 ++I;
3859
Jim Grosbach4b905842013-09-20 23:08:21 +00003860 const char *Begin = Body.data() + Pos + 1;
3861 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00003862 unsigned Index = 0;
3863 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003864 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00003865 break;
3866
3867 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00003868 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3869 Pos += 3;
3870 else {
3871 Pos = I;
3872 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00003873 } else {
3874 NamedParametersFound = true;
3875 Pos += 1 + Argument.size();
3876 }
3877 }
3878 // Update the scan point.
3879 Body = Body.substr(Pos);
3880 }
3881
3882 if (!NamedParametersFound && PositionalParametersFound)
3883 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3884 "used in macro body, possible positional parameter "
3885 "found in body which will have no effect");
3886}
3887
Nico Weber155dccd12014-07-24 17:08:39 +00003888/// parseDirectiveExitMacro
3889/// ::= .exitm
3890bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00003891 if (parseToken(AsmToken::EndOfStatement,
3892 "unexpected token in '" + Directive + "' directive"))
3893 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00003894
3895 if (!isInsideMacroInstantiation())
3896 return TokError("unexpected '" + Directive + "' in file, "
3897 "no current macro definition");
3898
3899 // Exit all conditionals that are active in the current macro.
3900 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3901 TheCondState = TheCondStack.back();
3902 TheCondStack.pop_back();
3903 }
3904
3905 handleMacroExit();
3906 return false;
3907}
3908
Jim Grosbach4b905842013-09-20 23:08:21 +00003909/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00003910/// ::= .endm
3911/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00003912bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00003913 if (getLexer().isNot(AsmToken::EndOfStatement))
3914 return TokError("unexpected token in '" + Directive + "' directive");
3915
3916 // If we are inside a macro instantiation, terminate the current
3917 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00003918 if (isInsideMacroInstantiation()) {
3919 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00003920 return false;
3921 }
3922
3923 // Otherwise, this .endmacro is a stray entry in the file; well formed
3924 // .endmacro directives are handled during the macro definition parsing.
3925 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00003926 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00003927}
3928
Jim Grosbach4b905842013-09-20 23:08:21 +00003929/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00003930/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00003931bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003932 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00003933 SMLoc Loc;
3934 if (getTokenLoc(Loc) || check(parseIdentifier(Name), Loc,
3935 "expected identifier in '.purgem' directive") ||
3936 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00003937 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003938 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003939
Nirav Dave1ab71992016-07-18 19:35:21 +00003940 if (!lookupMacro(Name))
3941 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3942
Jim Grosbach4b905842013-09-20 23:08:21 +00003943 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003944 return false;
3945}
Eli Benderskyf483ff92012-12-20 19:05:53 +00003946
Jim Grosbach4b905842013-09-20 23:08:21 +00003947/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00003948/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003949bool AsmParser::parseDirectiveBundleAlignMode() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003950 checkForValidSection();
Eli Benderskyf483ff92012-12-20 19:05:53 +00003951
3952 // Expect a single argument: an expression that evaluates to a constant
3953 // in the inclusive range 0-30.
3954 SMLoc ExprLoc = getLexer().getLoc();
3955 int64_t AlignSizePow2;
Nirav Davea645433c2016-07-18 15:24:03 +00003956 if (parseAbsoluteExpression(AlignSizePow2) ||
3957 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
3958 "in '.bundle_align_mode' "
3959 "directive") ||
3960 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
3961 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00003962 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00003963
3964 // Because of AlignSizePow2's verified range we can safely truncate it to
3965 // unsigned.
3966 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3967 return false;
3968}
3969
Jim Grosbach4b905842013-09-20 23:08:21 +00003970/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00003971/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00003972bool AsmParser::parseDirectiveBundleLock() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003973 checkForValidSection();
Eli Bendersky802b6282013-01-07 21:51:08 +00003974 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00003975
Eli Bendersky802b6282013-01-07 21:51:08 +00003976 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3977 StringRef Option;
3978 SMLoc Loc = getTok().getLoc();
3979 const char *kInvalidOptionError =
Jim Grosbach4b905842013-09-20 23:08:21 +00003980 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00003981
Nirav Davea645433c2016-07-18 15:24:03 +00003982 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
3983 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
3984 check(getTok().isNot(AsmToken::EndOfStatement), Loc,
3985 "unexpected token after '.bundle_lock' directive option"))
3986 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00003987 AlignToEnd = true;
3988 }
3989
Eli Benderskyf483ff92012-12-20 19:05:53 +00003990 Lex();
3991
Eli Bendersky802b6282013-01-07 21:51:08 +00003992 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00003993 return false;
3994}
3995
Jim Grosbach4b905842013-09-20 23:08:21 +00003996/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00003997/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00003998bool AsmParser::parseDirectiveBundleUnlock() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003999 checkForValidSection();
Eli Benderskyf483ff92012-12-20 19:05:53 +00004000
Nirav Davea645433c2016-07-18 15:24:03 +00004001 if (parseToken(AsmToken::EndOfStatement,
4002 "unexpected token in '.bundle_unlock' directive"))
4003 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004004
4005 getStreamer().EmitBundleUnlock();
4006 return false;
4007}
4008
Jim Grosbach4b905842013-09-20 23:08:21 +00004009/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004010/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004011bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004012 checkForValidSection();
Eli Bendersky17233942013-01-15 22:59:42 +00004013
Petr Hosek67a94a72016-05-28 05:57:48 +00004014 SMLoc NumBytesLoc = Lexer.getLoc();
4015 const MCExpr *NumBytes;
4016 if (parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004017 return true;
4018
4019 int64_t FillExpr = 0;
4020 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Eli Bendersky17233942013-01-15 22:59:42 +00004021
Nirav Davea645433c2016-07-18 15:24:03 +00004022 if (parseToken(AsmToken::Comma,
4023 "unexpected token in '" + Twine(IDVal) + "' directive") ||
4024 parseAbsoluteExpression(FillExpr))
Eli Bendersky17233942013-01-15 22:59:42 +00004025 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004026 }
4027
Nirav Davea645433c2016-07-18 15:24:03 +00004028 if (parseToken(AsmToken::EndOfStatement,
4029 "unexpected token in '" + Twine(IDVal) + "' directive"))
4030 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004031
Eli Bendersky17233942013-01-15 22:59:42 +00004032 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004033 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004034
4035 return false;
4036}
4037
Jim Grosbach4b905842013-09-20 23:08:21 +00004038/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004039/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004040bool AsmParser::parseDirectiveLEB128(bool Signed) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004041 checkForValidSection();
Eli Bendersky17233942013-01-15 22:59:42 +00004042 const MCExpr *Value;
4043
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004044 for (;;) {
4045 if (parseExpression(Value))
4046 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004047
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004048 if (Signed)
4049 getStreamer().EmitSLEB128Value(Value);
4050 else
4051 getStreamer().EmitULEB128Value(Value);
Eli Bendersky17233942013-01-15 22:59:42 +00004052
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004053 if (getLexer().is(AsmToken::EndOfStatement))
4054 break;
4055
Nirav Davea645433c2016-07-18 15:24:03 +00004056 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
4057 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004058 }
Nirav Davea645433c2016-07-18 15:24:03 +00004059 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004060
4061 return false;
4062}
4063
Jim Grosbach4b905842013-09-20 23:08:21 +00004064/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004065/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004066bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004067 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbara5508c82009-06-30 00:33:19 +00004068 for (;;) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004069 StringRef Name;
Jim Grosbachebdf32f2011-09-15 17:56:49 +00004070 SMLoc Loc = getTok().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004071
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004072 if (parseIdentifier(Name))
Jim Grosbachebdf32f2011-09-15 17:56:49 +00004073 return Error(Loc, "expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004074
Jim Grosbach6f482002015-05-18 18:43:14 +00004075 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbara5508c82009-06-30 00:33:19 +00004076
Jim Grosbachebdf32f2011-09-15 17:56:49 +00004077 // Assembler local symbols don't make any sense here. Complain loudly.
4078 if (Sym->isTemporary())
4079 return Error(Loc, "non-local symbol required in directive");
4080
Saleem Abdulrasool4208b612013-08-09 01:52:03 +00004081 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4082 return Error(Loc, "unable to emit symbol attribute");
Daniel Dunbara5508c82009-06-30 00:33:19 +00004083
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004084 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara5508c82009-06-30 00:33:19 +00004085 break;
4086
Nirav Davea645433c2016-07-18 15:24:03 +00004087 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
4088 return true;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004089 }
4090 }
4091
Sean Callanan686ed8d2010-01-19 20:22:31 +00004092 Lex();
Jan Wen Voungc7682872010-09-30 01:09:20 +00004093 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004094}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004095
Jim Grosbach4b905842013-09-20 23:08:21 +00004096/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004097/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004098bool AsmParser::parseDirectiveComm(bool IsLocal) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004099 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00004100
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004101 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004102 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004103 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004104 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004105
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004106 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004107 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004108
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004109 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004110 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004111 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004112
4113 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004114 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004115 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004116 return true;
4117
4118 int64_t Pow2Alignment = 0;
4119 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004120 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004121 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004122 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004123 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004124 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004125
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004126 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4127 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004128 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4129
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004130 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004131 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4132 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004133 if (!isPowerOf2_64(Pow2Alignment))
4134 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4135 Pow2Alignment = Log2_64(Pow2Alignment);
4136 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004137 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004138
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004139 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner28ad7542009-07-09 17:25:12 +00004140 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004141
Sean Callanan686ed8d2010-01-19 20:22:31 +00004142 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004143
Chris Lattner28ad7542009-07-09 17:25:12 +00004144 // NOTE: a size of zero for a .comm should create a undefined symbol
4145 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004146 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004147 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004148 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004149
Eric Christopherbc818852010-05-14 01:38:54 +00004150 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004151 // may internally end up wanting an alignment in bytes.
4152 // FIXME: Diagnose overflow.
4153 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004154 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004155 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004156
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004157 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004158 return Error(IDLoc, "invalid symbol redefinition");
4159
Chris Lattner28ad7542009-07-09 17:25:12 +00004160 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004161 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004162 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004163 return false;
4164 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004165
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004166 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004167 return false;
4168}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004169
Jim Grosbach4b905842013-09-20 23:08:21 +00004170/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004171/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004172bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004173 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004174 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004175
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004176 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004177 if (parseToken(AsmToken::EndOfStatement,
4178 "unexpected token in '.abort' directive"))
4179 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004180
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004181 if (Str.empty())
4182 Error(Loc, ".abort detected. Assembly stopping.");
4183 else
4184 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004185 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004186
4187 return false;
4188}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004189
Jim Grosbach4b905842013-09-20 23:08:21 +00004190/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004191/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004192bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004193 // Allow the strings to have escaped octal character sequence.
4194 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004195 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004196
Nirav Davea645433c2016-07-18 15:24:03 +00004197 if (check(getTok().isNot(AsmToken::String),
4198 "expected string in '.include' directive") ||
4199 parseEscapedString(Filename) ||
4200 check(getTok().isNot(AsmToken::EndOfStatement),
4201 "unexpected token in '.include' directive") ||
4202 // Attempt to switch the lexer to the included file before consuming the
4203 // end of statement to avoid losing it when we switch.
4204 check(enterIncludeFile(Filename), IncludeLoc,
4205 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004206 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004207
4208 return false;
4209}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004210
Jim Grosbach4b905842013-09-20 23:08:21 +00004211/// parseDirectiveIncbin
Kevin Enderby109f25c2011-12-14 21:47:48 +00004212/// ::= .incbin "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004213bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004214 // Allow the strings to have escaped octal character sequence.
4215 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004216 SMLoc IncbinLoc = getTok().getLoc();
4217 if (check(getTok().isNot(AsmToken::String),
4218 "expected string in '.incbin' directive") ||
4219 parseEscapedString(Filename) ||
4220 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004221 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004222 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004223
4224 // Attempt to process the included file.
4225 if (processIncbinFile(Filename))
4226 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004227 return false;
4228}
4229
Jim Grosbach4b905842013-09-20 23:08:21 +00004230/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004231/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4232bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004233 TheCondStack.push_back(TheCondState);
4234 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004235 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004236 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004237 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004238 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004239 if (parseAbsoluteExpression(ExprValue) ||
4240 parseToken(AsmToken::EndOfStatement,
4241 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004242 return true;
4243
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004244 switch (DirKind) {
4245 default:
4246 llvm_unreachable("unsupported directive");
4247 case DK_IF:
4248 case DK_IFNE:
4249 break;
4250 case DK_IFEQ:
4251 ExprValue = ExprValue == 0;
4252 break;
4253 case DK_IFGE:
4254 ExprValue = ExprValue >= 0;
4255 break;
4256 case DK_IFGT:
4257 ExprValue = ExprValue > 0;
4258 break;
4259 case DK_IFLE:
4260 ExprValue = ExprValue <= 0;
4261 break;
4262 case DK_IFLT:
4263 ExprValue = ExprValue < 0;
4264 break;
4265 }
4266
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004267 TheCondState.CondMet = ExprValue;
4268 TheCondState.Ignore = !TheCondState.CondMet;
4269 }
4270
4271 return false;
4272}
4273
Jim Grosbach4b905842013-09-20 23:08:21 +00004274/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004275/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004276bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004277 TheCondStack.push_back(TheCondState);
4278 TheCondState.TheCond = AsmCond::IfCond;
4279
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004280 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004281 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004282 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004283 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004284
Nirav Davea645433c2016-07-18 15:24:03 +00004285 if (parseToken(AsmToken::EndOfStatement,
4286 "unexpected token in '.ifb' directive"))
4287 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004288
4289 TheCondState.CondMet = ExpectBlank == Str.empty();
4290 TheCondState.Ignore = !TheCondState.CondMet;
4291 }
4292
4293 return false;
4294}
4295
Jim Grosbach4b905842013-09-20 23:08:21 +00004296/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004297/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004298/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004299bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004300 TheCondStack.push_back(TheCondState);
4301 TheCondState.TheCond = AsmCond::IfCond;
4302
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004303 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004304 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004305 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004306 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004307
Nirav Davea645433c2016-07-18 15:24:03 +00004308 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4309 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004310
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004311 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004312
Nirav Davea645433c2016-07-18 15:24:03 +00004313 if (parseToken(AsmToken::EndOfStatement,
4314 "unexpected token in '.ifc' directive"))
4315 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004316
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004317 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004318 TheCondState.Ignore = !TheCondState.CondMet;
4319 }
4320
4321 return false;
4322}
4323
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004324/// parseDirectiveIfeqs
4325/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004326bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004327 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004328 if (ExpectEqual)
4329 TokError("expected string parameter for '.ifeqs' directive");
4330 else
4331 TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004332 eatToEndOfStatement();
4333 return true;
4334 }
4335
4336 StringRef String1 = getTok().getStringContents();
4337 Lex();
4338
4339 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004340 if (ExpectEqual)
4341 TokError("expected comma after first string for '.ifeqs' directive");
4342 else
4343 TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004344 eatToEndOfStatement();
4345 return true;
4346 }
4347
4348 Lex();
4349
4350 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004351 if (ExpectEqual)
4352 TokError("expected string parameter for '.ifeqs' directive");
4353 else
4354 TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004355 eatToEndOfStatement();
4356 return true;
4357 }
4358
4359 StringRef String2 = getTok().getStringContents();
4360 Lex();
4361
4362 TheCondStack.push_back(TheCondState);
4363 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004364 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004365 TheCondState.Ignore = !TheCondState.CondMet;
4366
4367 return false;
4368}
4369
Jim Grosbach4b905842013-09-20 23:08:21 +00004370/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004371/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004372bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004373 StringRef Name;
4374 TheCondStack.push_back(TheCondState);
4375 TheCondState.TheCond = AsmCond::IfCond;
4376
4377 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004378 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004379 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00004380 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4381 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4382 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004383
Jim Grosbach6f482002015-05-18 18:43:14 +00004384 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004385
4386 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004387 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004388 else
Craig Topper353eda42014-04-24 06:44:33 +00004389 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004390 TheCondState.Ignore = !TheCondState.CondMet;
4391 }
4392
4393 return false;
4394}
4395
Jim Grosbach4b905842013-09-20 23:08:21 +00004396/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004397/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004398bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004399 if (TheCondState.TheCond != AsmCond::IfCond &&
4400 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper2172ad62013-04-22 04:24:02 +00004401 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4402 " an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004403 TheCondState.TheCond = AsmCond::ElseIfCond;
4404
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004405 bool LastIgnoreState = false;
4406 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004407 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004408 if (LastIgnoreState || TheCondState.CondMet) {
4409 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004410 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004411 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004412 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004413 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004414 return true;
4415
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004416 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004417 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004418
Sean Callanan686ed8d2010-01-19 20:22:31 +00004419 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004420 TheCondState.CondMet = ExprValue;
4421 TheCondState.Ignore = !TheCondState.CondMet;
4422 }
4423
4424 return false;
4425}
4426
Jim Grosbach4b905842013-09-20 23:08:21 +00004427/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004428/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004429bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004430 if (parseToken(AsmToken::EndOfStatement,
4431 "unexpected token in '.else' directive"))
4432 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004433
4434 if (TheCondState.TheCond != AsmCond::IfCond &&
4435 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper2172ad62013-04-22 04:24:02 +00004436 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4437 ".elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004438 TheCondState.TheCond = AsmCond::ElseCond;
4439 bool LastIgnoreState = false;
4440 if (!TheCondStack.empty())
4441 LastIgnoreState = TheCondStack.back().Ignore;
4442 if (LastIgnoreState || TheCondState.CondMet)
4443 TheCondState.Ignore = true;
4444 else
4445 TheCondState.Ignore = false;
4446
4447 return false;
4448}
4449
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004450/// parseDirectiveEnd
4451/// ::= .end
4452bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004453 if (parseToken(AsmToken::EndOfStatement,
4454 "unexpected token in '.end' directive"))
4455 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004456
4457 while (Lexer.isNot(AsmToken::Eof))
4458 Lex();
4459
4460 return false;
4461}
4462
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004463/// parseDirectiveError
4464/// ::= .err
4465/// ::= .error [string]
4466bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4467 if (!TheCondStack.empty()) {
4468 if (TheCondStack.back().Ignore) {
4469 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004470 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004471 }
4472 }
4473
4474 if (!WithMessage)
4475 return Error(L, ".err encountered");
4476
4477 StringRef Message = ".error directive invoked in source file";
4478 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4479 if (Lexer.isNot(AsmToken::String)) {
4480 TokError(".error argument must be a string");
4481 eatToEndOfStatement();
4482 return true;
4483 }
4484
4485 Message = getTok().getStringContents();
4486 Lex();
4487 }
4488
4489 Error(L, Message);
4490 return true;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004491}
4492
Nico Weber404012b2014-07-24 16:26:06 +00004493/// parseDirectiveWarning
4494/// ::= .warning [string]
4495bool AsmParser::parseDirectiveWarning(SMLoc L) {
4496 if (!TheCondStack.empty()) {
4497 if (TheCondStack.back().Ignore) {
4498 eatToEndOfStatement();
4499 return false;
4500 }
4501 }
4502
4503 StringRef Message = ".warning directive invoked in source file";
4504 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4505 if (Lexer.isNot(AsmToken::String)) {
4506 TokError(".warning argument must be a string");
4507 eatToEndOfStatement();
4508 return true;
4509 }
4510
4511 Message = getTok().getStringContents();
4512 Lex();
4513 }
4514
4515 Warning(L, Message);
4516 return false;
4517}
4518
Jim Grosbach4b905842013-09-20 23:08:21 +00004519/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004520/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00004521bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004522 if (parseToken(AsmToken::EndOfStatement,
4523 "unexpected token in '.endif' directive"))
4524 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004525
Jim Grosbach4b905842013-09-20 23:08:21 +00004526 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004527 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4528 ".else");
4529 if (!TheCondStack.empty()) {
4530 TheCondState = TheCondStack.back();
4531 TheCondStack.pop_back();
4532 }
4533
4534 return false;
4535}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00004536
Eli Bendersky17233942013-01-15 22:59:42 +00004537void AsmParser::initializeDirectiveKindMap() {
4538 DirectiveKindMap[".set"] = DK_SET;
4539 DirectiveKindMap[".equ"] = DK_EQU;
4540 DirectiveKindMap[".equiv"] = DK_EQUIV;
4541 DirectiveKindMap[".ascii"] = DK_ASCII;
4542 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4543 DirectiveKindMap[".string"] = DK_STRING;
4544 DirectiveKindMap[".byte"] = DK_BYTE;
4545 DirectiveKindMap[".short"] = DK_SHORT;
4546 DirectiveKindMap[".value"] = DK_VALUE;
4547 DirectiveKindMap[".2byte"] = DK_2BYTE;
4548 DirectiveKindMap[".long"] = DK_LONG;
4549 DirectiveKindMap[".int"] = DK_INT;
4550 DirectiveKindMap[".4byte"] = DK_4BYTE;
4551 DirectiveKindMap[".quad"] = DK_QUAD;
4552 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00004553 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00004554 DirectiveKindMap[".single"] = DK_SINGLE;
4555 DirectiveKindMap[".float"] = DK_FLOAT;
4556 DirectiveKindMap[".double"] = DK_DOUBLE;
4557 DirectiveKindMap[".align"] = DK_ALIGN;
4558 DirectiveKindMap[".align32"] = DK_ALIGN32;
4559 DirectiveKindMap[".balign"] = DK_BALIGN;
4560 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4561 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4562 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4563 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4564 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4565 DirectiveKindMap[".org"] = DK_ORG;
4566 DirectiveKindMap[".fill"] = DK_FILL;
4567 DirectiveKindMap[".zero"] = DK_ZERO;
4568 DirectiveKindMap[".extern"] = DK_EXTERN;
4569 DirectiveKindMap[".globl"] = DK_GLOBL;
4570 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00004571 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4572 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4573 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4574 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4575 DirectiveKindMap[".reference"] = DK_REFERENCE;
4576 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4577 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4578 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4579 DirectiveKindMap[".comm"] = DK_COMM;
4580 DirectiveKindMap[".common"] = DK_COMMON;
4581 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4582 DirectiveKindMap[".abort"] = DK_ABORT;
4583 DirectiveKindMap[".include"] = DK_INCLUDE;
4584 DirectiveKindMap[".incbin"] = DK_INCBIN;
4585 DirectiveKindMap[".code16"] = DK_CODE16;
4586 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4587 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004588 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00004589 DirectiveKindMap[".irp"] = DK_IRP;
4590 DirectiveKindMap[".irpc"] = DK_IRPC;
4591 DirectiveKindMap[".endr"] = DK_ENDR;
4592 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4593 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4594 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4595 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004596 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4597 DirectiveKindMap[".ifge"] = DK_IFGE;
4598 DirectiveKindMap[".ifgt"] = DK_IFGT;
4599 DirectiveKindMap[".ifle"] = DK_IFLE;
4600 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00004601 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00004602 DirectiveKindMap[".ifb"] = DK_IFB;
4603 DirectiveKindMap[".ifnb"] = DK_IFNB;
4604 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004605 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00004606 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00004607 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00004608 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4609 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4610 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4611 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4612 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004613 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00004614 DirectiveKindMap[".endif"] = DK_ENDIF;
4615 DirectiveKindMap[".skip"] = DK_SKIP;
4616 DirectiveKindMap[".space"] = DK_SPACE;
4617 DirectiveKindMap[".file"] = DK_FILE;
4618 DirectiveKindMap[".line"] = DK_LINE;
4619 DirectiveKindMap[".loc"] = DK_LOC;
4620 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004621 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
4622 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
4623 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00004624 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
David Majnemer408b5e62016-02-05 01:55:49 +00004625 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004626 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
4627 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Eli Bendersky17233942013-01-15 22:59:42 +00004628 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4629 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4630 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4631 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4632 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4633 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4634 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4635 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4636 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4637 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4638 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4639 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4640 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4641 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4642 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4643 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4644 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4645 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4646 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4647 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4648 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00004649 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00004650 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4651 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4652 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00004653 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00004654 DirectiveKindMap[".endm"] = DK_ENDM;
4655 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4656 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004657 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004658 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00004659 DirectiveKindMap[".warning"] = DK_WARNING;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00004660 DirectiveKindMap[".reloc"] = DK_RELOC;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00004661}
4662
Jim Grosbach4b905842013-09-20 23:08:21 +00004663MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004664 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004665
Rafael Espindola34b9c512012-06-03 23:57:14 +00004666 unsigned NestLevel = 0;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004667 for (;;) {
4668 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00004669 if (getLexer().is(AsmToken::Eof)) {
4670 Error(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00004671 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004672 }
4673
Rafael Espindola34b9c512012-06-03 23:57:14 +00004674 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00004675 (getTok().getIdentifier() == ".rept" ||
4676 getTok().getIdentifier() == ".irp" ||
4677 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004678 ++NestLevel;
4679 }
4680
4681 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00004682 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004683 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004684 EndToken = getTok();
4685 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004686 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4687 TokError("unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00004688 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004689 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004690 break;
4691 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004692 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004693 }
4694
Rafael Espindola34b9c512012-06-03 23:57:14 +00004695 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004696 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004697 }
4698
4699 const char *BodyStart = StartToken.getLoc().getPointer();
4700 const char *BodyEnd = EndToken.getLoc().getPointer();
4701 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4702
Rafael Espindola34b9c512012-06-03 23:57:14 +00004703 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004704 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00004705 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004706}
4707
Jim Grosbach4b905842013-09-20 23:08:21 +00004708void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00004709 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004710 OS << ".endr\n";
4711
Rafael Espindola3560ff22014-08-27 20:03:13 +00004712 std::unique_ptr<MemoryBuffer> Instantiation =
4713 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004714
Rafael Espindola34b9c512012-06-03 23:57:14 +00004715 // Create the macro instantiation object and add to the current macro
4716 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00004717 MacroInstantiation *MI = new MacroInstantiation(
4718 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00004719 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004720
Rafael Espindola34b9c512012-06-03 23:57:14 +00004721 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00004722 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00004723 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00004724 Lex();
4725}
4726
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004727/// parseDirectiveRept
4728/// ::= .rep | .rept count
4729bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004730 const MCExpr *CountExpr;
4731 SMLoc CountLoc = getTok().getLoc();
4732 if (parseExpression(CountExpr))
4733 return true;
4734
Rafael Espindola34b9c512012-06-03 23:57:14 +00004735 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00004736 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004737 eatToEndOfStatement();
4738 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4739 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004740
Nirav Davea645433c2016-07-18 15:24:03 +00004741 if (check(Count < 0, CountLoc, "Count is negative") ||
4742 parseToken(AsmToken::EndOfStatement,
4743 "unexpected token in '" + Dir + "' directive"))
4744 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004745
4746 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004747 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00004748 if (!M)
4749 return true;
4750
4751 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4752 // to hold the macro body with substitutions.
4753 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004754 raw_svector_ostream OS(Buf);
4755 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00004756 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4757 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00004758 return true;
4759 }
Jim Grosbach4b905842013-09-20 23:08:21 +00004760 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004761
4762 return false;
4763}
4764
Jim Grosbach4b905842013-09-20 23:08:21 +00004765/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00004766/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00004767bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00004768 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00004769 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00004770 if (check(parseIdentifier(Parameter.Name),
4771 "expected identifier in '.irp' directive") ||
4772 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
4773 parseMacroArguments(nullptr, A) ||
4774 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004775 return true;
4776
Rafael Espindola768b41c2012-06-15 14:02:34 +00004777 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004778 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00004779 if (!M)
4780 return true;
4781
4782 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4783 // to hold the macro body with substitutions.
4784 SmallString<256> Buf;
4785 raw_svector_ostream OS(Buf);
4786
Craig Topper84008482015-10-10 05:38:14 +00004787 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00004788 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4789 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00004790 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004791 return true;
4792 }
4793
Jim Grosbach4b905842013-09-20 23:08:21 +00004794 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00004795
4796 return false;
4797}
4798
Jim Grosbach4b905842013-09-20 23:08:21 +00004799/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004800/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00004801bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00004802 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00004803 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00004804
4805 if (check(parseIdentifier(Parameter.Name),
4806 "expected identifier in '.irpc' directive") ||
4807 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
4808 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004809 return true;
4810
4811 if (A.size() != 1 || A.front().size() != 1)
4812 return TokError("unexpected token in '.irpc' directive");
4813
4814 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00004815 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
4816 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004817
4818 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004819 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004820 if (!M)
4821 return true;
4822
4823 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4824 // to hold the macro body with substitutions.
4825 SmallString<256> Buf;
4826 raw_svector_ostream OS(Buf);
4827
4828 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004829 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00004830 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004831 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004832
Toma Tabacu217116e2015-04-27 10:50:29 +00004833 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
4834 // This is undocumented, but GAS seems to support it.
4835 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004836 return true;
4837 }
4838
Jim Grosbach4b905842013-09-20 23:08:21 +00004839 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004840
4841 return false;
4842}
4843
Jim Grosbach4b905842013-09-20 23:08:21 +00004844bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004845 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00004846 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004847
4848 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00004849 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004850 assert(getLexer().is(AsmToken::EndOfStatement));
4851
Jim Grosbach4b905842013-09-20 23:08:21 +00004852 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004853 return false;
4854}
Rafael Espindola12d73d12010-09-11 16:45:15 +00004855
Jim Grosbach4b905842013-09-20 23:08:21 +00004856bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00004857 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00004858 const MCExpr *Value;
4859 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004860 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00004861 return true;
4862 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4863 if (!MCE)
4864 return Error(ExprLoc, "unexpected expression in _emit");
4865 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00004866 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00004867 return Error(ExprLoc, "literal value out of range for directive");
4868
Craig Topper7d5b2312015-10-10 05:25:02 +00004869 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00004870 return false;
4871}
4872
Jim Grosbach4b905842013-09-20 23:08:21 +00004873bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00004874 const MCExpr *Value;
4875 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004876 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00004877 return true;
4878 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4879 if (!MCE)
4880 return Error(ExprLoc, "unexpected expression in align");
4881 uint64_t IntValue = MCE->getValue();
4882 if (!isPowerOf2_64(IntValue))
4883 return Error(ExprLoc, "literal value not a power of two greater then zero");
4884
Craig Topper7d5b2312015-10-10 05:25:02 +00004885 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00004886 return false;
4887}
4888
Chad Rosierf43fcf52013-02-13 21:27:17 +00004889// We are comparing pointers, but the pointers are relative to a single string.
4890// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00004891static int rewritesSort(const AsmRewrite *AsmRewriteA,
4892 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00004893 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4894 return -1;
4895 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4896 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004897
Chad Rosierfce4fab2013-04-08 17:43:47 +00004898 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4899 // rewrite to the same location. Make sure the SizeDirective rewrite is
4900 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4901 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00004902 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4903 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004904 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00004905
Jim Grosbach4b905842013-09-20 23:08:21 +00004906 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4907 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004908 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00004909 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00004910}
4911
Jim Grosbach4b905842013-09-20 23:08:21 +00004912bool AsmParser::parseMSInlineAsm(
4913 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4914 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4915 SmallVectorImpl<std::string> &Constraints,
4916 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4917 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00004918 SmallVector<void *, 4> InputDecls;
4919 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00004920 SmallVector<bool, 4> InputDeclsAddressOf;
4921 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00004922 SmallVector<std::string, 4> InputConstraints;
4923 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00004924 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00004925
Benjamin Kramer1a136112013-02-15 20:37:21 +00004926 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00004927
4928 // Prime the lexer.
4929 Lex();
4930
4931 // While we have input, parse each statement.
4932 unsigned InputIdx = 0;
4933 unsigned OutputIdx = 0;
4934 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00004935 // Parse curly braces marking block start/end
4936 if (parseCurlyBlockScope(AsmStrRewrites))
4937 continue;
4938
Eli Friedman0f4871d2012-10-22 23:58:19 +00004939 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00004940 if (parseStatement(Info, &SI))
Chad Rosierf1f6a722012-10-19 22:57:33 +00004941 return true;
Chad Rosier8bce6642012-10-18 15:49:34 +00004942
Chad Rosier149e8e02012-12-12 22:45:52 +00004943 if (Info.ParseError)
4944 return true;
4945
Benjamin Kramer1a136112013-02-15 20:37:21 +00004946 if (Info.Opcode == ~0U)
4947 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00004948
Benjamin Kramer1a136112013-02-15 20:37:21 +00004949 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00004950
Benjamin Kramer1a136112013-02-15 20:37:21 +00004951 // Build the list of clobbers, outputs and inputs.
4952 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00004953 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00004954
Benjamin Kramer1a136112013-02-15 20:37:21 +00004955 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00004956 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00004957 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00004958
Benjamin Kramer1a136112013-02-15 20:37:21 +00004959 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00004960 if (Operand.isReg() && !Operand.needAddressOf() &&
4961 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00004962 unsigned NumDefs = Desc.getNumDefs();
4963 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00004964 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4965 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00004966 continue;
4967 }
4968
4969 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00004970 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00004971 if (SymName.empty())
4972 continue;
4973
David Blaikie960ea3f2014-06-08 16:18:35 +00004974 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00004975 if (!OpDecl)
4976 continue;
4977
4978 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00004979 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00004980 if (isOutput) {
4981 ++InputIdx;
4982 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00004983 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00004984 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00004985 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00004986 } else {
4987 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00004988 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4989 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00004990 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00004991 }
Chad Rosier8bce6642012-10-18 15:49:34 +00004992 }
Reid Kleckneree088972013-12-10 18:27:32 +00004993
4994 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00004995 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
4996 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00004997 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00004998 }
4999
5000 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005001 NumOutputs = OutputDecls.size();
5002 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005003
5004 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005005 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5006 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5007 ClobberRegs.end());
5008 Clobbers.assign(ClobberRegs.size(), std::string());
5009 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5010 raw_string_ostream OS(Clobbers[I]);
5011 IP->printRegName(OS, ClobberRegs[I]);
5012 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005013
5014 // Merge the various outputs and inputs. Output are expected first.
5015 if (NumOutputs || NumInputs) {
5016 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005017 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005018 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005019 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005020 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005021 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005022 }
5023 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005024 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005025 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005026 }
5027 }
5028
5029 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005030 std::string AsmStringIR;
5031 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005032 StringRef ASMString =
5033 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5034 const char *AsmStart = ASMString.begin();
5035 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005036 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005037 for (const AsmRewrite &AR : AsmStrRewrites) {
5038 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005039 if (Kind == AOK_Delete)
5040 continue;
5041
David Majnemer8114c1a2014-06-23 02:17:16 +00005042 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005043 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005044
Chad Rosier120eefd2013-03-19 17:32:17 +00005045 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005046 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005047 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005048
Chad Rosier37e755c2012-10-23 17:43:43 +00005049 // Skip the original expression.
5050 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005051 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005052 continue;
5053 }
5054
Chad Rosierff10ed12013-04-12 16:26:42 +00005055 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005056 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005057 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005058 default:
5059 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005060 case AOK_Imm:
David Majnemer8114c1a2014-06-23 02:17:16 +00005061 OS << "$$" << AR.Val;
Chad Rosier11c42f22012-10-26 18:04:20 +00005062 break;
5063 case AOK_ImmPrefix:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005064 OS << "$$";
Chad Rosier8bce6642012-10-18 15:49:34 +00005065 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005066 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005067 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005068 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005069 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005070 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005071 break;
5072 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005073 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005074 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005075 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005076 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005077 default: break;
5078 case 8: OS << "byte ptr "; break;
5079 case 16: OS << "word ptr "; break;
5080 case 32: OS << "dword ptr "; break;
5081 case 64: OS << "qword ptr "; break;
5082 case 80: OS << "xword ptr "; break;
5083 case 128: OS << "xmmword ptr "; break;
5084 case 256: OS << "ymmword ptr "; break;
5085 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005086 break;
5087 case AOK_Emit:
5088 OS << ".byte";
5089 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005090 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005091 // MS alignment directives are measured in bytes. If the native assembler
5092 // measures alignment in bytes, we can pass it straight through.
5093 OS << ".align";
5094 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5095 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005096
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005097 // Alignment is in log2 form, so print that instead and skip the original
5098 // immediate.
5099 unsigned Val = AR.Val;
5100 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005101 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005102 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5103 break;
5104 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005105 case AOK_EVEN:
5106 OS << ".even";
5107 break;
Chad Rosierf0e87202012-10-25 20:41:34 +00005108 case AOK_DotOperator:
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005109 // Insert the dot if the user omitted it.
Alp Tokere69170a2014-06-26 22:52:05 +00005110 OS.flush();
5111 if (AsmStringIR.back() != '.')
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005112 OS << '.';
David Majnemer8114c1a2014-06-23 02:17:16 +00005113 OS << AR.Val;
Chad Rosierf0e87202012-10-25 20:41:34 +00005114 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005115 case AOK_EndOfStatement:
5116 OS << "\n\t";
5117 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005118 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005119
Chad Rosier8bce6642012-10-18 15:49:34 +00005120 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005121 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005122 }
5123
5124 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005125 if (AsmStart != AsmEnd)
5126 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005127
5128 AsmString = OS.str();
5129 return false;
5130}
5131
Pete Cooper80d21cb2015-06-22 19:35:57 +00005132namespace llvm {
5133namespace MCParserUtils {
5134
5135/// Returns whether the given symbol is used anywhere in the given expression,
5136/// or subexpressions.
5137static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5138 switch (Value->getKind()) {
5139 case MCExpr::Binary: {
5140 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5141 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5142 isSymbolUsedInExpression(Sym, BE->getRHS());
5143 }
5144 case MCExpr::Target:
5145 case MCExpr::Constant:
5146 return false;
5147 case MCExpr::SymbolRef: {
5148 const MCSymbol &S =
5149 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5150 if (S.isVariable())
5151 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5152 return &S == Sym;
5153 }
5154 case MCExpr::Unary:
5155 return isSymbolUsedInExpression(
5156 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5157 }
5158
5159 llvm_unreachable("Unknown expr kind!");
5160}
5161
5162bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5163 MCAsmParser &Parser, MCSymbol *&Sym,
5164 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005165
5166 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005167 SMLoc EqualLoc = Parser.getTok().getLoc();
Pete Cooper80d21cb2015-06-22 19:35:57 +00005168
5169 if (Parser.parseExpression(Value)) {
5170 Parser.TokError("missing expression");
5171 Parser.eatToEndOfStatement();
5172 return true;
5173 }
5174
5175 // Note: we don't count b as used in "a = b". This is to allow
5176 // a = b
5177 // b = c
5178
Nirav Davefd910412016-06-17 16:06:17 +00005179 if (Parser.getTok().isNot(AsmToken::EndOfStatement))
Pete Cooper80d21cb2015-06-22 19:35:57 +00005180 return Parser.TokError("unexpected token in assignment");
5181
5182 // Eat the end of statement marker.
5183 Parser.Lex();
5184
5185 // Validate that the LHS is allowed to be a variable (either it has not been
5186 // used as a symbol, or it is an absolute symbol).
5187 Sym = Parser.getContext().lookupSymbol(Name);
5188 if (Sym) {
5189 // Diagnose assignment to a label.
5190 //
5191 // FIXME: Diagnostics. Note the location of the definition as a label.
5192 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5193 if (isSymbolUsedInExpression(Sym, Value))
5194 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005195 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5196 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005197 ; // Allow redefinitions of undefined symbols only used in directives.
5198 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5199 ; // Allow redefinitions of variables that haven't yet been used.
5200 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5201 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5202 else if (!Sym->isVariable())
5203 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5204 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5205 return Parser.Error(EqualLoc,
5206 "invalid reassignment of non-absolute variable '" +
5207 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005208 } else if (Name == ".") {
Rafael Espindola7ae65d82015-11-04 23:59:18 +00005209 Parser.getStreamer().emitValueToOffset(Value, 0);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005210 return false;
5211 } else
5212 Sym = Parser.getContext().getOrCreateSymbol(Name);
5213
5214 Sym->setRedefinable(allow_redef);
5215
5216 return false;
5217}
5218
5219} // namespace MCParserUtils
5220} // namespace llvm
5221
Daniel Dunbar01e36072010-07-17 02:26:10 +00005222/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005223MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
5224 MCStreamer &Out, const MCAsmInfo &MAI) {
Jim Grosbach345768c2011-08-16 18:33:49 +00005225 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005226}