blob: 2db7504b37761306da8851ea72ca9b48abd48bde [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"
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +000037#include "llvm/Support/CommandLine.h"
Benjamin Kramer4efe5062012-01-28 15:28:41 +000038#include "llvm/Support/ErrorHandling.h"
Jim Grosbach76346c32011-06-29 16:05:14 +000039#include "llvm/Support/MathExtras.h"
Kevin Enderbye233dda2010-06-28 21:45:58 +000040#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000041#include "llvm/Support/SourceMgr.h"
Chris Lattner36e02122009-06-21 20:54:55 +000042#include "llvm/Support/raw_ostream.h"
Nick Lewycky0de20af2010-12-19 20:43:38 +000043#include <cctype>
Benjamin Kramerd59664f2014-04-29 23:26:49 +000044#include <deque>
Chad Rosier8bce6642012-10-18 15:49:34 +000045#include <set>
46#include <string>
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000047#include <vector>
Chris Lattnerb0133452009-06-21 20:16:42 +000048using namespace llvm;
49
Eric Christophera7c32732012-12-18 00:30:54 +000050MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
Nick Lewyckyac612272012-10-19 07:00:09 +000051
Daniel Dunbar86033402010-07-12 17:54:38 +000052namespace {
Eli Benderskya313ae62013-01-16 18:56:50 +000053/// \brief Helper types for tracking macro definitions.
54typedef std::vector<AsmToken> MCAsmMacroArgument;
55typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000056
57struct MCAsmMacroParameter {
58 StringRef Name;
59 MCAsmMacroArgument Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000060 bool Required;
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +000061 bool Vararg;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000062
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +000063 MCAsmMacroParameter() : Required(false), Vararg(false) {}
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000064};
65
Eli Benderskya313ae62013-01-16 18:56:50 +000066typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
67
68struct MCAsmMacro {
69 StringRef Name;
70 StringRef Body;
71 MCAsmMacroParameters Parameters;
72
73public:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +000074 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
75 : Name(N), Body(B), Parameters(std::move(P)) {}
Eli Benderskya313ae62013-01-16 18:56:50 +000076};
77
Daniel Dunbar43235712010-07-18 18:54:11 +000078/// \brief Helper class for storing information about an active macro
79/// instantiation.
80struct MacroInstantiation {
Daniel Dunbar43235712010-07-18 18:54:11 +000081 /// The location of the instantiation.
82 SMLoc InstantiationLoc;
83
Daniel Dunbar40f1d852012-12-01 01:38:48 +000084 /// The buffer where parsing should resume upon instantiation completion.
85 int ExitBuffer;
86
Daniel Dunbar43235712010-07-18 18:54:11 +000087 /// The location where parsing should resume upon instantiation completion.
88 SMLoc ExitLoc;
89
Nico Weber155dccd12014-07-24 17:08:39 +000090 /// The depth of TheCondStack at the start of the instantiation.
91 size_t CondStackDepth;
92
Daniel Dunbar43235712010-07-18 18:54:11 +000093public:
Rafael Espindola9eef18c2014-08-27 19:49:03 +000094 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
Daniel Dunbar43235712010-07-18 18:54:11 +000095};
96
Eli Friedman0f4871d2012-10-22 23:58:19 +000097struct ParseStatementInfo {
Jim Grosbach4b905842013-09-20 23:08:21 +000098 /// \brief The parsed operands from the last parsed statement.
David Blaikie960ea3f2014-06-08 16:18:35 +000099 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000100
Jim Grosbach4b905842013-09-20 23:08:21 +0000101 /// \brief The opcode from the last parsed instruction.
Eli Friedman0f4871d2012-10-22 23:58:19 +0000102 unsigned Opcode;
103
Jim Grosbach4b905842013-09-20 23:08:21 +0000104 /// \brief Was there an error parsing the inline assembly?
Chad Rosier149e8e02012-12-12 22:45:52 +0000105 bool ParseError;
106
Eli Friedman0f4871d2012-10-22 23:58:19 +0000107 SmallVectorImpl<AsmRewrite> *AsmRewrites;
108
Craig Topper353eda42014-04-24 06:44:33 +0000109 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000110 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier149e8e02012-12-12 22:45:52 +0000111 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000112};
113
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000114/// \brief The concrete assembly parser instance.
115class AsmParser : public MCAsmParser {
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000116 AsmParser(const AsmParser &) = delete;
117 void operator=(const AsmParser &) = delete;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000118private:
119 AsmLexer Lexer;
120 MCContext &Ctx;
121 MCStreamer &Out;
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000122 const MCAsmInfo &MAI;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000123 SourceMgr &SrcMgr;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000124 SourceMgr::DiagHandlerTy SavedDiagHandler;
125 void *SavedDiagContext;
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000126 std::unique_ptr<MCAsmParserExtension> PlatformParser;
Rafael Espindola82065cb2011-04-11 21:49:50 +0000127
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000128 /// This is the current buffer index we're lexing from as managed by the
129 /// SourceMgr object.
Alp Tokera55b95b2014-07-06 10:33:31 +0000130 unsigned CurBuffer;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000131
132 AsmCond TheCondState;
133 std::vector<AsmCond> TheCondStack;
134
Jim Grosbach4b905842013-09-20 23:08:21 +0000135 /// \brief maps directive names to handler methods in parser
Eli Bendersky17233942013-01-15 22:59:42 +0000136 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000137 /// addDirectiveHandler.
Eli Bendersky17233942013-01-15 22:59:42 +0000138 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000139
Jim Grosbach4b905842013-09-20 23:08:21 +0000140 /// \brief Map of currently defined macros.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000141 StringMap<MCAsmMacro> MacroMap;
Daniel Dunbarc1f58ec2010-07-18 18:47:21 +0000142
Jim Grosbach4b905842013-09-20 23:08:21 +0000143 /// \brief Stack of active macro instantiations.
Daniel Dunbar43235712010-07-18 18:54:11 +0000144 std::vector<MacroInstantiation*> ActiveMacros;
145
Jim Grosbach4b905842013-09-20 23:08:21 +0000146 /// \brief List of bodies of anonymous macros.
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +0000147 std::deque<MCAsmMacro> MacroLikeBodies;
148
Daniel Dunbar828984f2010-07-18 18:38:02 +0000149 /// Boolean tracking whether macro substitution is enabled.
Eli Benderskyc2f6f922013-01-14 18:08:41 +0000150 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000151
Toma Tabacu217116e2015-04-27 10:50:29 +0000152 /// \brief Keeps track of how many .macro's have been instantiated.
153 unsigned NumOfMacroInstantiations;
154
Daniel Dunbar43325c42010-09-09 22:42:56 +0000155 /// Flag tracking whether any errors have been encountered.
156 unsigned HadError : 1;
157
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000158 /// The values from the last parsed cpp hash file line comment if any.
159 StringRef CppHashFilename;
160 int64_t CppHashLineNumber;
161 SMLoc CppHashLoc;
Alp Tokera55b95b2014-07-06 10:33:31 +0000162 unsigned CppHashBuf;
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000163 /// When generating dwarf for assembly source files we need to calculate the
164 /// logical line number based on the last parsed cpp hash file line comment
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000165 /// and current line. Since this is slow and messes up the SourceMgr's
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000166 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
167 SMLoc LastQueryIDLoc;
Alp Tokera55b95b2014-07-06 10:33:31 +0000168 unsigned LastQueryBuffer;
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000169 unsigned LastQueryLine;
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000170
Devang Patela173ee52012-01-31 18:14:05 +0000171 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
172 unsigned AssemblerDialect;
173
Jim Grosbach4b905842013-09-20 23:08:21 +0000174 /// \brief is Darwin compatibility enabled?
Preston Gurd05500642012-09-19 20:36:12 +0000175 bool IsDarwin;
176
Jim Grosbach4b905842013-09-20 23:08:21 +0000177 /// \brief Are we parsing ms-style inline assembly?
Chad Rosier49963552012-10-13 00:26:04 +0000178 bool ParsingInlineAsm;
179
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000180public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000181 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000182 const MCAsmInfo &MAI);
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000183 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000184
Craig Topper59be68f2014-03-08 07:14:16 +0000185 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000186
Craig Topper59be68f2014-03-08 07:14:16 +0000187 void addDirectiveHandler(StringRef Directive,
188 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000189 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000190 }
191
Toma Tabacu11e14a92015-04-21 11:50:52 +0000192 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
193 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
194 }
195
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000196public:
197 /// @name MCAsmParser Interface
198 /// {
199
Craig Topper59be68f2014-03-08 07:14:16 +0000200 SourceMgr &getSourceManager() override { return SrcMgr; }
201 MCAsmLexer &getLexer() override { return Lexer; }
202 MCContext &getContext() override { return Ctx; }
203 MCStreamer &getStreamer() override { return Out; }
204 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000205 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000206 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000207 else
208 return AssemblerDialect;
209 }
Craig Topper59be68f2014-03-08 07:14:16 +0000210 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000211 AssemblerDialect = i;
212 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000213
Craig Topper59be68f2014-03-08 07:14:16 +0000214 void Note(SMLoc L, const Twine &Msg,
215 ArrayRef<SMRange> Ranges = None) override;
216 bool Warning(SMLoc L, const Twine &Msg,
217 ArrayRef<SMRange> Ranges = None) override;
218 bool Error(SMLoc L, const Twine &Msg,
219 ArrayRef<SMRange> Ranges = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000220
Craig Topper59be68f2014-03-08 07:14:16 +0000221 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000222
Craig Topper59be68f2014-03-08 07:14:16 +0000223 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
224 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000225
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000226 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000227 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier37e755c2012-10-23 17:43:43 +0000228 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000229 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000230 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000231 const MCInstrInfo *MII, const MCInstPrinter *IP,
232 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000233
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000234 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000235 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
236 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
237 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000238 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
239 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000240 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000241
Jim Grosbach4b905842013-09-20 23:08:21 +0000242 /// \brief Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000243 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000244 bool parseIdentifier(StringRef &Res) override;
245 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000246
Craig Topper59be68f2014-03-08 07:14:16 +0000247 void checkForValidSection() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000248 /// }
249
250private:
Daniel Dunbare5444a82010-09-09 22:42:59 +0000251
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000252 bool parseStatement(ParseStatementInfo &Info,
253 MCAsmParserSemaCallback *SI);
Jim Grosbach4b905842013-09-20 23:08:21 +0000254 void eatToEndOfLine();
Craig Topper3c76c522015-09-20 23:35:59 +0000255 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000256
Jim Grosbach4b905842013-09-20 23:08:21 +0000257 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000258 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000259 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000260 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000261 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000262 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000263
Eli Benderskya313ae62013-01-16 18:56:50 +0000264 /// \brief Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000265 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000266
267 /// \brief Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000268 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000269
270 /// \brief Lookup a previously defined macro.
271 /// \param Name Macro name.
272 /// \returns Pointer to macro. NULL if no such macro was defined.
Jim Grosbach4b905842013-09-20 23:08:21 +0000273 const MCAsmMacro* lookupMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000274
275 /// \brief Define a new macro with the given name and information.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000276 void defineMacro(StringRef Name, MCAsmMacro Macro);
Eli Benderskya313ae62013-01-16 18:56:50 +0000277
278 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
Jim Grosbach4b905842013-09-20 23:08:21 +0000279 void undefineMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000280
281 /// \brief Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000282 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000283
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000284 /// \brief Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000285 ///
286 /// \param M The macro.
287 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000288 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000289
290 /// \brief Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000291 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000292
David Majnemer91fc4c22014-01-29 18:57:46 +0000293 /// \brief Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000294 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000295
296 /// \brief Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000297 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000298
Jim Grosbach4b905842013-09-20 23:08:21 +0000299 void printMacroInstantiations();
300 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Dmitri Gribenko3238fb72013-05-05 00:40:33 +0000301 ArrayRef<SMRange> Ranges = None) const {
Chris Lattner72845262011-10-16 05:47:55 +0000302 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000303 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000304 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000305
Jim Grosbach4b905842013-09-20 23:08:21 +0000306 /// \brief Enter the specified file. This returns true on failure.
307 bool enterIncludeFile(const std::string &Filename);
308
309 /// \brief Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000310 /// This returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000311 bool processIncbinFile(const std::string &Filename);
Daniel Dunbar43235712010-07-18 18:54:11 +0000312
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000313 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000314 /// current token is not set; clients should ensure Lex() is called
315 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000316 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000317 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000318 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000319 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000320
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000321 /// \brief Parse up to the end of statement and a return the contents from the
322 /// current token until the end of the statement; the current token on exit
323 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000324 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000325
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000326 /// \brief Parse until the end of a statement or a comma is encountered,
327 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000328 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000329
Jim Grosbach4b905842013-09-20 23:08:21 +0000330 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +0000331 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000332
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000333 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
334 MCBinaryExpr::Opcode &Kind);
335
Jim Grosbach4b905842013-09-20 23:08:21 +0000336 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
337 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
338 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000339
Jim Grosbach4b905842013-09-20 23:08:21 +0000340 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000341
Eli Bendersky17233942013-01-15 22:59:42 +0000342 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000343 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000344 DK_NO_DIRECTIVE, // Placeholder
345 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000346 DK_RELOC,
David Woodhoused6de0d92014-02-01 16:20:59 +0000347 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
348 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky96522722013-01-11 22:55:28 +0000349 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000350 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
Kevin Enderby3aeada22013-08-28 17:50:59 +0000351 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000352 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
353 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
354 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
355 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000356 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
Sid Manning51c35602015-03-18 14:20:54 +0000357 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
358 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
Eli Bendersky17233942013-01-15 22:59:42 +0000359 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000360 DK_CV_FILE, DK_CV_LOC, DK_CV_LINETABLE, DK_CV_INLINE_LINETABLE,
361 DK_CV_STRINGTABLE, DK_CV_FILECHECKSUMS,
Eli Bendersky17233942013-01-15 22:59:42 +0000362 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
363 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
364 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
365 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
366 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000367 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
Nico Weber155dccd12014-07-24 17:08:39 +0000368 DK_MACROS_ON, DK_MACROS_OFF,
369 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000370 DK_SLEB128, DK_ULEB128,
Nico Weber404012b2014-07-24 16:26:06 +0000371 DK_ERR, DK_ERROR, DK_WARNING,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000372 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000373 };
374
Jim Grosbach4b905842013-09-20 23:08:21 +0000375 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000376 /// directives parsed by this class.
377 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000378
379 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000380 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000381 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Jim Grosbach4b905842013-09-20 23:08:21 +0000382 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
David Woodhoused6de0d92014-02-01 16:20:59 +0000383 bool parseDirectiveOctaValue(); // ".octa"
Jim Grosbach4b905842013-09-20 23:08:21 +0000384 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
385 bool parseDirectiveFill(); // ".fill"
386 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000387 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000388 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
389 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000390 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000391 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000392
Eli Bendersky17233942013-01-15 22:59:42 +0000393 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000394 bool parseDirectiveFile(SMLoc DirectiveLoc);
395 bool parseDirectiveLine();
396 bool parseDirectiveLoc();
397 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000398
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000399 // ".cv_file", ".cv_loc", ".cv_linetable", "cv_inline_linetable"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000400 bool parseDirectiveCVFile();
401 bool parseDirectiveCVLoc();
402 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000403 bool parseDirectiveCVInlineLinetable();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000404 bool parseDirectiveCVStringTable();
405 bool parseDirectiveCVFileChecksums();
406
Eli Bendersky17233942013-01-15 22:59:42 +0000407 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000408 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000409 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000410 bool parseDirectiveCFISections();
411 bool parseDirectiveCFIStartProc();
412 bool parseDirectiveCFIEndProc();
413 bool parseDirectiveCFIDefCfaOffset();
414 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
415 bool parseDirectiveCFIAdjustCfaOffset();
416 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
417 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
418 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
419 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
420 bool parseDirectiveCFIRememberState();
421 bool parseDirectiveCFIRestoreState();
422 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
423 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
424 bool parseDirectiveCFIEscape();
425 bool parseDirectiveCFISignalFrame();
426 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000427
428 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000429 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000430 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000431 bool parseDirectiveEndMacro(StringRef Directive);
432 bool parseDirectiveMacro(SMLoc DirectiveLoc);
433 bool parseDirectiveMacrosOnOff(StringRef Directive);
Eli Bendersky17233942013-01-15 22:59:42 +0000434
Eli Benderskyf483ff92012-12-20 19:05:53 +0000435 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000436 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000437 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000438 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000439 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000440 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000441
Eli Bendersky17233942013-01-15 22:59:42 +0000442 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000443 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000444
445 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000446 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000447
Jim Grosbach4b905842013-09-20 23:08:21 +0000448 /// \brief Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000449 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000450 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000451
Jim Grosbach4b905842013-09-20 23:08:21 +0000452 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000453
Jim Grosbach4b905842013-09-20 23:08:21 +0000454 bool parseDirectiveAbort(); // ".abort"
455 bool parseDirectiveInclude(); // ".include"
456 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000457
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000458 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
459 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000460 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000461 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000462 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000463 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000464 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
465 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000466 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000467 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
468 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
469 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
470 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000471 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000472
Jim Grosbach4b905842013-09-20 23:08:21 +0000473 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000474 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000475
Rafael Espindola34b9c512012-06-03 23:57:14 +0000476 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000477 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
478 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000479 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000480 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000481 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
482 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
483 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000484
Chad Rosierc7f552c2013-02-12 21:33:51 +0000485 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000486 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000487 size_t Len);
488
489 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000490 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000491
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000492 // "end"
493 bool parseDirectiveEnd(SMLoc DirectiveLoc);
494
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000495 // ".err" or ".error"
496 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000497
Nico Weber404012b2014-07-24 16:26:06 +0000498 // ".warning"
499 bool parseDirectiveWarning(SMLoc DirectiveLoc);
500
Eli Bendersky17233942013-01-15 22:59:42 +0000501 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000502};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000503}
Daniel Dunbar86033402010-07-12 17:54:38 +0000504
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000505namespace llvm {
506
507extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000508extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000509extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000510
511}
512
Chris Lattnerc35681b2010-01-19 19:46:13 +0000513enum { DEFAULT_ADDRSPACE = 0 };
514
David Blaikie9f380a32015-03-16 18:06:57 +0000515AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
516 const MCAsmInfo &MAI)
517 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
518 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
Alp Tokera55b95b2014-07-06 10:33:31 +0000519 MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
Oliver Stannardcf6bfb12014-11-03 12:19:03 +0000520 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000521 // Save the old handler.
522 SavedDiagHandler = SrcMgr.getDiagHandler();
523 SavedDiagContext = SrcMgr.getDiagContext();
524 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000525 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000526 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000527
Daniel Dunbarc5011082010-07-12 18:12:02 +0000528 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000529 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
530 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000531 PlatformParser.reset(createCOFFAsmParser());
532 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000533 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000534 PlatformParser.reset(createDarwinAsmParser());
535 IsDarwin = true;
536 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000537 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000538 PlatformParser.reset(createELFAsmParser());
539 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000540 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000541
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000542 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000543 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000544
545 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000546}
547
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000548AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000549 assert((HadError || ActiveMacros.empty()) &&
550 "Unexpected active macro instantiation!");
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000551}
552
Jim Grosbach4b905842013-09-20 23:08:21 +0000553void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000554 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000555 for (std::vector<MacroInstantiation *>::const_reverse_iterator
556 it = ActiveMacros.rbegin(),
557 ie = ActiveMacros.rend();
558 it != ie; ++it)
559 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000560 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000561}
562
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000563void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
564 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
565 printMacroInstantiations();
566}
567
Chris Lattnera3a06812011-10-16 04:47:35 +0000568bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000569 if(getTargetParser().getTargetOptions().MCNoWarn)
570 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000571 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Chris Lattnera3a06812011-10-16 04:47:35 +0000572 return Error(L, Msg, Ranges);
Jim Grosbach4b905842013-09-20 23:08:21 +0000573 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
574 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000575 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000576}
577
Chris Lattnera3a06812011-10-16 04:47:35 +0000578bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000579 HadError = true;
Jim Grosbach4b905842013-09-20 23:08:21 +0000580 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
581 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000582 return true;
583}
584
Jim Grosbach4b905842013-09-20 23:08:21 +0000585bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000586 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000587 unsigned NewBuf =
588 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
589 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000590 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000591
Sean Callanan7a77eae2010-01-21 00:19:58 +0000592 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000593 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000594 return false;
595}
Daniel Dunbar43235712010-07-18 18:54:11 +0000596
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000597/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000598/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000599/// returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000600bool AsmParser::processIncbinFile(const std::string &Filename) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000601 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000602 unsigned NewBuf =
603 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
604 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000605 return true;
606
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000607 // Pick up the bytes from the file and emit them.
Rafael Espindola64e1af82013-07-02 15:49:13 +0000608 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
Kevin Enderby109f25c2011-12-14 21:47:48 +0000609 return false;
610}
611
Alp Tokera55b95b2014-07-06 10:33:31 +0000612void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
613 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000614 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
615 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000616}
617
Sean Callanan7a77eae2010-01-21 00:19:58 +0000618const AsmToken &AsmParser::Lex() {
619 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000620
Sean Callanan7a77eae2010-01-21 00:19:58 +0000621 if (tok->is(AsmToken::Eof)) {
622 // If this is the end of an included file, pop the parent file off the
623 // include stack.
624 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
625 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000626 jumpToLoc(ParentIncludeLoc);
Sean Callanan7a77eae2010-01-21 00:19:58 +0000627 tok = &Lexer.Lex();
628 }
629 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000630
Sean Callanan7a77eae2010-01-21 00:19:58 +0000631 if (tok->is(AsmToken::Error))
Daniel Dunbard8a18452010-07-18 18:31:45 +0000632 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencer530ce852010-10-09 11:00:50 +0000633
Sean Callanan7a77eae2010-01-21 00:19:58 +0000634 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000635}
636
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000637bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000638 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000639 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000640 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000641
Chris Lattner36e02122009-06-21 20:54:55 +0000642 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000643 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000644
645 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000646 AsmCond StartingCondState = TheCondState;
647
Kevin Enderby6469fc22011-11-01 22:27:22 +0000648 // If we are generating dwarf for assembly source files save the initial text
649 // section and generate a .file directive.
650 if (getContext().getGenDwarfForAssembly()) {
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000651 MCSection *Sec = getStreamer().getCurrentSection().first;
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000652 if (!Sec->getBeginSymbol()) {
653 MCSymbol *SectionStartSym = getContext().createTempSymbol();
654 getStreamer().EmitLabel(SectionStartSym);
655 Sec->setBeginSymbol(SectionStartSym);
656 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000657 bool InsertResult = getContext().addGenDwarfSection(Sec);
658 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000659 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000660 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
661 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000662 }
663
Chris Lattner73f36112009-07-02 21:53:43 +0000664 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000665 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman0f4871d2012-10-22 23:58:19 +0000666 ParseStatementInfo Info;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000667 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000668 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000669
Daniel Dunbar43325c42010-09-09 22:42:56 +0000670 // We had an error, validate that one was emitted and recover by skipping to
671 // the next line.
672 assert(HadError && "Parse statement returned an error, but none emitted!");
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000673 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000674 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000675
676 if (TheCondState.TheCond != StartingCondState.TheCond ||
677 TheCondState.Ignore != StartingCondState.Ignore)
678 return TokError("unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000679
680 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000681 const auto &LineTables = getContext().getMCDwarfLineTables();
682 if (!LineTables.empty()) {
683 unsigned Index = 0;
684 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
685 if (File.Name.empty() && Index != 0)
686 TokError("unassigned file number: " + Twine(Index) +
687 " for .file directives");
688 ++Index;
689 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000690 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000691
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000692 // Check to see that all assembler local symbols were actually defined.
693 // Targets that don't do subsections via symbols may not want this, though,
694 // so conservatively exclude them. Only do this if we're finalizing, though,
695 // as otherwise we won't necessarilly have seen everything yet.
696 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
Craig Topper84008482015-10-10 05:38:14 +0000697 for (const auto &TableEntry : getContext().getSymbols()) {
698 MCSymbol *Sym = TableEntry.getValue();
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000699 // Variable symbols may not be marked as defined, so check those
700 // explicitly. If we know it's a variable, we have a definition for
701 // the purposes of this check.
702 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
703 // FIXME: We would really like to refer back to where the symbol was
704 // first referenced for a source location. We need to add something
705 // to track that. Currently, we just point to the end of the file.
Jim Grosbach0fdd5722015-10-16 22:07:59 +0000706 return Error(getLexer().getLoc(), "assembler local symbol '" +
707 Sym->getName() + "' not defined");
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000708 }
709 }
710
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000711 // Finalize the output stream if there are no errors and if the client wants
712 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000713 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000714 Out.Finish();
715
Oliver Stannard07b43d32015-11-17 09:58:07 +0000716 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000717}
718
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000719void AsmParser::checkForValidSection() {
Peter Collingbourne2f495b92013-04-17 21:18:16 +0000720 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
Daniel Dunbare5444a82010-09-09 22:42:59 +0000721 TokError("expected section directive before assembly directive");
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000722 Out.InitSections(false);
Daniel Dunbare5444a82010-09-09 22:42:59 +0000723 }
724}
725
Jim Grosbach4b905842013-09-20 23:08:21 +0000726/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000727void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000728 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Sean Callanan686ed8d2010-01-19 20:22:31 +0000729 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000730
Chris Lattnere5074c42009-06-22 01:29:09 +0000731 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000732 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan686ed8d2010-01-19 20:22:31 +0000733 Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000734}
735
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000736StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000737 const char *Start = getTok().getLoc().getPointer();
738
Jim Grosbach4b905842013-09-20 23:08:21 +0000739 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000740 Lex();
741
742 const char *End = getTok().getLoc().getPointer();
743 return StringRef(Start, End - Start);
744}
Chris Lattner78db3622009-06-22 05:51:26 +0000745
Jim Grosbach4b905842013-09-20 23:08:21 +0000746StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000747 const char *Start = getTok().getLoc().getPointer();
748
749 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000750 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000751 Lex();
752
753 const char *End = getTok().getLoc().getPointer();
754 return StringRef(Start, End - Start);
755}
756
Jim Grosbach4b905842013-09-20 23:08:21 +0000757/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000758/// NOTE: This assumes the leading '(' has already been consumed.
759///
760/// parenexpr ::= expr)
761///
Jim Grosbach4b905842013-09-20 23:08:21 +0000762bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
763 if (parseExpression(Res))
764 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000765 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +0000766 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000767 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000768 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +0000769 return false;
770}
Chris Lattner78db3622009-06-22 05:51:26 +0000771
Jim Grosbach4b905842013-09-20 23:08:21 +0000772/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000773/// NOTE: This assumes the leading '[' has already been consumed.
774///
775/// bracketexpr ::= expr]
776///
Jim Grosbach4b905842013-09-20 23:08:21 +0000777bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
778 if (parseExpression(Res))
779 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000780 if (Lexer.isNot(AsmToken::RBrac))
781 return TokError("expected ']' in brackets expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000782 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000783 Lex();
784 return false;
785}
786
Jim Grosbach4b905842013-09-20 23:08:21 +0000787/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000788/// primaryexpr ::= (parenexpr
789/// primaryexpr ::= symbol
790/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +0000791/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +0000792/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +0000793bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000794 SMLoc FirstTokenLoc = getLexer().getLoc();
795 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
796 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +0000797 default:
798 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +0000799 // If we have an error assume that we've already handled it.
800 case AsmToken::Error:
801 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000802 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000803 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000804 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000805 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000806 Res = MCUnaryExpr::createLNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000807 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +0000808 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +0000809 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +0000810 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +0000811 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +0000812 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000813 if (parseIdentifier(Identifier)) {
David Majnemer0c58bc62013-09-25 10:47:21 +0000814 if (FirstTokenKind == AsmToken::Dollar) {
815 if (Lexer.getMAI().getDollarIsPC()) {
816 // This is a '$' reference, which references the current PC. Emit a
817 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000818 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +0000819 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000820 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +0000821 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +0000822 EndLoc = FirstTokenLoc;
823 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +0000824 }
825 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +0000826 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000827 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000828 // Parse symbol variant
829 std::pair<StringRef, StringRef> Split;
830 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +0000831 if (FirstTokenKind == AsmToken::String) {
832 if (Lexer.is(AsmToken::At)) {
833 Lexer.Lex(); // eat @
834 SMLoc AtLoc = getLexer().getLoc();
835 StringRef VName;
836 if (parseIdentifier(VName))
837 return Error(AtLoc, "expected symbol variant after '@'");
838
839 Split = std::make_pair(Identifier, VName);
840 }
841 } else {
842 Split = Identifier.split('@');
843 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000844 } else if (Lexer.is(AsmToken::LParen)) {
845 Lexer.Lex(); // eat (
846 StringRef VName;
847 parseIdentifier(VName);
848 if (Lexer.isNot(AsmToken::RParen)) {
849 return Error(Lexer.getTok().getLoc(),
850 "unexpected token in variant, expected ')'");
851 }
852 Lexer.Lex(); // eat )
853 Split = std::make_pair(Identifier, VName);
854 }
Daniel Dunbar24764322010-08-24 19:13:42 +0000855
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000856 EndLoc = SMLoc::getFromPointer(Identifier.end());
857
Daniel Dunbard20cda02009-10-16 01:34:54 +0000858 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +0000859 StringRef SymbolName = Identifier;
860 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +0000861
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000862 // Lookup the symbol variant if used.
David Peixotto8ad70b32013-12-04 22:43:20 +0000863 if (Split.second.size()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000864 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +0000865 if (Variant != MCSymbolRefExpr::VK_Invalid) {
866 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +0000867 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +0000868 Variant = MCSymbolRefExpr::VK_None;
869 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +0000870 return Error(SMLoc::getFromPointer(Split.second.begin()),
871 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000872 }
873 }
Daniel Dunbar55992562010-03-15 23:51:06 +0000874
Jim Grosbach6f482002015-05-18 18:43:14 +0000875 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +0000876
Daniel Dunbard20cda02009-10-16 01:34:54 +0000877 // If this is an absolute variable reference, substitute it now to preserve
878 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +0000879 if (Sym->isVariable() &&
880 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +0000881 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +0000882 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +0000883
Vedant Kumar86dbd922015-08-31 17:44:53 +0000884 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +0000885 return false;
886 }
887
888 // Otherwise create a symbol ref.
Jim Grosbach13760bd2015-05-30 01:25:56 +0000889 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Chris Lattner78db3622009-06-22 05:51:26 +0000890 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +0000891 }
David Woodhousef42a6662014-02-01 16:20:54 +0000892 case AsmToken::BigNum:
893 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +0000894 case AsmToken::Integer: {
895 SMLoc Loc = getTok().getLoc();
896 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +0000897 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000898 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000899 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +0000900 // Look for 'b' or 'f' following an Integer as a directional label
901 if (Lexer.getKind() == AsmToken::Identifier) {
902 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +0000903 // Lookup the symbol variant if used.
904 std::pair<StringRef, StringRef> Split = IDVal.split('@');
905 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
906 if (Split.first.size() != IDVal.size()) {
907 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +0000908 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +0000909 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000910 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +0000911 }
Jim Grosbach4b905842013-09-20 23:08:21 +0000912 if (IDVal == "f" || IDVal == "b") {
913 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +0000914 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +0000915 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +0000916 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderby0510b482010-05-17 23:08:19 +0000917 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000918 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +0000919 Lex(); // Eat identifier.
920 }
921 }
Chris Lattner78db3622009-06-22 05:51:26 +0000922 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +0000923 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +0000924 case AsmToken::Real: {
925 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +0000926 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +0000927 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000928 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +0000929 Lex(); // Eat token.
930 return false;
931 }
Chris Lattner6b55cb92010-04-14 04:40:28 +0000932 case AsmToken::Dot: {
933 // This is a '.' reference, which references the current PC. Emit a
934 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000935 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +0000936 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000937 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000938 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +0000939 Lex(); // Eat identifier.
940 return false;
941 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000942 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000943 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +0000944 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000945 case AsmToken::LBrac:
946 if (!PlatformParser->HasBracketExpressions())
947 return TokError("brackets expression not supported on this target");
948 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +0000949 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000950 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000951 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000952 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000953 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000954 Res = MCUnaryExpr::createMinus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000955 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000956 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000957 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000958 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000959 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000960 Res = MCUnaryExpr::createPlus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000961 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000962 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000963 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000964 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000965 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000966 Res = MCUnaryExpr::createNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000967 return false;
Chris Lattner78db3622009-06-22 05:51:26 +0000968 }
969}
Chris Lattner7fdbce72009-06-22 06:32:03 +0000970
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000971bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +0000972 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000973 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +0000974}
975
Daniel Dunbar55f16672010-09-17 02:47:07 +0000976const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +0000977AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000978 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +0000979 // Ask the target implementation about this expression first.
980 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
981 if (NewE)
982 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000983 // Recurse over the given expression, rebuilding it to apply the given variant
984 // if there is exactly one symbol.
985 switch (E->getKind()) {
986 case MCExpr::Target:
987 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +0000988 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000989
990 case MCExpr::SymbolRef: {
991 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
992
993 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000994 TokError("invalid variant on expression '" + getTok().getIdentifier() +
995 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000996 return E;
997 }
998
Jim Grosbach13760bd2015-05-30 01:25:56 +0000999 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001000 }
1001
1002 case MCExpr::Unary: {
1003 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001004 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001005 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001006 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001007 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001008 }
1009
1010 case MCExpr::Binary: {
1011 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001012 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1013 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001014
1015 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001016 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001017
Jim Grosbach4b905842013-09-20 23:08:21 +00001018 if (!LHS)
1019 LHS = BE->getLHS();
1020 if (!RHS)
1021 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001022
Jim Grosbach13760bd2015-05-30 01:25:56 +00001023 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001024 }
1025 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001026
Craig Toppera2886c22012-02-07 05:05:23 +00001027 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001028}
1029
Jim Grosbach4b905842013-09-20 23:08:21 +00001030/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001031///
Jim Grosbachbd164242011-08-20 16:24:13 +00001032/// expr ::= expr &&,|| expr -> lowest.
1033/// expr ::= expr |,^,&,! expr
1034/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1035/// expr ::= expr <<,>> expr
1036/// expr ::= expr +,- expr
1037/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001038/// expr ::= primaryexpr
1039///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001040bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001041 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001042 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001043 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001044 return true;
1045
Daniel Dunbar55f16672010-09-17 02:47:07 +00001046 // As a special case, we support 'a op b @ modifier' by rewriting the
1047 // expression to include the modifier. This is inefficient, but in general we
1048 // expect users to use 'a@modifier op b'.
1049 if (Lexer.getKind() == AsmToken::At) {
1050 Lex();
1051
1052 if (Lexer.isNot(AsmToken::Identifier))
1053 return TokError("unexpected symbol modifier following '@'");
1054
1055 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001056 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001057 if (Variant == MCSymbolRefExpr::VK_Invalid)
1058 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1059
Jim Grosbach4b905842013-09-20 23:08:21 +00001060 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001061 if (!ModifiedRes) {
1062 return TokError("invalid modifier '" + getTok().getIdentifier() +
1063 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001064 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001065
Daniel Dunbar55f16672010-09-17 02:47:07 +00001066 Res = ModifiedRes;
1067 Lex();
1068 }
1069
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001070 // Try to constant fold it up front, if possible.
1071 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001072 if (Res->evaluateAsAbsolute(Value))
1073 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001074
1075 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001076}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001077
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001078bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001079 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001080 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001081}
1082
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001083bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1084 SMLoc &EndLoc) {
1085 if (parseParenExpr(Res, EndLoc))
1086 return true;
1087
1088 for (; ParenDepth > 0; --ParenDepth) {
1089 if (parseBinOpRHS(1, Res, EndLoc))
1090 return true;
1091
1092 // We don't Lex() the last RParen.
1093 // This is the same behavior as parseParenExpression().
1094 if (ParenDepth - 1 > 0) {
1095 if (Lexer.isNot(AsmToken::RParen))
1096 return TokError("expected ')' in parentheses expression");
1097 EndLoc = Lexer.getTok().getEndLoc();
1098 Lex();
1099 }
1100 }
1101 return false;
1102}
1103
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001104bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001105 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001106
Daniel Dunbar75630b32009-06-30 02:10:03 +00001107 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001108 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001109 return true;
1110
Jim Grosbach13760bd2015-05-30 01:25:56 +00001111 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001112 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001113
1114 return false;
1115}
1116
David Majnemer0993e0b2015-10-26 03:15:34 +00001117static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1118 MCBinaryExpr::Opcode &Kind,
1119 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001120 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001121 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001122 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001123
Jim Grosbach4b905842013-09-20 23:08:21 +00001124 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001125 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001126 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001127 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001128 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001129 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001130 return 1;
1131
Jim Grosbach4b905842013-09-20 23:08:21 +00001132 // Low Precedence: |, &, ^
1133 //
1134 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001135 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001136 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001137 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001138 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001139 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001140 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001141 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001142 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001143 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001144
Jim Grosbach4b905842013-09-20 23:08:21 +00001145 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001146 case AsmToken::EqualEqual:
1147 Kind = MCBinaryExpr::EQ;
1148 return 3;
1149 case AsmToken::ExclaimEqual:
1150 case AsmToken::LessGreater:
1151 Kind = MCBinaryExpr::NE;
1152 return 3;
1153 case AsmToken::Less:
1154 Kind = MCBinaryExpr::LT;
1155 return 3;
1156 case AsmToken::LessEqual:
1157 Kind = MCBinaryExpr::LTE;
1158 return 3;
1159 case AsmToken::Greater:
1160 Kind = MCBinaryExpr::GT;
1161 return 3;
1162 case AsmToken::GreaterEqual:
1163 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001164 return 3;
1165
Jim Grosbach4b905842013-09-20 23:08:21 +00001166 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001167 case AsmToken::LessLess:
1168 Kind = MCBinaryExpr::Shl;
1169 return 4;
1170 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001171 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001172 return 4;
1173
Jim Grosbach4b905842013-09-20 23:08:21 +00001174 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001175 case AsmToken::Plus:
1176 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001177 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001178 case AsmToken::Minus:
1179 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001180 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001181
Jim Grosbach4b905842013-09-20 23:08:21 +00001182 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001183 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001184 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001185 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001186 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001187 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001188 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001189 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001190 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001191 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001192 }
1193}
1194
David Majnemer0993e0b2015-10-26 03:15:34 +00001195static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1196 MCBinaryExpr::Opcode &Kind,
1197 bool ShouldUseLogicalShr) {
1198 switch (K) {
1199 default:
1200 return 0; // not a binop.
1201
1202 // Lowest Precedence: &&, ||
1203 case AsmToken::AmpAmp:
1204 Kind = MCBinaryExpr::LAnd;
1205 return 2;
1206 case AsmToken::PipePipe:
1207 Kind = MCBinaryExpr::LOr;
1208 return 1;
1209
1210 // Low Precedence: ==, !=, <>, <, <=, >, >=
1211 case AsmToken::EqualEqual:
1212 Kind = MCBinaryExpr::EQ;
1213 return 3;
1214 case AsmToken::ExclaimEqual:
1215 case AsmToken::LessGreater:
1216 Kind = MCBinaryExpr::NE;
1217 return 3;
1218 case AsmToken::Less:
1219 Kind = MCBinaryExpr::LT;
1220 return 3;
1221 case AsmToken::LessEqual:
1222 Kind = MCBinaryExpr::LTE;
1223 return 3;
1224 case AsmToken::Greater:
1225 Kind = MCBinaryExpr::GT;
1226 return 3;
1227 case AsmToken::GreaterEqual:
1228 Kind = MCBinaryExpr::GTE;
1229 return 3;
1230
1231 // Low Intermediate Precedence: +, -
1232 case AsmToken::Plus:
1233 Kind = MCBinaryExpr::Add;
1234 return 4;
1235 case AsmToken::Minus:
1236 Kind = MCBinaryExpr::Sub;
1237 return 4;
1238
1239 // High Intermediate Precedence: |, &, ^
1240 //
1241 // FIXME: gas seems to support '!' as an infix operator?
1242 case AsmToken::Pipe:
1243 Kind = MCBinaryExpr::Or;
1244 return 5;
1245 case AsmToken::Caret:
1246 Kind = MCBinaryExpr::Xor;
1247 return 5;
1248 case AsmToken::Amp:
1249 Kind = MCBinaryExpr::And;
1250 return 5;
1251
1252 // Highest Precedence: *, /, %, <<, >>
1253 case AsmToken::Star:
1254 Kind = MCBinaryExpr::Mul;
1255 return 6;
1256 case AsmToken::Slash:
1257 Kind = MCBinaryExpr::Div;
1258 return 6;
1259 case AsmToken::Percent:
1260 Kind = MCBinaryExpr::Mod;
1261 return 6;
1262 case AsmToken::LessLess:
1263 Kind = MCBinaryExpr::Shl;
1264 return 6;
1265 case AsmToken::GreaterGreater:
1266 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1267 return 6;
1268 }
1269}
1270
1271unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1272 MCBinaryExpr::Opcode &Kind) {
1273 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1274 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1275 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1276}
1277
Jim Grosbach4b905842013-09-20 23:08:21 +00001278/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001279/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001280bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001281 SMLoc &EndLoc) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001282 while (1) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001283 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001284 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001285
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001286 // If the next token is lower precedence than we are allowed to eat, return
1287 // successfully with what we ate already.
1288 if (TokPrec < Precedence)
1289 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001290
Sean Callanan686ed8d2010-01-19 20:22:31 +00001291 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001292
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001293 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001294 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001295 if (parsePrimaryExpr(RHS, EndLoc))
1296 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001297
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001298 // If BinOp binds less tightly with RHS than the operator after RHS, let
1299 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001300 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001301 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001302 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1303 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001304
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001305 // Merge LHS and RHS according to operator.
Jim Grosbach13760bd2015-05-30 01:25:56 +00001306 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001307 }
1308}
1309
Chris Lattner36e02122009-06-21 20:54:55 +00001310/// ParseStatement:
1311/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001312/// ::= Label* Directive ...Operands... EndOfStatement
1313/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001314bool AsmParser::parseStatement(ParseStatementInfo &Info,
1315 MCAsmParserSemaCallback *SI) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001316 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar8271d1bb2010-05-23 18:36:34 +00001317 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001318 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001319 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001320 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001321
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001322 // Statements always start with an identifier or are a full line comment.
Sean Callanan936b0d32010-01-19 21:44:56 +00001323 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001324 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001325 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001326 int64_t LocalLabelVal = -1;
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001327 // A full line comment is a '#' as the first token.
Kevin Enderby72553612011-09-13 23:45:18 +00001328 if (Lexer.is(AsmToken::Hash))
Jim Grosbach4b905842013-09-20 23:08:21 +00001329 return parseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar3f561042011-03-25 17:47:14 +00001330
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001331 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001332 if (Lexer.is(AsmToken::Integer)) {
1333 LocalLabelVal = getTok().getIntVal();
1334 if (LocalLabelVal < 0) {
1335 if (!TheCondState.Ignore)
1336 return TokError("unexpected token at start of statement");
1337 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001338 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001339 IDVal = getTok().getString();
1340 Lex(); // Consume the integer token to be used as an identifier token.
1341 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands41b4a6b2010-07-12 08:16:59 +00001342 if (!TheCondState.Ignore)
1343 return TokError("unexpected token at start of statement");
Kevin Enderby0510b482010-05-17 23:08:19 +00001344 }
1345 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001346 } else if (Lexer.is(AsmToken::Dot)) {
1347 // Treat '.' as a valid identifier in this context.
1348 Lex();
1349 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001350 } else if (Lexer.is(AsmToken::LCurly)) {
1351 // Treat '{' as a valid identifier in this context.
1352 Lex();
1353 IDVal = "{";
1354
1355 } else if (Lexer.is(AsmToken::RCurly)) {
1356 // Treat '}' as a valid identifier in this context.
1357 Lex();
1358 IDVal = "}";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001359 } else if (parseIdentifier(IDVal)) {
Chris Lattner926885c2010-04-17 18:14:27 +00001360 if (!TheCondState.Ignore)
1361 return TokError("unexpected token at start of statement");
1362 IDVal = "";
1363 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001364
Chris Lattner926885c2010-04-17 18:14:27 +00001365 // Handle conditional assembly here before checking for skipping. We
1366 // have to do this so that .endif isn't skipped in a ".if 0" block for
1367 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001368 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001369 DirectiveKindMap.find(IDVal);
1370 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1371 ? DK_NO_DIRECTIVE
1372 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001373 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001374 default:
1375 break;
1376 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001377 case DK_IFEQ:
1378 case DK_IFGE:
1379 case DK_IFGT:
1380 case DK_IFLE:
1381 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001382 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001383 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001384 case DK_IFB:
1385 return parseDirectiveIfb(IDLoc, true);
1386 case DK_IFNB:
1387 return parseDirectiveIfb(IDLoc, false);
1388 case DK_IFC:
1389 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001390 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001391 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001392 case DK_IFNC:
1393 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001394 case DK_IFNES:
1395 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001396 case DK_IFDEF:
1397 return parseDirectiveIfdef(IDLoc, true);
1398 case DK_IFNDEF:
1399 case DK_IFNOTDEF:
1400 return parseDirectiveIfdef(IDLoc, false);
1401 case DK_ELSEIF:
1402 return parseDirectiveElseIf(IDLoc);
1403 case DK_ELSE:
1404 return parseDirectiveElse(IDLoc);
1405 case DK_ENDIF:
1406 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001407 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001408
Eli Bendersky88024712013-01-16 19:32:36 +00001409 // Ignore the statement if in the middle of inactive conditional
1410 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001411 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001412 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001413 return false;
1414 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001415
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001416 // FIXME: Recurse on local labels?
1417
1418 // See what kind of statement we have.
1419 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001420 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001421 if (!getTargetParser().isLabel(ID))
1422 break;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001423 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00001424
Chris Lattner36e02122009-06-21 20:54:55 +00001425 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001426 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001427
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001428 // Diagnose attempt to use '.' as a label.
1429 if (IDVal == ".")
1430 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1431
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001432 // Diagnose attempt to use a variable as a label.
1433 //
1434 // FIXME: Diagnostics. Note the location of the definition as a label.
1435 // FIXME: This doesn't diagnose assignment to a symbol which has been
1436 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001437 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001438 if (LocalLabelVal == -1) {
1439 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001440 StringRef RewrittenLabel =
1441 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1442 assert(RewrittenLabel.size() &&
1443 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001444 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1445 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001446 IDVal = RewrittenLabel;
1447 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001448 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001449 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001450 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
David Majnemer58cb80c2014-12-24 10:27:50 +00001451
1452 Sym->redefineIfPossible();
1453
Daniel Dunbardeb7ba92010-05-05 19:01:00 +00001454 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001455 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencer530ce852010-10-09 11:00:50 +00001456
Daniel Dunbare73b2672009-08-26 22:13:22 +00001457 // Emit the label.
Chad Rosierf3feab32013-01-07 20:34:12 +00001458 if (!ParsingInlineAsm)
1459 Out.EmitLabel(Sym);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001460
Kevin Enderbye7739d42011-12-09 18:09:40 +00001461 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001462 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001463 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001464 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1465 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001466
Tim Northover1744d0a2013-10-25 12:49:50 +00001467 getTargetParser().onLabelParsed(Sym);
1468
Daniel Dunbar8271d1bb2010-05-23 18:36:34 +00001469 // Consume any end of statement token, if present, to avoid spurious
1470 // AddBlankLine calls().
1471 if (Lexer.is(AsmToken::EndOfStatement)) {
1472 Lex();
1473 if (Lexer.is(AsmToken::Eof))
1474 return false;
1475 }
1476
Eli Friedman0f4871d2012-10-22 23:58:19 +00001477 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001478 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001479
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001480 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001481 if (!getTargetParser().equalIsAsmAssignment())
1482 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001483 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001484 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001485
Jim Grosbach4b905842013-09-20 23:08:21 +00001486 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001487
1488 default: // Normal instruction or directive.
1489 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001490 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001491
1492 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001493 if (areMacrosEnabled())
1494 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1495 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001496 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001497
Michael J. Spencer530ce852010-10-09 11:00:50 +00001498 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001499
Eli Bendersky17233942013-01-15 22:59:42 +00001500 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001501 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001502 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001503 //
Eli Bendersky17233942013-01-15 22:59:42 +00001504 // 1. The target-specific assembly parser. Some directives are target
1505 // specific or may potentially behave differently on certain targets.
1506 // 2. Asm parser extensions. For example, platform-specific parsers
1507 // (like the ELF parser) register themselves as extensions.
1508 // 3. The generic directive parser implemented by this class. These are
1509 // all the directives that behave in a target and platform independent
1510 // manner, or at least have a default behavior that's shared between
1511 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001512
Eli Bendersky17233942013-01-15 22:59:42 +00001513 // First query the target-specific parser. It will return 'true' if it
1514 // isn't interested in this directive.
Akira Hatanakad3590752012-07-05 19:09:33 +00001515 if (!getTargetParser().ParseDirective(ID))
1516 return false;
1517
Alp Tokercb402912014-01-24 17:20:08 +00001518 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001519 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001520 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1521 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001522 if (Handler.first)
1523 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1524
1525 // Finally, if no one else is interested in this directive, it must be
1526 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001527 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001528 default:
1529 break;
1530 case DK_SET:
1531 case DK_EQU:
1532 return parseDirectiveSet(IDVal, true);
1533 case DK_EQUIV:
1534 return parseDirectiveSet(IDVal, false);
1535 case DK_ASCII:
1536 return parseDirectiveAscii(IDVal, false);
1537 case DK_ASCIZ:
1538 case DK_STRING:
1539 return parseDirectiveAscii(IDVal, true);
1540 case DK_BYTE:
1541 return parseDirectiveValue(1);
1542 case DK_SHORT:
1543 case DK_VALUE:
1544 case DK_2BYTE:
1545 return parseDirectiveValue(2);
1546 case DK_LONG:
1547 case DK_INT:
1548 case DK_4BYTE:
1549 return parseDirectiveValue(4);
1550 case DK_QUAD:
1551 case DK_8BYTE:
1552 return parseDirectiveValue(8);
David Woodhoused6de0d92014-02-01 16:20:59 +00001553 case DK_OCTA:
1554 return parseDirectiveOctaValue();
Jim Grosbach4b905842013-09-20 23:08:21 +00001555 case DK_SINGLE:
1556 case DK_FLOAT:
1557 return parseDirectiveRealValue(APFloat::IEEEsingle);
1558 case DK_DOUBLE:
1559 return parseDirectiveRealValue(APFloat::IEEEdouble);
1560 case DK_ALIGN: {
1561 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1562 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1563 }
1564 case DK_ALIGN32: {
1565 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1566 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1567 }
1568 case DK_BALIGN:
1569 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1570 case DK_BALIGNW:
1571 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1572 case DK_BALIGNL:
1573 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1574 case DK_P2ALIGN:
1575 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1576 case DK_P2ALIGNW:
1577 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1578 case DK_P2ALIGNL:
1579 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1580 case DK_ORG:
1581 return parseDirectiveOrg();
1582 case DK_FILL:
1583 return parseDirectiveFill();
1584 case DK_ZERO:
1585 return parseDirectiveZero();
1586 case DK_EXTERN:
1587 eatToEndOfStatement(); // .extern is the default, ignore it.
1588 return false;
1589 case DK_GLOBL:
1590 case DK_GLOBAL:
1591 return parseDirectiveSymbolAttribute(MCSA_Global);
1592 case DK_LAZY_REFERENCE:
1593 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1594 case DK_NO_DEAD_STRIP:
1595 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1596 case DK_SYMBOL_RESOLVER:
1597 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1598 case DK_PRIVATE_EXTERN:
1599 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1600 case DK_REFERENCE:
1601 return parseDirectiveSymbolAttribute(MCSA_Reference);
1602 case DK_WEAK_DEFINITION:
1603 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1604 case DK_WEAK_REFERENCE:
1605 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1606 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1607 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1608 case DK_COMM:
1609 case DK_COMMON:
1610 return parseDirectiveComm(/*IsLocal=*/false);
1611 case DK_LCOMM:
1612 return parseDirectiveComm(/*IsLocal=*/true);
1613 case DK_ABORT:
1614 return parseDirectiveAbort();
1615 case DK_INCLUDE:
1616 return parseDirectiveInclude();
1617 case DK_INCBIN:
1618 return parseDirectiveIncbin();
1619 case DK_CODE16:
1620 case DK_CODE16GCC:
1621 return TokError(Twine(IDVal) + " not supported yet");
1622 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001623 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001624 case DK_IRP:
1625 return parseDirectiveIrp(IDLoc);
1626 case DK_IRPC:
1627 return parseDirectiveIrpc(IDLoc);
1628 case DK_ENDR:
1629 return parseDirectiveEndr(IDLoc);
1630 case DK_BUNDLE_ALIGN_MODE:
1631 return parseDirectiveBundleAlignMode();
1632 case DK_BUNDLE_LOCK:
1633 return parseDirectiveBundleLock();
1634 case DK_BUNDLE_UNLOCK:
1635 return parseDirectiveBundleUnlock();
1636 case DK_SLEB128:
1637 return parseDirectiveLEB128(true);
1638 case DK_ULEB128:
1639 return parseDirectiveLEB128(false);
1640 case DK_SPACE:
1641 case DK_SKIP:
1642 return parseDirectiveSpace(IDVal);
1643 case DK_FILE:
1644 return parseDirectiveFile(IDLoc);
1645 case DK_LINE:
1646 return parseDirectiveLine();
1647 case DK_LOC:
1648 return parseDirectiveLoc();
1649 case DK_STABS:
1650 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001651 case DK_CV_FILE:
1652 return parseDirectiveCVFile();
1653 case DK_CV_LOC:
1654 return parseDirectiveCVLoc();
1655 case DK_CV_LINETABLE:
1656 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00001657 case DK_CV_INLINE_LINETABLE:
1658 return parseDirectiveCVInlineLinetable();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001659 case DK_CV_STRINGTABLE:
1660 return parseDirectiveCVStringTable();
1661 case DK_CV_FILECHECKSUMS:
1662 return parseDirectiveCVFileChecksums();
Jim Grosbach4b905842013-09-20 23:08:21 +00001663 case DK_CFI_SECTIONS:
1664 return parseDirectiveCFISections();
1665 case DK_CFI_STARTPROC:
1666 return parseDirectiveCFIStartProc();
1667 case DK_CFI_ENDPROC:
1668 return parseDirectiveCFIEndProc();
1669 case DK_CFI_DEF_CFA:
1670 return parseDirectiveCFIDefCfa(IDLoc);
1671 case DK_CFI_DEF_CFA_OFFSET:
1672 return parseDirectiveCFIDefCfaOffset();
1673 case DK_CFI_ADJUST_CFA_OFFSET:
1674 return parseDirectiveCFIAdjustCfaOffset();
1675 case DK_CFI_DEF_CFA_REGISTER:
1676 return parseDirectiveCFIDefCfaRegister(IDLoc);
1677 case DK_CFI_OFFSET:
1678 return parseDirectiveCFIOffset(IDLoc);
1679 case DK_CFI_REL_OFFSET:
1680 return parseDirectiveCFIRelOffset(IDLoc);
1681 case DK_CFI_PERSONALITY:
1682 return parseDirectiveCFIPersonalityOrLsda(true);
1683 case DK_CFI_LSDA:
1684 return parseDirectiveCFIPersonalityOrLsda(false);
1685 case DK_CFI_REMEMBER_STATE:
1686 return parseDirectiveCFIRememberState();
1687 case DK_CFI_RESTORE_STATE:
1688 return parseDirectiveCFIRestoreState();
1689 case DK_CFI_SAME_VALUE:
1690 return parseDirectiveCFISameValue(IDLoc);
1691 case DK_CFI_RESTORE:
1692 return parseDirectiveCFIRestore(IDLoc);
1693 case DK_CFI_ESCAPE:
1694 return parseDirectiveCFIEscape();
1695 case DK_CFI_SIGNAL_FRAME:
1696 return parseDirectiveCFISignalFrame();
1697 case DK_CFI_UNDEFINED:
1698 return parseDirectiveCFIUndefined(IDLoc);
1699 case DK_CFI_REGISTER:
1700 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00001701 case DK_CFI_WINDOW_SAVE:
1702 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00001703 case DK_MACROS_ON:
1704 case DK_MACROS_OFF:
1705 return parseDirectiveMacrosOnOff(IDVal);
1706 case DK_MACRO:
1707 return parseDirectiveMacro(IDLoc);
Nico Weber155dccd12014-07-24 17:08:39 +00001708 case DK_EXITM:
1709 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001710 case DK_ENDM:
1711 case DK_ENDMACRO:
1712 return parseDirectiveEndMacro(IDVal);
1713 case DK_PURGEM:
1714 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00001715 case DK_END:
1716 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00001717 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00001718 return parseDirectiveError(IDLoc, false);
1719 case DK_ERROR:
1720 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00001721 case DK_WARNING:
1722 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00001723 case DK_RELOC:
1724 return parseDirectiveReloc(IDLoc);
Eli Friedman20b02642010-07-19 04:17:25 +00001725 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00001726
Jim Grosbach758e0cc2012-05-01 18:38:27 +00001727 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00001728 }
Chris Lattner36e02122009-06-21 20:54:55 +00001729
Chad Rosierc7f552c2013-02-12 21:33:51 +00001730 // __asm _emit or __asm __emit
1731 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1732 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001733 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00001734
1735 // __asm align
1736 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001737 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00001738
Michael Zuckerman02ecd432015-12-13 17:07:23 +00001739 if (ParsingInlineAsm && (IDVal == "even"))
1740 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001741 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00001742
Chris Lattner7cbfa442010-05-19 23:34:33 +00001743 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00001744 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00001745 ParseInstructionInfo IInfo(Info.AsmRewrites);
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001746 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001747 Info.ParsedOperands);
Chad Rosier149e8e02012-12-12 22:45:52 +00001748 Info.ParseError = HadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00001749
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001750 // Dump the parsed representation, if requested.
1751 if (getShowParsedOperands()) {
1752 SmallString<256> Str;
1753 raw_svector_ostream OS(Str);
1754 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001755 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001756 if (i != 0)
1757 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001758 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001759 }
1760 OS << "]";
1761
Jim Grosbach4b905842013-09-20 23:08:21 +00001762 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001763 }
1764
Oliver Stannard8b273082014-06-19 15:52:37 +00001765 // If we are generating dwarf for the current section then generate a .loc
1766 // directive for the instruction.
Kevin Enderby6469fc22011-11-01 22:27:22 +00001767 if (!HadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00001768 getContext().getGenDwarfSectionSyms().count(
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00001769 getStreamer().getCurrentSection().first)) {
1770 unsigned Line;
1771 if (ActiveMacros.empty())
1772 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1773 else
Frederic Riss16238d92015-06-25 21:57:33 +00001774 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
1775 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001776
Eli Bendersky88024712013-01-16 19:32:36 +00001777 // If we previously parsed a cpp hash file line comment then make sure the
1778 // current Dwarf File is for the CppHashFilename if not then emit the
1779 // Dwarf File table for it and adjust the line number for the .loc.
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00001780 if (CppHashFilename.size()) {
David Blaikiec714ef42014-03-17 01:52:11 +00001781 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1782 0, StringRef(), CppHashFilename);
1783 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001784
Jim Grosbach4b905842013-09-20 23:08:21 +00001785 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1786 // cache with the different Loc from the call above we save the last
1787 // info we queried here with SrcMgr.FindLineNumber().
1788 unsigned CppHashLocLineNo;
1789 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1790 CppHashLocLineNo = LastQueryLine;
1791 else {
1792 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1793 LastQueryLine = CppHashLocLineNo;
1794 LastQueryIDLoc = CppHashLoc;
1795 LastQueryBuffer = CppHashBuf;
1796 }
1797 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00001798 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001799
Jim Grosbach4b905842013-09-20 23:08:21 +00001800 getStreamer().EmitDwarfLocDirective(
1801 getContext().getGenDwarfFileNumber(), Line, 0,
1802 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1803 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00001804 }
1805
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00001806 // If parsing succeeded, match the instruction.
Chad Rosier49963552012-10-13 00:26:04 +00001807 if (!HadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00001808 uint64_t ErrorInfo;
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001809 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1810 Info.ParsedOperands, Out,
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00001811 ErrorInfo, ParsingInlineAsm);
Chad Rosier49963552012-10-13 00:26:04 +00001812 }
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001813
Chris Lattnera2a9d162010-09-11 16:18:25 +00001814 // Don't skip the rest of the line, the instruction parser is responsible for
1815 // that.
1816 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00001817}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00001818
Jim Grosbach4b905842013-09-20 23:08:21 +00001819/// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
Kevin Enderby72553612011-09-13 23:45:18 +00001820/// since they may not be able to be tokenized to get to the end of line token.
Jim Grosbach4b905842013-09-20 23:08:21 +00001821void AsmParser::eatToEndOfLine() {
Rafael Espindolae0d09082011-10-19 18:48:52 +00001822 if (!Lexer.is(AsmToken::EndOfStatement))
1823 Lexer.LexUntilEndOfLine();
Jim Grosbach4b905842013-09-20 23:08:21 +00001824 // Eat EOL.
1825 Lex();
Kevin Enderby72553612011-09-13 23:45:18 +00001826}
1827
Jim Grosbach4b905842013-09-20 23:08:21 +00001828/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00001829/// ::= # number "filename"
1830/// or just as a full line comment if it doesn't have a number and a string.
Craig Topper3c76c522015-09-20 23:35:59 +00001831bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00001832 Lex(); // Eat the hash token.
1833
1834 if (getLexer().isNot(AsmToken::Integer)) {
1835 // Consume the line since in cases it is not a well-formed line directive,
1836 // as if were simply a full line comment.
Jim Grosbach4b905842013-09-20 23:08:21 +00001837 eatToEndOfLine();
Kevin Enderby72553612011-09-13 23:45:18 +00001838 return false;
1839 }
1840
1841 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00001842 Lex();
1843
1844 if (getLexer().isNot(AsmToken::String)) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001845 eatToEndOfLine();
Kevin Enderby72553612011-09-13 23:45:18 +00001846 return false;
1847 }
1848
1849 StringRef Filename = getTok().getString();
1850 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00001851 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00001852
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001853 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1854 CppHashLoc = L;
1855 CppHashFilename = Filename;
1856 CppHashLineNumber = LineNumber;
Kevin Enderby27121c12012-11-05 21:55:41 +00001857 CppHashBuf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00001858
1859 // Ignore any trailing characters, they're just comment.
Jim Grosbach4b905842013-09-20 23:08:21 +00001860 eatToEndOfLine();
Kevin Enderby72553612011-09-13 23:45:18 +00001861 return false;
1862}
1863
Jim Grosbach4b905842013-09-20 23:08:21 +00001864/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001865/// for the Filename and LineNo if any in the diagnostic.
1866void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001867 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001868 raw_ostream &OS = errs();
1869
1870 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00001871 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00001872 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1873 unsigned CppHashBuf =
1874 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001875
Jim Grosbach4b905842013-09-20 23:08:21 +00001876 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001877 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00001878 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1879 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1880 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001881 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1882 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001883 }
1884
Eric Christophera7c32732012-12-18 00:30:54 +00001885 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001886 // manager changed or buffer changed (like in a nested include) then just
1887 // print the normal diagnostic using its Filename and LineNo.
Jim Grosbach4b905842013-09-20 23:08:21 +00001888 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001889 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00001890 if (Parser->SavedDiagHandler)
1891 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1892 else
Craig Topper353eda42014-04-24 06:44:33 +00001893 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001894 return;
1895 }
1896
Eric Christophera7c32732012-12-18 00:30:54 +00001897 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001898 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1899 // the diagnostic.
Jakub Staszakec2ffa92013-09-16 22:03:38 +00001900 const std::string &Filename = Parser->CppHashFilename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001901
1902 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1903 int CppHashLocLineNo =
1904 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00001905 int LineNo =
1906 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001907
Jim Grosbach4b905842013-09-20 23:08:21 +00001908 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1909 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00001910 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001911
Benjamin Kramer47f5e302011-10-16 10:48:29 +00001912 if (Parser->SavedDiagHandler)
1913 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1914 else
Craig Topper353eda42014-04-24 06:44:33 +00001915 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001916}
1917
Rafael Espindola2c064482012-08-21 18:29:30 +00001918// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1919// difference being that that function accepts '@' as part of identifiers and
1920// we can't do that. AsmLexer.cpp should probably be changed to handle
1921// '@' as a special case when needed.
1922static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001923 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1924 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00001925}
1926
Rafael Espindola34b9c512012-06-03 23:57:14 +00001927bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00001928 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00001929 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00001930 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00001931 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00001932 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00001933 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00001934 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001935
Preston Gurd05500642012-09-19 20:36:12 +00001936 // A macro without parameters is handled differently on Darwin:
1937 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001938 while (!Body.empty()) {
1939 // Scan for the next substitution.
1940 std::size_t End = Body.size(), Pos = 0;
1941 for (; Pos != End; ++Pos) {
1942 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00001943 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00001944 // This macro has no parameters, look for $0, $1, etc.
1945 if (Body[Pos] != '$' || Pos + 1 == End)
1946 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001947
Rafael Espindola1134ab232011-06-05 02:43:45 +00001948 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00001949 if (Next == '$' || Next == 'n' ||
1950 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00001951 break;
1952 } else {
1953 // This macro has parameters, look for \foo, \bar, etc.
1954 if (Body[Pos] == '\\' && Pos + 1 != End)
1955 break;
1956 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001957 }
1958
1959 // Add the prefix.
1960 OS << Body.slice(0, Pos);
1961
1962 // Check if we reached the end.
1963 if (Pos == End)
1964 break;
1965
Benjamin Kramer513e7442014-02-20 13:36:32 +00001966 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001967 switch (Body[Pos + 1]) {
1968 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00001969 case '$':
1970 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001971 break;
1972
Jim Grosbach4b905842013-09-20 23:08:21 +00001973 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00001974 case 'n':
1975 OS << A.size();
1976 break;
1977
Jim Grosbach4b905842013-09-20 23:08:21 +00001978 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00001979 default: {
1980 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00001981 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00001982 if (Index >= A.size())
1983 break;
1984
1985 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00001986 for (const AsmToken &Token : A[Index])
1987 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00001988 break;
1989 }
1990 }
1991 Pos += 2;
1992 } else {
1993 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00001994
1995 // Check for the \@ pseudo-variable.
1996 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00001997 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00001998 else
1999 while (isIdentifierChar(Body[I]) && I + 1 != End)
2000 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002001
Jim Grosbach4b905842013-09-20 23:08:21 +00002002 const char *Begin = Body.data() + Pos + 1;
2003 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002004 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002005
Toma Tabacu217116e2015-04-27 10:50:29 +00002006 if (Argument == "@") {
2007 OS << NumOfMacroInstantiations;
2008 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002009 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002010 for (; Index < NParameters; ++Index)
2011 if (Parameters[Index].Name == Argument)
2012 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002013
Toma Tabacu217116e2015-04-27 10:50:29 +00002014 if (Index == NParameters) {
2015 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2016 Pos += 3;
2017 else {
2018 OS << '\\' << Argument;
2019 Pos = I;
2020 }
2021 } else {
2022 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002023 for (const AsmToken &Token : A[Index])
Toma Tabacu217116e2015-04-27 10:50:29 +00002024 // We expect no quotes around the string's contents when
2025 // parsing for varargs.
Craig Topper84008482015-10-10 05:38:14 +00002026 if (Token.getKind() != AsmToken::String || VarargParameter)
2027 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002028 else
Craig Topper84008482015-10-10 05:38:14 +00002029 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002030
2031 Pos += 1 + Argument.size();
2032 }
Preston Gurd05500642012-09-19 20:36:12 +00002033 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002034 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002035 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002036 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002037 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002038
Rafael Espindola1134ab232011-06-05 02:43:45 +00002039 return false;
2040}
Daniel Dunbar43235712010-07-18 18:54:11 +00002041
Nico Weber2a8f9222014-07-24 16:29:04 +00002042MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002043 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002044 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002045 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002046
Jim Grosbach4b905842013-09-20 23:08:21 +00002047static bool isOperator(AsmToken::TokenKind kind) {
2048 switch (kind) {
2049 default:
2050 return false;
2051 case AsmToken::Plus:
2052 case AsmToken::Minus:
2053 case AsmToken::Tilde:
2054 case AsmToken::Slash:
2055 case AsmToken::Star:
2056 case AsmToken::Dot:
2057 case AsmToken::Equal:
2058 case AsmToken::EqualEqual:
2059 case AsmToken::Pipe:
2060 case AsmToken::PipePipe:
2061 case AsmToken::Caret:
2062 case AsmToken::Amp:
2063 case AsmToken::AmpAmp:
2064 case AsmToken::Exclaim:
2065 case AsmToken::ExclaimEqual:
2066 case AsmToken::Percent:
2067 case AsmToken::Less:
2068 case AsmToken::LessEqual:
2069 case AsmToken::LessLess:
2070 case AsmToken::LessGreater:
2071 case AsmToken::Greater:
2072 case AsmToken::GreaterEqual:
2073 case AsmToken::GreaterGreater:
2074 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002075 }
2076}
2077
David Majnemer16252452014-01-29 00:07:39 +00002078namespace {
2079class AsmLexerSkipSpaceRAII {
2080public:
2081 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2082 Lexer.setSkipSpace(SkipSpace);
2083 }
2084
2085 ~AsmLexerSkipSpaceRAII() {
2086 Lexer.setSkipSpace(true);
2087 }
2088
2089private:
2090 AsmLexer &Lexer;
2091};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002092}
David Majnemer16252452014-01-29 00:07:39 +00002093
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002094bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2095
2096 if (Vararg) {
2097 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2098 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002099 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002100 }
2101 return false;
2102 }
2103
Rafael Espindola768b41c2012-06-15 14:02:34 +00002104 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002105 unsigned AddTokens = 0;
2106
David Majnemer16252452014-01-29 00:07:39 +00002107 // Darwin doesn't use spaces to delmit arguments.
2108 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002109
2110 for (;;) {
David Majnemer16252452014-01-29 00:07:39 +00002111 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002112 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002113
David Majnemer91fc4c22014-01-29 18:57:46 +00002114 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
Preston Gurd05500642012-09-19 20:36:12 +00002115 break;
Preston Gurd05500642012-09-19 20:36:12 +00002116
2117 if (Lexer.is(AsmToken::Space)) {
2118 Lex(); // Eat spaces
2119
2120 // Spaces can delimit parameters, but could also be part an expression.
2121 // If the token after a space is an operator, add the token and the next
2122 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002123 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002124 if (isOperator(Lexer.getKind())) {
Preston Gurd05500642012-09-19 20:36:12 +00002125 // Check to see whether the token is used as an operator,
2126 // or part of an identifier
Jordan Rosee8f1eae2013-01-07 19:00:49 +00002127 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd05500642012-09-19 20:36:12 +00002128 if (*NextChar == ' ')
2129 AddTokens = 2;
2130 }
2131
2132 if (!AddTokens && ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002133 break;
2134 }
2135 }
2136 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002137
Jim Grosbach4b905842013-09-20 23:08:21 +00002138 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002139 // to be able to fill in the remaining default parameter values
2140 if (Lexer.is(AsmToken::EndOfStatement))
2141 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002142
2143 // Adjust the current parentheses level.
2144 if (Lexer.is(AsmToken::LParen))
2145 ++ParenLevel;
2146 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2147 --ParenLevel;
2148
2149 // Append the token to the current argument list.
2150 MA.push_back(getTok());
Preston Gurd05500642012-09-19 20:36:12 +00002151 if (AddTokens)
2152 AddTokens--;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002153 Lex();
2154 }
Preston Gurd05500642012-09-19 20:36:12 +00002155
Rafael Espindola768b41c2012-06-15 14:02:34 +00002156 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002157 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002158 return false;
2159}
2160
2161// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002162bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002163 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002164 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002165 bool NamedParametersFound = false;
2166 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002167
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002168 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002169 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002170
Rafael Espindola768b41c2012-06-15 14:02:34 +00002171 // Parse two kinds of macro invocations:
2172 // - macros defined without any parameters accept an arbitrary number of them
2173 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002174 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002175 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2176 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002177 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002178 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002179
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002180 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002181 if (parseIdentifier(FA.Name)) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002182 Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002183 eatToEndOfStatement();
2184 return true;
2185 }
2186
2187 if (!Lexer.is(AsmToken::Equal)) {
2188 TokError("expected '=' after formal parameter identifier");
2189 eatToEndOfStatement();
2190 return true;
2191 }
2192 Lex();
2193
2194 NamedParametersFound = true;
2195 }
2196
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002197 if (NamedParametersFound && FA.Name.empty()) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002198 Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002199 eatToEndOfStatement();
2200 return true;
2201 }
2202
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002203 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2204 if (parseMacroArgument(FA.Value, Vararg))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002205 return true;
2206
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002207 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002208 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002209 unsigned FAI = 0;
2210 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002211 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002212 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002213
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002214 if (FAI >= NParameters) {
Oliver Stannard8b273082014-06-19 15:52:37 +00002215 assert(M && "expected macro to be defined");
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002216 Error(IDLoc,
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002217 "parameter named '" + FA.Name + "' does not exist for macro '" +
Saleem Abdulrasool3f44cd72014-03-17 17:13:57 +00002218 M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002219 return true;
2220 }
2221 PI = FAI;
2222 }
2223
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002224 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002225 if (A.size() <= PI)
2226 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002227 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002228
2229 if (FALocs.size() <= PI)
2230 FALocs.resize(PI + 1);
2231
2232 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002233 }
Jim Grosbach206661622012-07-30 22:44:17 +00002234
Preston Gurd242ed3152012-09-19 20:29:04 +00002235 // At the end of the statement, fill in remaining arguments that have
2236 // default values. If there aren't any, then the next argument is
2237 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002238 if (Lexer.is(AsmToken::EndOfStatement)) {
2239 bool Failure = false;
2240 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2241 if (A[FAI].empty()) {
2242 if (M->Parameters[FAI].Required) {
2243 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2244 "missing value for required parameter "
2245 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2246 Failure = true;
2247 }
2248
2249 if (!M->Parameters[FAI].Value.empty())
2250 A[FAI] = M->Parameters[FAI].Value;
2251 }
2252 }
2253 return Failure;
2254 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002255
2256 if (Lexer.is(AsmToken::Comma))
2257 Lex();
2258 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002259
2260 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002261}
2262
Jim Grosbach4b905842013-09-20 23:08:21 +00002263const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002264 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2265 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002266}
2267
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002268void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2269 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002270}
2271
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002272void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002273
Jim Grosbach4b905842013-09-20 23:08:21 +00002274bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbar43235712010-07-18 18:54:11 +00002275 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2276 // this, although we should protect against infinite loops.
2277 if (ActiveMacros.size() == 20)
2278 return TokError("macros cannot be nested more than 20 levels deep");
2279
Eli Bendersky38274122013-01-14 23:22:36 +00002280 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002281 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002282 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002283
Rafael Espindola1134ab232011-06-05 02:43:45 +00002284 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2285 // to hold the macro body with substitutions.
2286 SmallString<256> Buf;
2287 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002288 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002289
Toma Tabacu217116e2015-04-27 10:50:29 +00002290 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002291 return true;
2292
Eli Bendersky38274122013-01-14 23:22:36 +00002293 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002294 // instantiation.
2295 OS << ".endmacro\n";
2296
Rafael Espindola3560ff22014-08-27 20:03:13 +00002297 std::unique_ptr<MemoryBuffer> Instantiation =
2298 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002299
Daniel Dunbar43235712010-07-18 18:54:11 +00002300 // Create the macro instantiation object and add to the current macro
2301 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002302 MacroInstantiation *MI = new MacroInstantiation(
2303 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002304 ActiveMacros.push_back(MI);
2305
Toma Tabacu217116e2015-04-27 10:50:29 +00002306 ++NumOfMacroInstantiations;
2307
Daniel Dunbar43235712010-07-18 18:54:11 +00002308 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002309 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002310 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002311 Lex();
2312
2313 return false;
2314}
2315
Jim Grosbach4b905842013-09-20 23:08:21 +00002316void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002317 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002318 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002319 Lex();
2320
2321 // Pop the instantiation entry.
2322 delete ActiveMacros.back();
2323 ActiveMacros.pop_back();
2324}
2325
Jim Grosbach4b905842013-09-20 23:08:21 +00002326bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002327 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002328 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002329 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002330 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2331 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002332 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002333
Pete Cooper80d21cb2015-06-22 19:35:57 +00002334 if (!Sym) {
2335 // In the case where we parse an expression starting with a '.', we will
2336 // not generate an error, nor will we create a symbol. In this case we
2337 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002338 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002339 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002340
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002341 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002342 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002343 if (NoDeadStrip)
2344 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2345
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002346 return false;
2347}
2348
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002349/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002350/// ::= identifier
2351/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002352bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002353 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002354 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2355 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002356 // handle this as a context dependent token, instead we detect adjacent tokens
2357 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002358 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2359 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002360
Hans Wennborgce69d772013-10-18 20:46:28 +00002361 // Consume the prefix character, and check for a following identifier.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002362 Lex();
2363 if (Lexer.isNot(AsmToken::Identifier))
2364 return true;
2365
Hans Wennborgce69d772013-10-18 20:46:28 +00002366 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2367 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002368 return true;
2369
2370 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002371 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002372 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002373 Lex();
2374 return false;
2375 }
2376
Jim Grosbach4b905842013-09-20 23:08:21 +00002377 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002378 return true;
2379
Sean Callanan936b0d32010-01-19 21:44:56 +00002380 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002381
Sean Callanan686ed8d2010-01-19 20:22:31 +00002382 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002383
2384 return false;
2385}
2386
Jim Grosbach4b905842013-09-20 23:08:21 +00002387/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002388/// ::= .equ identifier ',' expression
2389/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002390/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002391bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002392 StringRef Name;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002393
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002394 if (parseIdentifier(Name))
Roman Divacky41e6ceb2010-10-28 16:57:58 +00002395 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencer530ce852010-10-09 11:00:50 +00002396
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002397 if (getLexer().isNot(AsmToken::Comma))
Roman Divacky41e6ceb2010-10-28 16:57:58 +00002398 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002399 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002400
Jim Grosbach4b905842013-09-20 23:08:21 +00002401 return parseAssignment(Name, allow_redef, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002402}
2403
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002404bool AsmParser::parseEscapedString(std::string &Data) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002405 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbaref668c12009-08-14 18:19:52 +00002406
2407 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002408 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002409 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2410 if (Str[i] != '\\') {
2411 Data += Str[i];
2412 continue;
2413 }
2414
2415 // Recognize escaped characters. Note that this escape semantics currently
2416 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2417 ++i;
2418 if (i == e)
2419 return TokError("unexpected backslash at end of string");
2420
2421 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002422 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002423 // Consume up to three octal characters.
2424 unsigned Value = Str[i] - '0';
2425
Jim Grosbach4b905842013-09-20 23:08:21 +00002426 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002427 ++i;
2428 Value = Value * 8 + (Str[i] - '0');
2429
Jim Grosbach4b905842013-09-20 23:08:21 +00002430 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002431 ++i;
2432 Value = Value * 8 + (Str[i] - '0');
2433 }
2434 }
2435
2436 if (Value > 255)
2437 return TokError("invalid octal escape sequence (out of range)");
2438
Jim Grosbach4b905842013-09-20 23:08:21 +00002439 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002440 continue;
2441 }
2442
2443 // Otherwise recognize individual escapes.
2444 switch (Str[i]) {
2445 default:
2446 // Just reject invalid escape sequences for now.
2447 return TokError("invalid escape sequence (unrecognized character)");
2448
2449 case 'b': Data += '\b'; break;
2450 case 'f': Data += '\f'; break;
2451 case 'n': Data += '\n'; break;
2452 case 'r': Data += '\r'; break;
2453 case 't': Data += '\t'; break;
2454 case '"': Data += '"'; break;
2455 case '\\': Data += '\\'; break;
2456 }
2457 }
2458
2459 return false;
2460}
2461
Jim Grosbach4b905842013-09-20 23:08:21 +00002462/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002463/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002464bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002465 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002466 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002467
Daniel Dunbara10e5192009-06-24 23:30:00 +00002468 for (;;) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002469 if (getLexer().isNot(AsmToken::String))
Rafael Espindola63760ba2010-10-28 20:02:27 +00002470 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002471
Daniel Dunbaref668c12009-08-14 18:19:52 +00002472 std::string Data;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002473 if (parseEscapedString(Data))
Daniel Dunbaref668c12009-08-14 18:19:52 +00002474 return true;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002475
Rafael Espindola64e1af82013-07-02 15:49:13 +00002476 getStreamer().EmitBytes(Data);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002477 if (ZeroTerminated)
Rafael Espindola64e1af82013-07-02 15:49:13 +00002478 getStreamer().EmitBytes(StringRef("\0", 1));
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002479
Sean Callanan686ed8d2010-01-19 20:22:31 +00002480 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002481
2482 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002483 break;
2484
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002485 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola63760ba2010-10-28 20:02:27 +00002486 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002487 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002488 }
2489 }
2490
Sean Callanan686ed8d2010-01-19 20:22:31 +00002491 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002492 return false;
2493}
2494
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002495/// parseDirectiveReloc
2496/// ::= .reloc expression , identifier [ , expression ]
2497bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2498 const MCExpr *Offset;
2499 const MCExpr *Expr = nullptr;
2500
2501 SMLoc OffsetLoc = Lexer.getTok().getLoc();
2502 if (parseExpression(Offset))
2503 return true;
2504
2505 // We can only deal with constant expressions at the moment.
2506 int64_t OffsetValue;
2507 if (!Offset->evaluateAsAbsolute(OffsetValue))
2508 return Error(OffsetLoc, "expression is not a constant value");
2509
David Majnemerce108422016-01-19 23:05:27 +00002510 if (OffsetValue < 0)
2511 return Error(OffsetLoc, "expression is negative");
2512
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002513 if (Lexer.isNot(AsmToken::Comma))
2514 return TokError("expected comma");
2515 Lexer.Lex();
2516
2517 if (Lexer.isNot(AsmToken::Identifier))
2518 return TokError("expected relocation name");
2519 SMLoc NameLoc = Lexer.getTok().getLoc();
2520 StringRef Name = Lexer.getTok().getIdentifier();
2521 Lexer.Lex();
2522
2523 if (Lexer.is(AsmToken::Comma)) {
2524 Lexer.Lex();
2525 SMLoc ExprLoc = Lexer.getLoc();
2526 if (parseExpression(Expr))
2527 return true;
2528
2529 MCValue Value;
2530 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2531 return Error(ExprLoc, "expression must be relocatable");
2532 }
2533
2534 if (Lexer.isNot(AsmToken::EndOfStatement))
2535 return TokError("unexpected token in .reloc directive");
2536
2537 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2538 return Error(NameLoc, "unknown relocation name");
2539
2540 return false;
2541}
2542
Jim Grosbach4b905842013-09-20 23:08:21 +00002543/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002544/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002545bool AsmParser::parseDirectiveValue(unsigned Size) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002546 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002547 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002548
Daniel Dunbara10e5192009-06-24 23:30:00 +00002549 for (;;) {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002550 const MCExpr *Value;
Jim Grosbach76346c32011-06-29 16:05:14 +00002551 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002552 if (parseExpression(Value))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002553 return true;
2554
Daniel Dunbar6738a2e2010-05-23 18:36:38 +00002555 // Special case constant expressions to match code generator.
Jim Grosbach76346c32011-06-29 16:05:14 +00002556 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2557 assert(Size <= 8 && "Invalid size");
2558 uint64_t IntValue = MCE->getValue();
2559 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2560 return Error(ExprLoc, "literal value out of range for directive");
Rafael Espindola64e1af82013-07-02 15:49:13 +00002561 getStreamer().EmitIntValue(IntValue, Size);
Jim Grosbach76346c32011-06-29 16:05:14 +00002562 } else
Kevin Enderby96918bc2014-04-22 17:27:29 +00002563 getStreamer().EmitValue(Value, Size, ExprLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002564
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002565 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002566 break;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002567
Daniel Dunbara10e5192009-06-24 23:30:00 +00002568 // FIXME: Improve diagnostic.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002569 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002570 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002571 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002572 }
2573 }
2574
Sean Callanan686ed8d2010-01-19 20:22:31 +00002575 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002576 return false;
2577}
2578
David Woodhoused6de0d92014-02-01 16:20:59 +00002579/// ParseDirectiveOctaValue
2580/// ::= .octa [ hexconstant (, hexconstant)* ]
2581bool AsmParser::parseDirectiveOctaValue() {
2582 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2583 checkForValidSection();
2584
2585 for (;;) {
2586 if (Lexer.getKind() == AsmToken::Error)
2587 return true;
2588 if (Lexer.getKind() != AsmToken::Integer &&
2589 Lexer.getKind() != AsmToken::BigNum)
2590 return TokError("unknown token in expression");
2591
2592 SMLoc ExprLoc = getLexer().getLoc();
2593 APInt IntValue = getTok().getAPIntVal();
2594 Lex();
2595
2596 uint64_t hi, lo;
2597 if (IntValue.isIntN(64)) {
2598 hi = 0;
2599 lo = IntValue.getZExtValue();
2600 } else if (IntValue.isIntN(128)) {
David Woodhouse6c9a6f92014-02-01 16:52:33 +00002601 // It might actually have more than 128 bits, but the top ones are zero.
2602 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002603 lo = IntValue.getLoBits(64).getZExtValue();
2604 } else
2605 return Error(ExprLoc, "literal value out of range for directive");
2606
2607 if (MAI.isLittleEndian()) {
2608 getStreamer().EmitIntValue(lo, 8);
2609 getStreamer().EmitIntValue(hi, 8);
2610 } else {
2611 getStreamer().EmitIntValue(hi, 8);
2612 getStreamer().EmitIntValue(lo, 8);
2613 }
2614
2615 if (getLexer().is(AsmToken::EndOfStatement))
2616 break;
2617
2618 // FIXME: Improve diagnostic.
2619 if (getLexer().isNot(AsmToken::Comma))
2620 return TokError("unexpected token in directive");
2621 Lex();
2622 }
2623 }
2624
2625 Lex();
2626 return false;
2627}
2628
Jim Grosbach4b905842013-09-20 23:08:21 +00002629/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00002630/// ::= (.single | .double) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002631bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
Daniel Dunbar2af16532010-09-24 01:59:56 +00002632 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002633 checkForValidSection();
Daniel Dunbar2af16532010-09-24 01:59:56 +00002634
2635 for (;;) {
2636 // We don't truly support arithmetic on floating point expressions, so we
2637 // have to manually parse unary prefixes.
2638 bool IsNeg = false;
2639 if (getLexer().is(AsmToken::Minus)) {
2640 Lex();
2641 IsNeg = true;
2642 } else if (getLexer().is(AsmToken::Plus))
2643 Lex();
2644
Michael J. Spencer530ce852010-10-09 11:00:50 +00002645 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby5bbe9572011-03-29 21:11:52 +00002646 getLexer().isNot(AsmToken::Real) &&
2647 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbar2af16532010-09-24 01:59:56 +00002648 return TokError("unexpected token in directive");
2649
2650 // Convert to an APFloat.
2651 APFloat Value(Semantics);
Kevin Enderby5bbe9572011-03-29 21:11:52 +00002652 StringRef IDVal = getTok().getString();
2653 if (getLexer().is(AsmToken::Identifier)) {
2654 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2655 Value = APFloat::getInf(Semantics);
2656 else if (!IDVal.compare_lower("nan"))
2657 Value = APFloat::getNaN(Semantics, false, ~0);
2658 else
2659 return TokError("invalid floating point literal");
2660 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Jim Grosbach4b905842013-09-20 23:08:21 +00002661 APFloat::opInvalidOp)
Daniel Dunbar2af16532010-09-24 01:59:56 +00002662 return TokError("invalid floating point literal");
2663 if (IsNeg)
2664 Value.changeSign();
2665
2666 // Consume the numeric token.
2667 Lex();
2668
2669 // Emit the value as an integer.
2670 APInt AsInt = Value.bitcastToAPInt();
2671 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
Rafael Espindola64e1af82013-07-02 15:49:13 +00002672 AsInt.getBitWidth() / 8);
Daniel Dunbar2af16532010-09-24 01:59:56 +00002673
2674 if (getLexer().is(AsmToken::EndOfStatement))
2675 break;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002676
Daniel Dunbar2af16532010-09-24 01:59:56 +00002677 if (getLexer().isNot(AsmToken::Comma))
2678 return TokError("unexpected token in directive");
2679 Lex();
2680 }
2681 }
2682
2683 Lex();
2684 return false;
2685}
2686
Jim Grosbach4b905842013-09-20 23:08:21 +00002687/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00002688/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002689bool AsmParser::parseDirectiveZero() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002690 checkForValidSection();
Rafael Espindola922e3f42010-09-16 15:03:59 +00002691
2692 int64_t NumBytes;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002693 if (parseAbsoluteExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00002694 return true;
2695
Rafael Espindolab91bac62010-10-05 19:42:57 +00002696 int64_t Val = 0;
2697 if (getLexer().is(AsmToken::Comma)) {
2698 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002699 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00002700 return true;
2701 }
2702
Rafael Espindola922e3f42010-09-16 15:03:59 +00002703 if (getLexer().isNot(AsmToken::EndOfStatement))
2704 return TokError("unexpected token in '.zero' directive");
2705
2706 Lex();
2707
Rafael Espindola64e1af82013-07-02 15:49:13 +00002708 getStreamer().EmitFill(NumBytes, Val);
Rafael Espindola922e3f42010-09-16 15:03:59 +00002709
2710 return false;
2711}
2712
Jim Grosbach4b905842013-09-20 23:08:21 +00002713/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00002714/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002715bool AsmParser::parseDirectiveFill() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002716 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002717
David Majnemer522d3db2014-02-01 07:19:38 +00002718 SMLoc RepeatLoc = getLexer().getLoc();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002719 int64_t NumValues;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002720 if (parseAbsoluteExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002721 return true;
2722
David Majnemer522d3db2014-02-01 07:19:38 +00002723 if (NumValues < 0) {
2724 Warning(RepeatLoc,
2725 "'.fill' directive with negative repeat count has no effect");
2726 NumValues = 0;
2727 }
2728
Roman Divackye33098f2013-09-24 17:44:41 +00002729 int64_t FillSize = 1;
2730 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002731
David Majnemer522d3db2014-02-01 07:19:38 +00002732 SMLoc SizeLoc, ExprLoc;
Roman Divackye33098f2013-09-24 17:44:41 +00002733 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2734 if (getLexer().isNot(AsmToken::Comma))
2735 return TokError("unexpected token in '.fill' directive");
2736 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002737
David Majnemer522d3db2014-02-01 07:19:38 +00002738 SizeLoc = getLexer().getLoc();
Roman Divackye33098f2013-09-24 17:44:41 +00002739 if (parseAbsoluteExpression(FillSize))
2740 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002741
Roman Divackye33098f2013-09-24 17:44:41 +00002742 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2743 if (getLexer().isNot(AsmToken::Comma))
2744 return TokError("unexpected token in '.fill' directive");
2745 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002746
David Majnemer522d3db2014-02-01 07:19:38 +00002747 ExprLoc = getLexer().getLoc();
Roman Divackye33098f2013-09-24 17:44:41 +00002748 if (parseAbsoluteExpression(FillExpr))
2749 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002750
Roman Divackye33098f2013-09-24 17:44:41 +00002751 if (getLexer().isNot(AsmToken::EndOfStatement))
2752 return TokError("unexpected token in '.fill' directive");
2753
2754 Lex();
2755 }
2756 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002757
David Majnemer522d3db2014-02-01 07:19:38 +00002758 if (FillSize < 0) {
2759 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2760 NumValues = 0;
2761 }
2762 if (FillSize > 8) {
2763 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2764 FillSize = 8;
2765 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002766
David Majnemer522d3db2014-02-01 07:19:38 +00002767 if (!isUInt<32>(FillExpr) && FillSize > 4)
2768 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2769
Alexey Samsonov1b0713c2014-09-02 17:25:29 +00002770 if (NumValues > 0) {
2771 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2772 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2773 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2774 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2775 if (NonZeroFillSize < FillSize)
2776 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2777 }
David Majnemer522d3db2014-02-01 07:19:38 +00002778 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002779
2780 return false;
2781}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002782
Jim Grosbach4b905842013-09-20 23:08:21 +00002783/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002784/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002785bool AsmParser::parseDirectiveOrg() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002786 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002787
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002788 const MCExpr *Offset;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002789 if (parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002790 return true;
2791
2792 // Parse optional fill expression.
2793 int64_t FillExpr = 0;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002794 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2795 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002796 return TokError("unexpected token in '.org' directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002797 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00002798
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002799 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002800 return true;
2801
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002802 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002803 return TokError("unexpected token in '.org' directive");
2804 }
2805
Sean Callanan686ed8d2010-01-19 20:22:31 +00002806 Lex();
Rafael Espindola7ae65d82015-11-04 23:59:18 +00002807 getStreamer().emitValueToOffset(Offset, FillExpr);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002808 return false;
2809}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002810
Jim Grosbach4b905842013-09-20 23:08:21 +00002811/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002812/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00002813bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002814 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002815
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002816 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002817 int64_t Alignment;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002818 if (parseAbsoluteExpression(Alignment))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002819 return true;
2820
2821 SMLoc MaxBytesLoc;
2822 bool HasFillExpr = false;
2823 int64_t FillExpr = 0;
2824 int64_t MaxBytesToFill = 0;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002825 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2826 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002827 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002828 Lex();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002829
2830 // The fill expression can be omitted while specifying a maximum number of
2831 // alignment bytes, e.g:
2832 // .align 3,,4
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002833 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002834 HasFillExpr = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002835 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002836 return true;
2837 }
2838
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002839 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2840 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002841 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002842 Lex();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002843
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002844 MaxBytesLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002845 if (parseAbsoluteExpression(MaxBytesToFill))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002846 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002847
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002848 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002849 return TokError("unexpected token in directive");
2850 }
2851 }
2852
Sean Callanan686ed8d2010-01-19 20:22:31 +00002853 Lex();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002854
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002855 if (!HasFillExpr)
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002856 FillExpr = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002857
2858 // Compute alignment in bytes.
2859 if (IsPow2) {
2860 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002861 if (Alignment >= 32) {
2862 Error(AlignmentLoc, "invalid alignment value");
2863 Alignment = 31;
2864 }
2865
Benjamin Kramer63951ad2009-09-06 09:35:10 +00002866 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00002867 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00002868 // Reject alignments that aren't either a power of two or zero,
2869 // for gas compatibility. Alignment of zero is silently rounded
2870 // up to one.
2871 if (Alignment == 0)
2872 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00002873 if (!isPowerOf2_64(Alignment))
2874 Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002875 }
2876
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002877 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002878 if (MaxBytesLoc.isValid()) {
2879 if (MaxBytesToFill < 1) {
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002880 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00002881 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00002882 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002883 }
2884
2885 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00002886 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00002887 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002888 MaxBytesToFill = 0;
2889 }
2890 }
2891
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002892 // Check whether we should use optimal code alignment for this .align
2893 // directive.
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00002894 const MCSection *Section = getStreamer().getCurrentSection().first;
2895 assert(Section && "must have section to emit alignment");
2896 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002897 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2898 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002899 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002900 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00002901 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00002902 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2903 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002904 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002905
2906 return false;
2907}
2908
Jim Grosbach4b905842013-09-20 23:08:21 +00002909/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00002910/// ::= .file [number] filename
2911/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00002912bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00002913 // FIXME: I'm not sure what this is.
2914 int64_t FileNumber = -1;
2915 SMLoc FileNumberLoc = getLexer().getLoc();
2916 if (getLexer().is(AsmToken::Integer)) {
2917 FileNumber = getTok().getIntVal();
2918 Lex();
2919
2920 if (FileNumber < 1)
2921 return TokError("file number less than one");
2922 }
2923
2924 if (getLexer().isNot(AsmToken::String))
2925 return TokError("unexpected token in '.file' directive");
2926
2927 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002928 // Allow the strings to have escaped octal character sequence.
2929 std::string Path = getTok().getString();
2930 if (parseEscapedString(Path))
2931 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00002932 Lex();
2933
2934 StringRef Directory;
2935 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002936 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00002937 if (getLexer().is(AsmToken::String)) {
2938 if (FileNumber == -1)
2939 return TokError("explicit path specified, but no file number");
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002940 if (parseEscapedString(FilenameData))
2941 return true;
2942 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00002943 Directory = Path;
2944 Lex();
2945 } else {
2946 Filename = Path;
2947 }
2948
2949 if (getLexer().isNot(AsmToken::EndOfStatement))
2950 return TokError("unexpected token in '.file' directive");
2951
2952 if (FileNumber == -1)
2953 getStreamer().EmitFileDirective(Filename);
2954 else {
David Blaikiedc3f01e2015-03-09 01:57:13 +00002955 if (getContext().getGenDwarfForAssembly())
Jim Grosbach4b905842013-09-20 23:08:21 +00002956 Error(DirectiveLoc,
2957 "input can't have .file dwarf directives when -g is "
2958 "used to generate dwarf debug info for assembly code");
Eli Bendersky17233942013-01-15 22:59:42 +00002959
David Blaikiec714ef42014-03-17 01:52:11 +00002960 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2961 0)
Eli Bendersky17233942013-01-15 22:59:42 +00002962 Error(FileNumberLoc, "file number already allocated");
2963 }
2964
2965 return false;
2966}
2967
Jim Grosbach4b905842013-09-20 23:08:21 +00002968/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00002969/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00002970bool AsmParser::parseDirectiveLine() {
Eli Bendersky17233942013-01-15 22:59:42 +00002971 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2972 if (getLexer().isNot(AsmToken::Integer))
2973 return TokError("unexpected token in '.line' directive");
2974
2975 int64_t LineNumber = getTok().getIntVal();
Jim Grosbach4b905842013-09-20 23:08:21 +00002976 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00002977 Lex();
2978
2979 // FIXME: Do something with the .line.
2980 }
2981
2982 if (getLexer().isNot(AsmToken::EndOfStatement))
2983 return TokError("unexpected token in '.line' directive");
2984
2985 return false;
2986}
2987
Jim Grosbach4b905842013-09-20 23:08:21 +00002988/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00002989/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2990/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2991/// The first number is a file number, must have been previously assigned with
2992/// a .file directive, the second number is the line number and optionally the
2993/// third number is a column position (zero if not specified). The remaining
2994/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00002995bool AsmParser::parseDirectiveLoc() {
Eli Bendersky17233942013-01-15 22:59:42 +00002996 if (getLexer().isNot(AsmToken::Integer))
2997 return TokError("unexpected token in '.loc' directive");
2998 int64_t FileNumber = getTok().getIntVal();
2999 if (FileNumber < 1)
3000 return TokError("file number less than one in '.loc' directive");
3001 if (!getContext().isValidDwarfFileNumber(FileNumber))
3002 return TokError("unassigned file number in '.loc' directive");
3003 Lex();
3004
3005 int64_t LineNumber = 0;
3006 if (getLexer().is(AsmToken::Integer)) {
3007 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003008 if (LineNumber < 0)
3009 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003010 Lex();
3011 }
3012
3013 int64_t ColumnPos = 0;
3014 if (getLexer().is(AsmToken::Integer)) {
3015 ColumnPos = getTok().getIntVal();
3016 if (ColumnPos < 0)
3017 return TokError("column position less than zero in '.loc' directive");
3018 Lex();
3019 }
3020
3021 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3022 unsigned Isa = 0;
3023 int64_t Discriminator = 0;
3024 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3025 for (;;) {
3026 if (getLexer().is(AsmToken::EndOfStatement))
3027 break;
3028
3029 StringRef Name;
3030 SMLoc Loc = getTok().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003031 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003032 return TokError("unexpected token in '.loc' directive");
3033
3034 if (Name == "basic_block")
3035 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3036 else if (Name == "prologue_end")
3037 Flags |= DWARF2_FLAG_PROLOGUE_END;
3038 else if (Name == "epilogue_begin")
3039 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3040 else if (Name == "is_stmt") {
3041 Loc = getTok().getLoc();
3042 const MCExpr *Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003043 if (parseExpression(Value))
Eli Bendersky17233942013-01-15 22:59:42 +00003044 return true;
3045 // The expression must be the constant 0 or 1.
3046 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3047 int Value = MCE->getValue();
3048 if (Value == 0)
3049 Flags &= ~DWARF2_FLAG_IS_STMT;
3050 else if (Value == 1)
3051 Flags |= DWARF2_FLAG_IS_STMT;
3052 else
3053 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003054 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003055 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3056 }
Craig Topperf15655b2013-04-22 04:22:40 +00003057 } else if (Name == "isa") {
Eli Bendersky17233942013-01-15 22:59:42 +00003058 Loc = getTok().getLoc();
3059 const MCExpr *Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003060 if (parseExpression(Value))
Eli Bendersky17233942013-01-15 22:59:42 +00003061 return true;
3062 // The expression must be a constant greater or equal to 0.
3063 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3064 int Value = MCE->getValue();
3065 if (Value < 0)
3066 return Error(Loc, "isa number less than zero");
3067 Isa = Value;
Craig Topperf15655b2013-04-22 04:22:40 +00003068 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003069 return Error(Loc, "isa number not a constant value");
3070 }
Craig Topperf15655b2013-04-22 04:22:40 +00003071 } else if (Name == "discriminator") {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003072 if (parseAbsoluteExpression(Discriminator))
Eli Bendersky17233942013-01-15 22:59:42 +00003073 return true;
Craig Topperf15655b2013-04-22 04:22:40 +00003074 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003075 return Error(Loc, "unknown sub-directive in '.loc' directive");
3076 }
3077
3078 if (getLexer().is(AsmToken::EndOfStatement))
3079 break;
3080 }
3081 }
3082
3083 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3084 Isa, Discriminator, StringRef());
3085
3086 return false;
3087}
3088
Jim Grosbach4b905842013-09-20 23:08:21 +00003089/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003090/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003091bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003092 return TokError("unsupported directive '.stabs'");
3093}
3094
Reid Kleckner2214ed82016-01-29 00:49:42 +00003095/// parseDirectiveCVFile
3096/// ::= .cv_file number filename
3097bool AsmParser::parseDirectiveCVFile() {
3098 SMLoc FileNumberLoc = getLexer().getLoc();
3099 if (getLexer().isNot(AsmToken::Integer))
3100 return TokError("expected file number in '.cv_file' directive");
3101
3102 int64_t FileNumber = getTok().getIntVal();
3103 Lex();
3104
3105 if (FileNumber < 1)
3106 return TokError("file number less than one");
3107
3108 if (getLexer().isNot(AsmToken::String))
3109 return TokError("unexpected token in '.cv_file' directive");
3110
3111 // Usually the directory and filename together, otherwise just the directory.
3112 // Allow the strings to have escaped octal character sequence.
3113 std::string Filename;
3114 if (parseEscapedString(Filename))
3115 return true;
3116 Lex();
3117
3118 if (getLexer().isNot(AsmToken::EndOfStatement))
3119 return TokError("unexpected token in '.cv_file' directive");
3120
3121 if (getStreamer().EmitCVFileDirective(FileNumber, Filename) == 0)
3122 Error(FileNumberLoc, "file number already allocated");
3123
3124 return false;
3125}
3126
3127/// parseDirectiveCVLoc
3128/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3129/// [is_stmt VALUE]
3130/// The first number is a file number, must have been previously assigned with
3131/// a .file directive, the second number is the line number and optionally the
3132/// third number is a column position (zero if not specified). The remaining
3133/// optional items are .loc sub-directives.
3134bool AsmParser::parseDirectiveCVLoc() {
3135 if (getLexer().isNot(AsmToken::Integer))
3136 return TokError("unexpected token in '.cv_loc' directive");
3137
3138 int64_t FunctionId = getTok().getIntVal();
3139 if (FunctionId < 0)
3140 return TokError("function id less than zero in '.cv_loc' directive");
3141 Lex();
3142
3143 int64_t FileNumber = getTok().getIntVal();
3144 if (FileNumber < 1)
3145 return TokError("file number less than one in '.cv_loc' directive");
3146 if (!getContext().isValidCVFileNumber(FileNumber))
3147 return TokError("unassigned file number in '.cv_loc' directive");
3148 Lex();
3149
3150 int64_t LineNumber = 0;
3151 if (getLexer().is(AsmToken::Integer)) {
3152 LineNumber = getTok().getIntVal();
3153 if (LineNumber < 0)
3154 return TokError("line number less than zero in '.cv_loc' directive");
3155 Lex();
3156 }
3157
3158 int64_t ColumnPos = 0;
3159 if (getLexer().is(AsmToken::Integer)) {
3160 ColumnPos = getTok().getIntVal();
3161 if (ColumnPos < 0)
3162 return TokError("column position less than zero in '.cv_loc' directive");
3163 Lex();
3164 }
3165
3166 bool PrologueEnd = false;
3167 uint64_t IsStmt = 0;
3168 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3169 StringRef Name;
3170 SMLoc Loc = getTok().getLoc();
3171 if (parseIdentifier(Name))
3172 return TokError("unexpected token in '.cv_loc' directive");
3173
3174 if (Name == "prologue_end")
3175 PrologueEnd = true;
3176 else if (Name == "is_stmt") {
3177 Loc = getTok().getLoc();
3178 const MCExpr *Value;
3179 if (parseExpression(Value))
3180 return true;
3181 // The expression must be the constant 0 or 1.
3182 IsStmt = ~0ULL;
3183 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3184 IsStmt = MCE->getValue();
3185
3186 if (IsStmt > 1)
3187 return Error(Loc, "is_stmt value not 0 or 1");
3188 } else {
3189 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3190 }
3191 }
3192
3193 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
3194 ColumnPos, PrologueEnd, IsStmt, StringRef());
3195 return false;
3196}
3197
3198/// parseDirectiveCVLinetable
3199/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3200bool AsmParser::parseDirectiveCVLinetable() {
3201 int64_t FunctionId = getTok().getIntVal();
3202 if (FunctionId < 0)
3203 return TokError("function id less than zero in '.cv_linetable' directive");
3204 Lex();
3205
3206 if (Lexer.isNot(AsmToken::Comma))
3207 return TokError("unexpected token in '.cv_linetable' directive");
3208 Lex();
3209
3210 SMLoc Loc = getLexer().getLoc();
3211 StringRef FnStartName;
3212 if (parseIdentifier(FnStartName))
3213 return Error(Loc, "expected identifier in directive");
3214
3215 if (Lexer.isNot(AsmToken::Comma))
3216 return TokError("unexpected token in '.cv_linetable' directive");
3217 Lex();
3218
3219 Loc = getLexer().getLoc();
3220 StringRef FnEndName;
3221 if (parseIdentifier(FnEndName))
3222 return Error(Loc, "expected identifier in directive");
3223
3224 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3225 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3226
3227 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3228 return false;
3229}
3230
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003231/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003232/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003233/// ("contains" SecondaryFunctionId+)?
3234bool AsmParser::parseDirectiveCVInlineLinetable() {
3235 int64_t PrimaryFunctionId = getTok().getIntVal();
3236 if (PrimaryFunctionId < 0)
3237 return TokError(
3238 "function id less than zero in '.cv_inline_linetable' directive");
3239 Lex();
3240
3241 int64_t SourceFileId = getTok().getIntVal();
3242 if (SourceFileId <= 0)
3243 return TokError(
3244 "File id less than zero in '.cv_inline_linetable' directive");
3245 Lex();
3246
3247 int64_t SourceLineNum = getTok().getIntVal();
3248 if (SourceLineNum < 0)
3249 return TokError(
3250 "Line number less than zero in '.cv_inline_linetable' directive");
3251 Lex();
3252
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003253 SMLoc Loc = getLexer().getLoc();
3254 StringRef FnStartName;
3255 if (parseIdentifier(FnStartName))
3256 return Error(Loc, "expected identifier in directive");
3257 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3258
David Majnemerc9911f22016-02-02 19:22:34 +00003259 Loc = getLexer().getLoc();
3260 StringRef FnEndName;
3261 if (parseIdentifier(FnEndName))
3262 return Error(Loc, "expected identifier in directive");
3263 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3264
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003265 SmallVector<unsigned, 8> SecondaryFunctionIds;
3266 if (getLexer().is(AsmToken::Identifier)) {
3267 if (getTok().getIdentifier() != "contains")
3268 return TokError(
3269 "unexpected identifier in '.cv_inline_linetable' directive");
3270 Lex();
3271
3272 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3273 int64_t SecondaryFunctionId = getTok().getIntVal();
3274 if (SecondaryFunctionId < 0)
3275 return TokError(
3276 "function id less than zero in '.cv_inline_linetable' directive");
3277 Lex();
3278
3279 SecondaryFunctionIds.push_back(SecondaryFunctionId);
3280 }
3281 }
3282
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003283 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3284 SourceLineNum, FnStartSym,
David Majnemerc9911f22016-02-02 19:22:34 +00003285 FnEndSym, SecondaryFunctionIds);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003286 return false;
3287}
3288
Reid Kleckner2214ed82016-01-29 00:49:42 +00003289/// parseDirectiveCVStringTable
3290/// ::= .cv_stringtable
3291bool AsmParser::parseDirectiveCVStringTable() {
3292 getStreamer().EmitCVStringTableDirective();
3293 return false;
3294}
3295
3296/// parseDirectiveCVFileChecksums
3297/// ::= .cv_filechecksums
3298bool AsmParser::parseDirectiveCVFileChecksums() {
3299 getStreamer().EmitCVFileChecksumsDirective();
3300 return false;
3301}
3302
Jim Grosbach4b905842013-09-20 23:08:21 +00003303/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003304/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003305bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003306 StringRef Name;
3307 bool EH = false;
3308 bool Debug = false;
3309
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003310 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003311 return TokError("Expected an identifier");
3312
3313 if (Name == ".eh_frame")
3314 EH = true;
3315 else if (Name == ".debug_frame")
3316 Debug = true;
3317
3318 if (getLexer().is(AsmToken::Comma)) {
3319 Lex();
3320
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003321 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003322 return TokError("Expected an identifier");
3323
3324 if (Name == ".eh_frame")
3325 EH = true;
3326 else if (Name == ".debug_frame")
3327 Debug = true;
3328 }
3329
3330 getStreamer().EmitCFISections(EH, Debug);
3331 return false;
3332}
3333
Jim Grosbach4b905842013-09-20 23:08:21 +00003334/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003335/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003336bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003337 StringRef Simple;
3338 if (getLexer().isNot(AsmToken::EndOfStatement))
3339 if (parseIdentifier(Simple) || Simple != "simple")
3340 return TokError("unexpected token in .cfi_startproc directive");
3341
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003342 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003343 return false;
3344}
3345
Jim Grosbach4b905842013-09-20 23:08:21 +00003346/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003347/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003348bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003349 getStreamer().EmitCFIEndProc();
3350 return false;
3351}
3352
Jim Grosbach4b905842013-09-20 23:08:21 +00003353/// \brief parse register name or number.
3354bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003355 SMLoc DirectiveLoc) {
3356 unsigned RegNo;
3357
3358 if (getLexer().isNot(AsmToken::Integer)) {
3359 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3360 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003361 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003362 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003363 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003364
3365 return false;
3366}
3367
Jim Grosbach4b905842013-09-20 23:08:21 +00003368/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003369/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003370bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003371 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003372 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003373 return true;
3374
3375 if (getLexer().isNot(AsmToken::Comma))
3376 return TokError("unexpected token in directive");
3377 Lex();
3378
3379 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003380 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003381 return true;
3382
3383 getStreamer().EmitCFIDefCfa(Register, Offset);
3384 return false;
3385}
3386
Jim Grosbach4b905842013-09-20 23:08:21 +00003387/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003388/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003389bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003390 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003391 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003392 return true;
3393
3394 getStreamer().EmitCFIDefCfaOffset(Offset);
3395 return false;
3396}
3397
Jim Grosbach4b905842013-09-20 23:08:21 +00003398/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003399/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003400bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003401 int64_t Register1 = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003402 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003403 return true;
3404
3405 if (getLexer().isNot(AsmToken::Comma))
3406 return TokError("unexpected token in directive");
3407 Lex();
3408
3409 int64_t Register2 = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003410 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003411 return true;
3412
3413 getStreamer().EmitCFIRegister(Register1, Register2);
3414 return false;
3415}
3416
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003417/// parseDirectiveCFIWindowSave
3418/// ::= .cfi_window_save
3419bool AsmParser::parseDirectiveCFIWindowSave() {
3420 getStreamer().EmitCFIWindowSave();
3421 return false;
3422}
3423
Jim Grosbach4b905842013-09-20 23:08:21 +00003424/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003425/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003426bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003427 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003428 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003429 return true;
3430
3431 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3432 return false;
3433}
3434
Jim Grosbach4b905842013-09-20 23:08:21 +00003435/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003436/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003437bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003438 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003439 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003440 return true;
3441
3442 getStreamer().EmitCFIDefCfaRegister(Register);
3443 return false;
3444}
3445
Jim Grosbach4b905842013-09-20 23:08:21 +00003446/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003447/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003448bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003449 int64_t Register = 0;
3450 int64_t Offset = 0;
3451
Jim Grosbach4b905842013-09-20 23:08:21 +00003452 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003453 return true;
3454
3455 if (getLexer().isNot(AsmToken::Comma))
3456 return TokError("unexpected token in directive");
3457 Lex();
3458
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003459 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003460 return true;
3461
3462 getStreamer().EmitCFIOffset(Register, Offset);
3463 return false;
3464}
3465
Jim Grosbach4b905842013-09-20 23:08:21 +00003466/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003467/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003468bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003469 int64_t Register = 0;
3470
Jim Grosbach4b905842013-09-20 23:08:21 +00003471 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003472 return true;
3473
3474 if (getLexer().isNot(AsmToken::Comma))
3475 return TokError("unexpected token in directive");
3476 Lex();
3477
3478 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003479 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003480 return true;
3481
3482 getStreamer().EmitCFIRelOffset(Register, Offset);
3483 return false;
3484}
3485
3486static bool isValidEncoding(int64_t Encoding) {
3487 if (Encoding & ~0xff)
3488 return false;
3489
3490 if (Encoding == dwarf::DW_EH_PE_omit)
3491 return true;
3492
3493 const unsigned Format = Encoding & 0xf;
3494 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3495 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3496 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3497 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3498 return false;
3499
3500 const unsigned Application = Encoding & 0x70;
3501 if (Application != dwarf::DW_EH_PE_absptr &&
3502 Application != dwarf::DW_EH_PE_pcrel)
3503 return false;
3504
3505 return true;
3506}
3507
Jim Grosbach4b905842013-09-20 23:08:21 +00003508/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003509/// IsPersonality true for cfi_personality, false for cfi_lsda
3510/// ::= .cfi_personality encoding, [symbol_name]
3511/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003512bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003513 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003514 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003515 return true;
3516 if (Encoding == dwarf::DW_EH_PE_omit)
3517 return false;
3518
3519 if (!isValidEncoding(Encoding))
3520 return TokError("unsupported encoding.");
3521
3522 if (getLexer().isNot(AsmToken::Comma))
3523 return TokError("unexpected token in directive");
3524 Lex();
3525
3526 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003527 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003528 return TokError("expected identifier in directive");
3529
Jim Grosbach6f482002015-05-18 18:43:14 +00003530 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003531
3532 if (IsPersonality)
3533 getStreamer().EmitCFIPersonality(Sym, Encoding);
3534 else
3535 getStreamer().EmitCFILsda(Sym, Encoding);
3536 return false;
3537}
3538
Jim Grosbach4b905842013-09-20 23:08:21 +00003539/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00003540/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003541bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003542 getStreamer().EmitCFIRememberState();
3543 return false;
3544}
3545
Jim Grosbach4b905842013-09-20 23:08:21 +00003546/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00003547/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003548bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003549 getStreamer().EmitCFIRestoreState();
3550 return false;
3551}
3552
Jim Grosbach4b905842013-09-20 23:08:21 +00003553/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00003554/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00003555bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003556 int64_t Register = 0;
3557
Jim Grosbach4b905842013-09-20 23:08:21 +00003558 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003559 return true;
3560
3561 getStreamer().EmitCFISameValue(Register);
3562 return false;
3563}
3564
Jim Grosbach4b905842013-09-20 23:08:21 +00003565/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00003566/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00003567bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003568 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003569 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003570 return true;
3571
3572 getStreamer().EmitCFIRestore(Register);
3573 return false;
3574}
3575
Jim Grosbach4b905842013-09-20 23:08:21 +00003576/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00003577/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003578bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00003579 std::string Values;
3580 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003581 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003582 return true;
3583
3584 Values.push_back((uint8_t)CurrValue);
3585
3586 while (getLexer().is(AsmToken::Comma)) {
3587 Lex();
3588
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003589 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003590 return true;
3591
3592 Values.push_back((uint8_t)CurrValue);
3593 }
3594
3595 getStreamer().EmitCFIEscape(Values);
3596 return false;
3597}
3598
Jim Grosbach4b905842013-09-20 23:08:21 +00003599/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00003600/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00003601bool AsmParser::parseDirectiveCFISignalFrame() {
Eli Bendersky17233942013-01-15 22:59:42 +00003602 if (getLexer().isNot(AsmToken::EndOfStatement))
3603 return Error(getLexer().getLoc(),
3604 "unexpected token in '.cfi_signal_frame'");
3605
3606 getStreamer().EmitCFISignalFrame();
3607 return false;
3608}
3609
Jim Grosbach4b905842013-09-20 23:08:21 +00003610/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00003611/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00003612bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003613 int64_t Register = 0;
3614
Jim Grosbach4b905842013-09-20 23:08:21 +00003615 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003616 return true;
3617
3618 getStreamer().EmitCFIUndefined(Register);
3619 return false;
3620}
3621
Jim Grosbach4b905842013-09-20 23:08:21 +00003622/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00003623/// ::= .macros_on
3624/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00003625bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00003626 if (getLexer().isNot(AsmToken::EndOfStatement))
3627 return Error(getLexer().getLoc(),
3628 "unexpected token in '" + Directive + "' directive");
3629
Jim Grosbach4b905842013-09-20 23:08:21 +00003630 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00003631 return false;
3632}
3633
Jim Grosbach4b905842013-09-20 23:08:21 +00003634/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003635/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00003636bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003637 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003638 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003639 return TokError("expected identifier in '.macro' directive");
3640
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003641 if (getLexer().is(AsmToken::Comma))
3642 Lex();
3643
Eli Bendersky17233942013-01-15 22:59:42 +00003644 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00003645 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003646
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003647 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003648 return Error(Lexer.getLoc(),
3649 "Vararg parameter '" + Parameters.back().Name +
3650 "' should be last one in the list of parameters.");
3651
David Majnemer91fc4c22014-01-29 18:57:46 +00003652 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003653 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00003654 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003655
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003656 if (Lexer.is(AsmToken::Colon)) {
3657 Lex(); // consume ':'
3658
3659 SMLoc QualLoc;
3660 StringRef Qualifier;
3661
3662 QualLoc = Lexer.getLoc();
3663 if (parseIdentifier(Qualifier))
3664 return Error(QualLoc, "missing parameter qualifier for "
3665 "'" + Parameter.Name + "' in macro '" + Name + "'");
3666
3667 if (Qualifier == "req")
3668 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00003669 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003670 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003671 else
3672 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3673 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3674 }
3675
David Majnemer91fc4c22014-01-29 18:57:46 +00003676 if (getLexer().is(AsmToken::Equal)) {
3677 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003678
3679 SMLoc ParamLoc;
3680
3681 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003682 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00003683 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003684
3685 if (Parameter.Required)
3686 Warning(ParamLoc, "pointless default value for required parameter "
3687 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00003688 }
David Majnemer91fc4c22014-01-29 18:57:46 +00003689
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003690 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00003691
3692 if (getLexer().is(AsmToken::Comma))
3693 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003694 }
3695
3696 // Eat the end of statement.
3697 Lex();
3698
3699 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003700 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003701
3702 // Lex the macro definition.
3703 for (;;) {
3704 // Check whether we have reached the end of the file.
3705 if (getLexer().is(AsmToken::Eof))
3706 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3707
3708 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003709 if (getLexer().is(AsmToken::Identifier)) {
3710 if (getTok().getIdentifier() == ".endm" ||
3711 getTok().getIdentifier() == ".endmacro") {
3712 if (MacroDepth == 0) { // Outermost macro.
3713 EndToken = getTok();
3714 Lex();
3715 if (getLexer().isNot(AsmToken::EndOfStatement))
3716 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3717 "' directive");
3718 break;
3719 } else {
3720 // Otherwise we just found the end of an inner macro.
3721 --MacroDepth;
3722 }
3723 } else if (getTok().getIdentifier() == ".macro") {
3724 // We allow nested macros. Those aren't instantiated until the outermost
3725 // macro is expanded so just ignore them for now.
3726 ++MacroDepth;
3727 }
Eli Bendersky17233942013-01-15 22:59:42 +00003728 }
3729
3730 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003731 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00003732 }
3733
Jim Grosbach4b905842013-09-20 23:08:21 +00003734 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00003735 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3736 }
3737
3738 const char *BodyStart = StartToken.getLoc().getPointer();
3739 const char *BodyEnd = EndToken.getLoc().getPointer();
3740 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00003741 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003742 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00003743 return false;
3744}
3745
Jim Grosbach4b905842013-09-20 23:08:21 +00003746/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00003747///
3748/// With the support added for named parameters there may be code out there that
3749/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00003750/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00003751/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00003752/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00003753/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3754/// warning that the positional parameter found in body which have no effect.
3755/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00003756/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00003757/// intended or change the macro to use the named parameters. It is possible
3758/// this warning will trigger when the none of the named parameters are used
3759/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00003760void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00003761 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00003762 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00003763 // If this macro is not defined with named parameters the warning we are
3764 // checking for here doesn't apply.
3765 unsigned NParameters = Parameters.size();
3766 if (NParameters == 0)
3767 return;
3768
3769 bool NamedParametersFound = false;
3770 bool PositionalParametersFound = false;
3771
3772 // Look at the body of the macro for use of both the named parameters and what
3773 // are likely to be positional parameters. This is what expandMacro() is
3774 // doing when it finds the parameters in the body.
3775 while (!Body.empty()) {
3776 // Scan for the next possible parameter.
3777 std::size_t End = Body.size(), Pos = 0;
3778 for (; Pos != End; ++Pos) {
3779 // Check for a substitution or escape.
3780 // This macro is defined with parameters, look for \foo, \bar, etc.
3781 if (Body[Pos] == '\\' && Pos + 1 != End)
3782 break;
3783
3784 // This macro should have parameters, but look for $0, $1, ..., $n too.
3785 if (Body[Pos] != '$' || Pos + 1 == End)
3786 continue;
3787 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00003788 if (Next == '$' || Next == 'n' ||
3789 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00003790 break;
3791 }
3792
3793 // Check if we reached the end.
3794 if (Pos == End)
3795 break;
3796
3797 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00003798 switch (Body[Pos + 1]) {
3799 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00003800 case '$':
3801 break;
3802
Jim Grosbach4b905842013-09-20 23:08:21 +00003803 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00003804 case 'n':
3805 PositionalParametersFound = true;
3806 break;
3807
Jim Grosbach4b905842013-09-20 23:08:21 +00003808 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00003809 default: {
3810 PositionalParametersFound = true;
3811 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00003812 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00003813 }
3814 Pos += 2;
3815 } else {
3816 unsigned I = Pos + 1;
3817 while (isIdentifierChar(Body[I]) && I + 1 != End)
3818 ++I;
3819
Jim Grosbach4b905842013-09-20 23:08:21 +00003820 const char *Begin = Body.data() + Pos + 1;
3821 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00003822 unsigned Index = 0;
3823 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003824 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00003825 break;
3826
3827 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00003828 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3829 Pos += 3;
3830 else {
3831 Pos = I;
3832 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00003833 } else {
3834 NamedParametersFound = true;
3835 Pos += 1 + Argument.size();
3836 }
3837 }
3838 // Update the scan point.
3839 Body = Body.substr(Pos);
3840 }
3841
3842 if (!NamedParametersFound && PositionalParametersFound)
3843 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3844 "used in macro body, possible positional parameter "
3845 "found in body which will have no effect");
3846}
3847
Nico Weber155dccd12014-07-24 17:08:39 +00003848/// parseDirectiveExitMacro
3849/// ::= .exitm
3850bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3851 if (getLexer().isNot(AsmToken::EndOfStatement))
3852 return TokError("unexpected token in '" + Directive + "' directive");
3853
3854 if (!isInsideMacroInstantiation())
3855 return TokError("unexpected '" + Directive + "' in file, "
3856 "no current macro definition");
3857
3858 // Exit all conditionals that are active in the current macro.
3859 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3860 TheCondState = TheCondStack.back();
3861 TheCondStack.pop_back();
3862 }
3863
3864 handleMacroExit();
3865 return false;
3866}
3867
Jim Grosbach4b905842013-09-20 23:08:21 +00003868/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00003869/// ::= .endm
3870/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00003871bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00003872 if (getLexer().isNot(AsmToken::EndOfStatement))
3873 return TokError("unexpected token in '" + Directive + "' directive");
3874
3875 // If we are inside a macro instantiation, terminate the current
3876 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00003877 if (isInsideMacroInstantiation()) {
3878 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00003879 return false;
3880 }
3881
3882 // Otherwise, this .endmacro is a stray entry in the file; well formed
3883 // .endmacro directives are handled during the macro definition parsing.
3884 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00003885 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00003886}
3887
Jim Grosbach4b905842013-09-20 23:08:21 +00003888/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00003889/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00003890bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003891 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003892 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003893 return TokError("expected identifier in '.purgem' directive");
3894
3895 if (getLexer().isNot(AsmToken::EndOfStatement))
3896 return TokError("unexpected token in '.purgem' directive");
3897
Jim Grosbach4b905842013-09-20 23:08:21 +00003898 if (!lookupMacro(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003899 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3900
Jim Grosbach4b905842013-09-20 23:08:21 +00003901 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003902 return false;
3903}
Eli Benderskyf483ff92012-12-20 19:05:53 +00003904
Jim Grosbach4b905842013-09-20 23:08:21 +00003905/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00003906/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003907bool AsmParser::parseDirectiveBundleAlignMode() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003908 checkForValidSection();
Eli Benderskyf483ff92012-12-20 19:05:53 +00003909
3910 // Expect a single argument: an expression that evaluates to a constant
3911 // in the inclusive range 0-30.
3912 SMLoc ExprLoc = getLexer().getLoc();
3913 int64_t AlignSizePow2;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003914 if (parseAbsoluteExpression(AlignSizePow2))
Eli Benderskyf483ff92012-12-20 19:05:53 +00003915 return true;
3916 else if (getLexer().isNot(AsmToken::EndOfStatement))
3917 return TokError("unexpected token after expression in"
3918 " '.bundle_align_mode' directive");
3919 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3920 return Error(ExprLoc,
3921 "invalid bundle alignment size (expected between 0 and 30)");
3922
3923 Lex();
3924
3925 // Because of AlignSizePow2's verified range we can safely truncate it to
3926 // unsigned.
3927 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3928 return false;
3929}
3930
Jim Grosbach4b905842013-09-20 23:08:21 +00003931/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00003932/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00003933bool AsmParser::parseDirectiveBundleLock() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003934 checkForValidSection();
Eli Bendersky802b6282013-01-07 21:51:08 +00003935 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00003936
Eli Bendersky802b6282013-01-07 21:51:08 +00003937 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3938 StringRef Option;
3939 SMLoc Loc = getTok().getLoc();
3940 const char *kInvalidOptionError =
Jim Grosbach4b905842013-09-20 23:08:21 +00003941 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00003942
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003943 if (parseIdentifier(Option))
Eli Bendersky802b6282013-01-07 21:51:08 +00003944 return Error(Loc, kInvalidOptionError);
3945
3946 if (Option != "align_to_end")
3947 return Error(Loc, kInvalidOptionError);
3948 else if (getLexer().isNot(AsmToken::EndOfStatement))
3949 return Error(Loc,
3950 "unexpected token after '.bundle_lock' directive option");
3951 AlignToEnd = true;
3952 }
3953
Eli Benderskyf483ff92012-12-20 19:05:53 +00003954 Lex();
3955
Eli Bendersky802b6282013-01-07 21:51:08 +00003956 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00003957 return false;
3958}
3959
Jim Grosbach4b905842013-09-20 23:08:21 +00003960/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00003961/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00003962bool AsmParser::parseDirectiveBundleUnlock() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003963 checkForValidSection();
Eli Benderskyf483ff92012-12-20 19:05:53 +00003964
3965 if (getLexer().isNot(AsmToken::EndOfStatement))
3966 return TokError("unexpected token in '.bundle_unlock' directive");
3967 Lex();
3968
3969 getStreamer().EmitBundleUnlock();
3970 return false;
3971}
3972
Jim Grosbach4b905842013-09-20 23:08:21 +00003973/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00003974/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003975bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003976 checkForValidSection();
Eli Bendersky17233942013-01-15 22:59:42 +00003977
3978 int64_t NumBytes;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003979 if (parseAbsoluteExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00003980 return true;
3981
3982 int64_t FillExpr = 0;
3983 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3984 if (getLexer().isNot(AsmToken::Comma))
3985 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3986 Lex();
3987
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003988 if (parseAbsoluteExpression(FillExpr))
Eli Bendersky17233942013-01-15 22:59:42 +00003989 return true;
3990
3991 if (getLexer().isNot(AsmToken::EndOfStatement))
3992 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3993 }
3994
3995 Lex();
3996
3997 if (NumBytes <= 0)
Jim Grosbach4b905842013-09-20 23:08:21 +00003998 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3999 "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004000
4001 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Rafael Espindola64e1af82013-07-02 15:49:13 +00004002 getStreamer().EmitFill(NumBytes, FillExpr);
Eli Bendersky17233942013-01-15 22:59:42 +00004003
4004 return false;
4005}
4006
Jim Grosbach4b905842013-09-20 23:08:21 +00004007/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004008/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004009bool AsmParser::parseDirectiveLEB128(bool Signed) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004010 checkForValidSection();
Eli Bendersky17233942013-01-15 22:59:42 +00004011 const MCExpr *Value;
4012
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004013 for (;;) {
4014 if (parseExpression(Value))
4015 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004016
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004017 if (Signed)
4018 getStreamer().EmitSLEB128Value(Value);
4019 else
4020 getStreamer().EmitULEB128Value(Value);
Eli Bendersky17233942013-01-15 22:59:42 +00004021
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004022 if (getLexer().is(AsmToken::EndOfStatement))
4023 break;
4024
4025 if (getLexer().isNot(AsmToken::Comma))
4026 return TokError("unexpected token in directive");
4027 Lex();
4028 }
Eli Bendersky17233942013-01-15 22:59:42 +00004029
4030 return false;
4031}
4032
Jim Grosbach4b905842013-09-20 23:08:21 +00004033/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004034/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004035bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004036 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbara5508c82009-06-30 00:33:19 +00004037 for (;;) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004038 StringRef Name;
Jim Grosbachebdf32f2011-09-15 17:56:49 +00004039 SMLoc Loc = getTok().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004040
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004041 if (parseIdentifier(Name))
Jim Grosbachebdf32f2011-09-15 17:56:49 +00004042 return Error(Loc, "expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004043
Jim Grosbach6f482002015-05-18 18:43:14 +00004044 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbara5508c82009-06-30 00:33:19 +00004045
Jim Grosbachebdf32f2011-09-15 17:56:49 +00004046 // Assembler local symbols don't make any sense here. Complain loudly.
4047 if (Sym->isTemporary())
4048 return Error(Loc, "non-local symbol required in directive");
4049
Saleem Abdulrasool4208b612013-08-09 01:52:03 +00004050 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4051 return Error(Loc, "unable to emit symbol attribute");
Daniel Dunbara5508c82009-06-30 00:33:19 +00004052
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004053 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara5508c82009-06-30 00:33:19 +00004054 break;
4055
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004056 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara5508c82009-06-30 00:33:19 +00004057 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004058 Lex();
Daniel Dunbara5508c82009-06-30 00:33:19 +00004059 }
4060 }
4061
Sean Callanan686ed8d2010-01-19 20:22:31 +00004062 Lex();
Jan Wen Voungc7682872010-09-30 01:09:20 +00004063 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004064}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004065
Jim Grosbach4b905842013-09-20 23:08:21 +00004066/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004067/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004068bool AsmParser::parseDirectiveComm(bool IsLocal) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004069 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00004070
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004071 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004072 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004073 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004074 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004075
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004076 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004077 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004078
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004079 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004080 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004081 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004082
4083 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004084 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004085 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004086 return true;
4087
4088 int64_t Pow2Alignment = 0;
4089 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004090 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004091 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004092 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004093 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004094 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004095
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004096 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4097 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004098 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4099
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004100 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004101 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4102 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004103 if (!isPowerOf2_64(Pow2Alignment))
4104 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4105 Pow2Alignment = Log2_64(Pow2Alignment);
4106 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004107 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004108
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004109 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner28ad7542009-07-09 17:25:12 +00004110 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004111
Sean Callanan686ed8d2010-01-19 20:22:31 +00004112 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004113
Chris Lattner28ad7542009-07-09 17:25:12 +00004114 // NOTE: a size of zero for a .comm should create a undefined symbol
4115 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004116 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004117 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004118 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004119
Eric Christopherbc818852010-05-14 01:38:54 +00004120 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004121 // may internally end up wanting an alignment in bytes.
4122 // FIXME: Diagnose overflow.
4123 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004124 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004125 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004126
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004127 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004128 return Error(IDLoc, "invalid symbol redefinition");
4129
Chris Lattner28ad7542009-07-09 17:25:12 +00004130 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004131 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004132 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004133 return false;
4134 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004135
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004136 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004137 return false;
4138}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004139
Jim Grosbach4b905842013-09-20 23:08:21 +00004140/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004141/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004142bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004143 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004144 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004145
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004146 StringRef Str = parseStringToEndOfStatement();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004147 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby56523ce2009-07-13 23:15:14 +00004148 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004149
Sean Callanan686ed8d2010-01-19 20:22:31 +00004150 Lex();
Kevin Enderby56523ce2009-07-13 23:15:14 +00004151
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004152 if (Str.empty())
4153 Error(Loc, ".abort detected. Assembly stopping.");
4154 else
4155 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004156 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004157
4158 return false;
4159}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004160
Jim Grosbach4b905842013-09-20 23:08:21 +00004161/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004162/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004163bool AsmParser::parseDirectiveInclude() {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004164 if (getLexer().isNot(AsmToken::String))
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004165 return TokError("expected string in '.include' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004166
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004167 // Allow the strings to have escaped octal character sequence.
4168 std::string Filename;
4169 if (parseEscapedString(Filename))
4170 return true;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004171 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00004172 Lex();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004173
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004174 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004175 return TokError("unexpected token in '.include' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004176
Chris Lattner693fbb82009-07-16 06:14:39 +00004177 // Attempt to switch the lexer to the included file before consuming the end
4178 // of statement to avoid losing it when we switch.
Jim Grosbach4b905842013-09-20 23:08:21 +00004179 if (enterIncludeFile(Filename)) {
Daniel Dunbard8a18452010-07-18 18:31:45 +00004180 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner693fbb82009-07-16 06:14:39 +00004181 return true;
4182 }
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004183
4184 return false;
4185}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004186
Jim Grosbach4b905842013-09-20 23:08:21 +00004187/// parseDirectiveIncbin
Kevin Enderby109f25c2011-12-14 21:47:48 +00004188/// ::= .incbin "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004189bool AsmParser::parseDirectiveIncbin() {
Kevin Enderby109f25c2011-12-14 21:47:48 +00004190 if (getLexer().isNot(AsmToken::String))
4191 return TokError("expected string in '.incbin' directive");
4192
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004193 // Allow the strings to have escaped octal character sequence.
4194 std::string Filename;
4195 if (parseEscapedString(Filename))
4196 return true;
Kevin Enderby109f25c2011-12-14 21:47:48 +00004197 SMLoc IncbinLoc = getLexer().getLoc();
4198 Lex();
4199
4200 if (getLexer().isNot(AsmToken::EndOfStatement))
4201 return TokError("unexpected token in '.incbin' directive");
4202
Kevin Enderby109f25c2011-12-14 21:47:48 +00004203 // Attempt to process the included file.
Jim Grosbach4b905842013-09-20 23:08:21 +00004204 if (processIncbinFile(Filename)) {
Kevin Enderby109f25c2011-12-14 21:47:48 +00004205 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
4206 return true;
4207 }
4208
4209 return false;
4210}
4211
Jim Grosbach4b905842013-09-20 23:08:21 +00004212/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004213/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4214bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004215 TheCondStack.push_back(TheCondState);
4216 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004217 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004218 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004219 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004220 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004221 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004222 return true;
4223
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004224 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004225 return TokError("unexpected token in '.if' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004226
Sean Callanan686ed8d2010-01-19 20:22:31 +00004227 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004228
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004229 switch (DirKind) {
4230 default:
4231 llvm_unreachable("unsupported directive");
4232 case DK_IF:
4233 case DK_IFNE:
4234 break;
4235 case DK_IFEQ:
4236 ExprValue = ExprValue == 0;
4237 break;
4238 case DK_IFGE:
4239 ExprValue = ExprValue >= 0;
4240 break;
4241 case DK_IFGT:
4242 ExprValue = ExprValue > 0;
4243 break;
4244 case DK_IFLE:
4245 ExprValue = ExprValue <= 0;
4246 break;
4247 case DK_IFLT:
4248 ExprValue = ExprValue < 0;
4249 break;
4250 }
4251
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004252 TheCondState.CondMet = ExprValue;
4253 TheCondState.Ignore = !TheCondState.CondMet;
4254 }
4255
4256 return false;
4257}
4258
Jim Grosbach4b905842013-09-20 23:08:21 +00004259/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004260/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004261bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004262 TheCondStack.push_back(TheCondState);
4263 TheCondState.TheCond = AsmCond::IfCond;
4264
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004265 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004266 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004267 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004268 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004269
4270 if (getLexer().isNot(AsmToken::EndOfStatement))
4271 return TokError("unexpected token in '.ifb' directive");
4272
4273 Lex();
4274
4275 TheCondState.CondMet = ExpectBlank == Str.empty();
4276 TheCondState.Ignore = !TheCondState.CondMet;
4277 }
4278
4279 return false;
4280}
4281
Jim Grosbach4b905842013-09-20 23:08:21 +00004282/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004283/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004284/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004285bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004286 TheCondStack.push_back(TheCondState);
4287 TheCondState.TheCond = AsmCond::IfCond;
4288
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004289 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004290 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004291 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004292 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004293
4294 if (getLexer().isNot(AsmToken::Comma))
4295 return TokError("unexpected token in '.ifc' directive");
4296
4297 Lex();
4298
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004299 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004300
4301 if (getLexer().isNot(AsmToken::EndOfStatement))
4302 return TokError("unexpected token in '.ifc' directive");
4303
4304 Lex();
4305
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004306 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004307 TheCondState.Ignore = !TheCondState.CondMet;
4308 }
4309
4310 return false;
4311}
4312
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004313/// parseDirectiveIfeqs
4314/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004315bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004316 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004317 if (ExpectEqual)
4318 TokError("expected string parameter for '.ifeqs' directive");
4319 else
4320 TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004321 eatToEndOfStatement();
4322 return true;
4323 }
4324
4325 StringRef String1 = getTok().getStringContents();
4326 Lex();
4327
4328 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004329 if (ExpectEqual)
4330 TokError("expected comma after first string for '.ifeqs' directive");
4331 else
4332 TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004333 eatToEndOfStatement();
4334 return true;
4335 }
4336
4337 Lex();
4338
4339 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004340 if (ExpectEqual)
4341 TokError("expected string parameter for '.ifeqs' directive");
4342 else
4343 TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004344 eatToEndOfStatement();
4345 return true;
4346 }
4347
4348 StringRef String2 = getTok().getStringContents();
4349 Lex();
4350
4351 TheCondStack.push_back(TheCondState);
4352 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004353 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004354 TheCondState.Ignore = !TheCondState.CondMet;
4355
4356 return false;
4357}
4358
Jim Grosbach4b905842013-09-20 23:08:21 +00004359/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004360/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004361bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004362 StringRef Name;
4363 TheCondStack.push_back(TheCondState);
4364 TheCondState.TheCond = AsmCond::IfCond;
4365
4366 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004367 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004368 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004369 if (parseIdentifier(Name))
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004370 return TokError("expected identifier after '.ifdef'");
4371
4372 Lex();
4373
Jim Grosbach6f482002015-05-18 18:43:14 +00004374 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004375
4376 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004377 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004378 else
Craig Topper353eda42014-04-24 06:44:33 +00004379 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004380 TheCondState.Ignore = !TheCondState.CondMet;
4381 }
4382
4383 return false;
4384}
4385
Jim Grosbach4b905842013-09-20 23:08:21 +00004386/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004387/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004388bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004389 if (TheCondState.TheCond != AsmCond::IfCond &&
4390 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper2172ad62013-04-22 04:24:02 +00004391 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4392 " an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004393 TheCondState.TheCond = AsmCond::ElseIfCond;
4394
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004395 bool LastIgnoreState = false;
4396 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004397 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004398 if (LastIgnoreState || TheCondState.CondMet) {
4399 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004400 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004401 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004402 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004403 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004404 return true;
4405
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004406 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004407 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004408
Sean Callanan686ed8d2010-01-19 20:22:31 +00004409 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004410 TheCondState.CondMet = ExprValue;
4411 TheCondState.Ignore = !TheCondState.CondMet;
4412 }
4413
4414 return false;
4415}
4416
Jim Grosbach4b905842013-09-20 23:08:21 +00004417/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004418/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004419bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004420 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004421 return TokError("unexpected token in '.else' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004422
Sean Callanan686ed8d2010-01-19 20:22:31 +00004423 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004424
4425 if (TheCondState.TheCond != AsmCond::IfCond &&
4426 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper2172ad62013-04-22 04:24:02 +00004427 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4428 ".elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004429 TheCondState.TheCond = AsmCond::ElseCond;
4430 bool LastIgnoreState = false;
4431 if (!TheCondStack.empty())
4432 LastIgnoreState = TheCondStack.back().Ignore;
4433 if (LastIgnoreState || TheCondState.CondMet)
4434 TheCondState.Ignore = true;
4435 else
4436 TheCondState.Ignore = false;
4437
4438 return false;
4439}
4440
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004441/// parseDirectiveEnd
4442/// ::= .end
4443bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4444 if (getLexer().isNot(AsmToken::EndOfStatement))
4445 return TokError("unexpected token in '.end' directive");
4446
4447 Lex();
4448
4449 while (Lexer.isNot(AsmToken::Eof))
4450 Lex();
4451
4452 return false;
4453}
4454
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004455/// parseDirectiveError
4456/// ::= .err
4457/// ::= .error [string]
4458bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4459 if (!TheCondStack.empty()) {
4460 if (TheCondStack.back().Ignore) {
4461 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004462 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004463 }
4464 }
4465
4466 if (!WithMessage)
4467 return Error(L, ".err encountered");
4468
4469 StringRef Message = ".error directive invoked in source file";
4470 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4471 if (Lexer.isNot(AsmToken::String)) {
4472 TokError(".error argument must be a string");
4473 eatToEndOfStatement();
4474 return true;
4475 }
4476
4477 Message = getTok().getStringContents();
4478 Lex();
4479 }
4480
4481 Error(L, Message);
4482 return true;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004483}
4484
Nico Weber404012b2014-07-24 16:26:06 +00004485/// parseDirectiveWarning
4486/// ::= .warning [string]
4487bool AsmParser::parseDirectiveWarning(SMLoc L) {
4488 if (!TheCondStack.empty()) {
4489 if (TheCondStack.back().Ignore) {
4490 eatToEndOfStatement();
4491 return false;
4492 }
4493 }
4494
4495 StringRef Message = ".warning directive invoked in source file";
4496 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4497 if (Lexer.isNot(AsmToken::String)) {
4498 TokError(".warning argument must be a string");
4499 eatToEndOfStatement();
4500 return true;
4501 }
4502
4503 Message = getTok().getStringContents();
4504 Lex();
4505 }
4506
4507 Warning(L, Message);
4508 return false;
4509}
4510
Jim Grosbach4b905842013-09-20 23:08:21 +00004511/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004512/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00004513bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004514 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004515 return TokError("unexpected token in '.endif' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004516
Sean Callanan686ed8d2010-01-19 20:22:31 +00004517 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004518
Jim Grosbach4b905842013-09-20 23:08:21 +00004519 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004520 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4521 ".else");
4522 if (!TheCondStack.empty()) {
4523 TheCondState = TheCondStack.back();
4524 TheCondStack.pop_back();
4525 }
4526
4527 return false;
4528}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00004529
Eli Bendersky17233942013-01-15 22:59:42 +00004530void AsmParser::initializeDirectiveKindMap() {
4531 DirectiveKindMap[".set"] = DK_SET;
4532 DirectiveKindMap[".equ"] = DK_EQU;
4533 DirectiveKindMap[".equiv"] = DK_EQUIV;
4534 DirectiveKindMap[".ascii"] = DK_ASCII;
4535 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4536 DirectiveKindMap[".string"] = DK_STRING;
4537 DirectiveKindMap[".byte"] = DK_BYTE;
4538 DirectiveKindMap[".short"] = DK_SHORT;
4539 DirectiveKindMap[".value"] = DK_VALUE;
4540 DirectiveKindMap[".2byte"] = DK_2BYTE;
4541 DirectiveKindMap[".long"] = DK_LONG;
4542 DirectiveKindMap[".int"] = DK_INT;
4543 DirectiveKindMap[".4byte"] = DK_4BYTE;
4544 DirectiveKindMap[".quad"] = DK_QUAD;
4545 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00004546 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00004547 DirectiveKindMap[".single"] = DK_SINGLE;
4548 DirectiveKindMap[".float"] = DK_FLOAT;
4549 DirectiveKindMap[".double"] = DK_DOUBLE;
4550 DirectiveKindMap[".align"] = DK_ALIGN;
4551 DirectiveKindMap[".align32"] = DK_ALIGN32;
4552 DirectiveKindMap[".balign"] = DK_BALIGN;
4553 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4554 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4555 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4556 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4557 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4558 DirectiveKindMap[".org"] = DK_ORG;
4559 DirectiveKindMap[".fill"] = DK_FILL;
4560 DirectiveKindMap[".zero"] = DK_ZERO;
4561 DirectiveKindMap[".extern"] = DK_EXTERN;
4562 DirectiveKindMap[".globl"] = DK_GLOBL;
4563 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00004564 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4565 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4566 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4567 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4568 DirectiveKindMap[".reference"] = DK_REFERENCE;
4569 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4570 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4571 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4572 DirectiveKindMap[".comm"] = DK_COMM;
4573 DirectiveKindMap[".common"] = DK_COMMON;
4574 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4575 DirectiveKindMap[".abort"] = DK_ABORT;
4576 DirectiveKindMap[".include"] = DK_INCLUDE;
4577 DirectiveKindMap[".incbin"] = DK_INCBIN;
4578 DirectiveKindMap[".code16"] = DK_CODE16;
4579 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4580 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004581 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00004582 DirectiveKindMap[".irp"] = DK_IRP;
4583 DirectiveKindMap[".irpc"] = DK_IRPC;
4584 DirectiveKindMap[".endr"] = DK_ENDR;
4585 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4586 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4587 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4588 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004589 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4590 DirectiveKindMap[".ifge"] = DK_IFGE;
4591 DirectiveKindMap[".ifgt"] = DK_IFGT;
4592 DirectiveKindMap[".ifle"] = DK_IFLE;
4593 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00004594 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00004595 DirectiveKindMap[".ifb"] = DK_IFB;
4596 DirectiveKindMap[".ifnb"] = DK_IFNB;
4597 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004598 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00004599 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00004600 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00004601 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4602 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4603 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4604 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4605 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004606 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00004607 DirectiveKindMap[".endif"] = DK_ENDIF;
4608 DirectiveKindMap[".skip"] = DK_SKIP;
4609 DirectiveKindMap[".space"] = DK_SPACE;
4610 DirectiveKindMap[".file"] = DK_FILE;
4611 DirectiveKindMap[".line"] = DK_LINE;
4612 DirectiveKindMap[".loc"] = DK_LOC;
4613 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004614 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
4615 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
4616 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00004617 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004618 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
4619 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Eli Bendersky17233942013-01-15 22:59:42 +00004620 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4621 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4622 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4623 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4624 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4625 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4626 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4627 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4628 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4629 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4630 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4631 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4632 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4633 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4634 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4635 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4636 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4637 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4638 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4639 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4640 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00004641 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00004642 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4643 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4644 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00004645 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00004646 DirectiveKindMap[".endm"] = DK_ENDM;
4647 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4648 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004649 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004650 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00004651 DirectiveKindMap[".warning"] = DK_WARNING;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00004652 DirectiveKindMap[".reloc"] = DK_RELOC;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00004653}
4654
Jim Grosbach4b905842013-09-20 23:08:21 +00004655MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004656 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004657
Rafael Espindola34b9c512012-06-03 23:57:14 +00004658 unsigned NestLevel = 0;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004659 for (;;) {
4660 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00004661 if (getLexer().is(AsmToken::Eof)) {
4662 Error(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00004663 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004664 }
4665
Rafael Espindola34b9c512012-06-03 23:57:14 +00004666 if (Lexer.is(AsmToken::Identifier) &&
4667 (getTok().getIdentifier() == ".rept")) {
4668 ++NestLevel;
4669 }
4670
4671 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00004672 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004673 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004674 EndToken = getTok();
4675 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004676 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4677 TokError("unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00004678 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004679 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004680 break;
4681 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004682 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004683 }
4684
Rafael Espindola34b9c512012-06-03 23:57:14 +00004685 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004686 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004687 }
4688
4689 const char *BodyStart = StartToken.getLoc().getPointer();
4690 const char *BodyEnd = EndToken.getLoc().getPointer();
4691 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4692
Rafael Espindola34b9c512012-06-03 23:57:14 +00004693 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004694 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00004695 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004696}
4697
Jim Grosbach4b905842013-09-20 23:08:21 +00004698void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00004699 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004700 OS << ".endr\n";
4701
Rafael Espindola3560ff22014-08-27 20:03:13 +00004702 std::unique_ptr<MemoryBuffer> Instantiation =
4703 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004704
Rafael Espindola34b9c512012-06-03 23:57:14 +00004705 // Create the macro instantiation object and add to the current macro
4706 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00004707 MacroInstantiation *MI = new MacroInstantiation(
4708 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00004709 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004710
Rafael Espindola34b9c512012-06-03 23:57:14 +00004711 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00004712 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00004713 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00004714 Lex();
4715}
4716
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004717/// parseDirectiveRept
4718/// ::= .rep | .rept count
4719bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004720 const MCExpr *CountExpr;
4721 SMLoc CountLoc = getTok().getLoc();
4722 if (parseExpression(CountExpr))
4723 return true;
4724
Rafael Espindola34b9c512012-06-03 23:57:14 +00004725 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00004726 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004727 eatToEndOfStatement();
4728 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4729 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004730
4731 if (Count < 0)
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004732 return Error(CountLoc, "Count is negative");
Rafael Espindola34b9c512012-06-03 23:57:14 +00004733
4734 if (Lexer.isNot(AsmToken::EndOfStatement))
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004735 return TokError("unexpected token in '" + Dir + "' directive");
Rafael Espindola34b9c512012-06-03 23:57:14 +00004736
4737 // Eat the end of statement.
4738 Lex();
4739
4740 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004741 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00004742 if (!M)
4743 return true;
4744
4745 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4746 // to hold the macro body with substitutions.
4747 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004748 raw_svector_ostream OS(Buf);
4749 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00004750 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4751 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00004752 return true;
4753 }
Jim Grosbach4b905842013-09-20 23:08:21 +00004754 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004755
4756 return false;
4757}
4758
Jim Grosbach4b905842013-09-20 23:08:21 +00004759/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00004760/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00004761bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00004762 MCAsmMacroParameter Parameter;
Rafael Espindola768b41c2012-06-15 14:02:34 +00004763
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004764 if (parseIdentifier(Parameter.Name))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004765 return TokError("expected identifier in '.irp' directive");
4766
Rafael Espindola768b41c2012-06-15 14:02:34 +00004767 if (Lexer.isNot(AsmToken::Comma))
4768 return TokError("expected comma in '.irp' directive");
4769
4770 Lex();
4771
Eli Bendersky38274122013-01-14 23:22:36 +00004772 MCAsmMacroArguments A;
Craig Topper353eda42014-04-24 06:44:33 +00004773 if (parseMacroArguments(nullptr, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004774 return true;
4775
4776 // Eat the end of statement.
4777 Lex();
4778
4779 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004780 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00004781 if (!M)
4782 return true;
4783
4784 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4785 // to hold the macro body with substitutions.
4786 SmallString<256> Buf;
4787 raw_svector_ostream OS(Buf);
4788
Craig Topper84008482015-10-10 05:38:14 +00004789 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00004790 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4791 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00004792 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004793 return true;
4794 }
4795
Jim Grosbach4b905842013-09-20 23:08:21 +00004796 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00004797
4798 return false;
4799}
4800
Jim Grosbach4b905842013-09-20 23:08:21 +00004801/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004802/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00004803bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00004804 MCAsmMacroParameter Parameter;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004805
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004806 if (parseIdentifier(Parameter.Name))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004807 return TokError("expected identifier in '.irpc' directive");
4808
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004809 if (Lexer.isNot(AsmToken::Comma))
4810 return TokError("expected comma in '.irpc' directive");
4811
4812 Lex();
4813
Eli Bendersky38274122013-01-14 23:22:36 +00004814 MCAsmMacroArguments A;
Craig Topper353eda42014-04-24 06:44:33 +00004815 if (parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004816 return true;
4817
4818 if (A.size() != 1 || A.front().size() != 1)
4819 return TokError("unexpected token in '.irpc' directive");
4820
4821 // Eat the end of statement.
4822 Lex();
4823
4824 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004825 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004826 if (!M)
4827 return true;
4828
4829 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4830 // to hold the macro body with substitutions.
4831 SmallString<256> Buf;
4832 raw_svector_ostream OS(Buf);
4833
4834 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004835 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00004836 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004837 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004838
Toma Tabacu217116e2015-04-27 10:50:29 +00004839 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
4840 // This is undocumented, but GAS seems to support it.
4841 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004842 return true;
4843 }
4844
Jim Grosbach4b905842013-09-20 23:08:21 +00004845 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004846
4847 return false;
4848}
4849
Jim Grosbach4b905842013-09-20 23:08:21 +00004850bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004851 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00004852 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004853
4854 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00004855 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004856 assert(getLexer().is(AsmToken::EndOfStatement));
4857
Jim Grosbach4b905842013-09-20 23:08:21 +00004858 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004859 return false;
4860}
Rafael Espindola12d73d12010-09-11 16:45:15 +00004861
Jim Grosbach4b905842013-09-20 23:08:21 +00004862bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00004863 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00004864 const MCExpr *Value;
4865 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004866 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00004867 return true;
4868 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4869 if (!MCE)
4870 return Error(ExprLoc, "unexpected expression in _emit");
4871 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00004872 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00004873 return Error(ExprLoc, "literal value out of range for directive");
4874
Craig Topper7d5b2312015-10-10 05:25:02 +00004875 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00004876 return false;
4877}
4878
Jim Grosbach4b905842013-09-20 23:08:21 +00004879bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00004880 const MCExpr *Value;
4881 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004882 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00004883 return true;
4884 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4885 if (!MCE)
4886 return Error(ExprLoc, "unexpected expression in align");
4887 uint64_t IntValue = MCE->getValue();
4888 if (!isPowerOf2_64(IntValue))
4889 return Error(ExprLoc, "literal value not a power of two greater then zero");
4890
Craig Topper7d5b2312015-10-10 05:25:02 +00004891 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00004892 return false;
4893}
4894
Chad Rosierf43fcf52013-02-13 21:27:17 +00004895// We are comparing pointers, but the pointers are relative to a single string.
4896// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00004897static int rewritesSort(const AsmRewrite *AsmRewriteA,
4898 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00004899 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4900 return -1;
4901 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4902 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004903
Chad Rosierfce4fab2013-04-08 17:43:47 +00004904 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4905 // rewrite to the same location. Make sure the SizeDirective rewrite is
4906 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4907 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00004908 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4909 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004910 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00004911
Jim Grosbach4b905842013-09-20 23:08:21 +00004912 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4913 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004914 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00004915 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00004916}
4917
Jim Grosbach4b905842013-09-20 23:08:21 +00004918bool AsmParser::parseMSInlineAsm(
4919 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4920 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4921 SmallVectorImpl<std::string> &Constraints,
4922 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4923 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00004924 SmallVector<void *, 4> InputDecls;
4925 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00004926 SmallVector<bool, 4> InputDeclsAddressOf;
4927 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00004928 SmallVector<std::string, 4> InputConstraints;
4929 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00004930 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00004931
Benjamin Kramer1a136112013-02-15 20:37:21 +00004932 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00004933
4934 // Prime the lexer.
4935 Lex();
4936
4937 // While we have input, parse each statement.
4938 unsigned InputIdx = 0;
4939 unsigned OutputIdx = 0;
4940 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00004941 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00004942 if (parseStatement(Info, &SI))
Chad Rosierf1f6a722012-10-19 22:57:33 +00004943 return true;
Chad Rosier8bce6642012-10-18 15:49:34 +00004944
Chad Rosier149e8e02012-12-12 22:45:52 +00004945 if (Info.ParseError)
4946 return true;
4947
Benjamin Kramer1a136112013-02-15 20:37:21 +00004948 if (Info.Opcode == ~0U)
4949 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00004950
Benjamin Kramer1a136112013-02-15 20:37:21 +00004951 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00004952
Benjamin Kramer1a136112013-02-15 20:37:21 +00004953 // Build the list of clobbers, outputs and inputs.
4954 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00004955 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00004956
Benjamin Kramer1a136112013-02-15 20:37:21 +00004957 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00004958 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00004959 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00004960
Benjamin Kramer1a136112013-02-15 20:37:21 +00004961 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00004962 if (Operand.isReg() && !Operand.needAddressOf() &&
4963 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00004964 unsigned NumDefs = Desc.getNumDefs();
4965 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00004966 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4967 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00004968 continue;
4969 }
4970
4971 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00004972 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00004973 if (SymName.empty())
4974 continue;
4975
David Blaikie960ea3f2014-06-08 16:18:35 +00004976 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00004977 if (!OpDecl)
4978 continue;
4979
4980 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00004981 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00004982 if (isOutput) {
4983 ++InputIdx;
4984 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00004985 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00004986 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00004987 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00004988 } else {
4989 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00004990 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4991 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00004992 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00004993 }
Chad Rosier8bce6642012-10-18 15:49:34 +00004994 }
Reid Kleckneree088972013-12-10 18:27:32 +00004995
4996 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00004997 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
4998 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00004999 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005000 }
5001
5002 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005003 NumOutputs = OutputDecls.size();
5004 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005005
5006 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005007 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5008 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5009 ClobberRegs.end());
5010 Clobbers.assign(ClobberRegs.size(), std::string());
5011 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5012 raw_string_ostream OS(Clobbers[I]);
5013 IP->printRegName(OS, ClobberRegs[I]);
5014 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005015
5016 // Merge the various outputs and inputs. Output are expected first.
5017 if (NumOutputs || NumInputs) {
5018 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005019 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005020 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005021 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005022 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005023 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005024 }
5025 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005026 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005027 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005028 }
5029 }
5030
5031 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005032 std::string AsmStringIR;
5033 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005034 StringRef ASMString =
5035 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5036 const char *AsmStart = ASMString.begin();
5037 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005038 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005039 for (const AsmRewrite &AR : AsmStrRewrites) {
5040 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005041 if (Kind == AOK_Delete)
5042 continue;
5043
David Majnemer8114c1a2014-06-23 02:17:16 +00005044 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005045 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005046
Chad Rosier120eefd2013-03-19 17:32:17 +00005047 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005048 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005049 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005050
Chad Rosier37e755c2012-10-23 17:43:43 +00005051 // Skip the original expression.
5052 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005053 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005054 continue;
5055 }
5056
Chad Rosierff10ed12013-04-12 16:26:42 +00005057 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005058 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005059 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005060 default:
5061 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005062 case AOK_Imm:
David Majnemer8114c1a2014-06-23 02:17:16 +00005063 OS << "$$" << AR.Val;
Chad Rosier11c42f22012-10-26 18:04:20 +00005064 break;
5065 case AOK_ImmPrefix:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005066 OS << "$$";
Chad Rosier8bce6642012-10-18 15:49:34 +00005067 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005068 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005069 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005070 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005071 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005072 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005073 break;
5074 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005075 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005076 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005077 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005078 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005079 default: break;
5080 case 8: OS << "byte ptr "; break;
5081 case 16: OS << "word ptr "; break;
5082 case 32: OS << "dword ptr "; break;
5083 case 64: OS << "qword ptr "; break;
5084 case 80: OS << "xword ptr "; break;
5085 case 128: OS << "xmmword ptr "; break;
5086 case 256: OS << "ymmword ptr "; break;
5087 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005088 break;
5089 case AOK_Emit:
5090 OS << ".byte";
5091 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005092 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005093 // MS alignment directives are measured in bytes. If the native assembler
5094 // measures alignment in bytes, we can pass it straight through.
5095 OS << ".align";
5096 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5097 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005098
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005099 // Alignment is in log2 form, so print that instead and skip the original
5100 // immediate.
5101 unsigned Val = AR.Val;
5102 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005103 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005104 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5105 break;
5106 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005107 case AOK_EVEN:
5108 OS << ".even";
5109 break;
Chad Rosierf0e87202012-10-25 20:41:34 +00005110 case AOK_DotOperator:
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005111 // Insert the dot if the user omitted it.
Alp Tokere69170a2014-06-26 22:52:05 +00005112 OS.flush();
5113 if (AsmStringIR.back() != '.')
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005114 OS << '.';
David Majnemer8114c1a2014-06-23 02:17:16 +00005115 OS << AR.Val;
Chad Rosierf0e87202012-10-25 20:41:34 +00005116 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005117 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005118
Chad Rosier8bce6642012-10-18 15:49:34 +00005119 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005120 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005121 }
5122
5123 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005124 if (AsmStart != AsmEnd)
5125 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005126
5127 AsmString = OS.str();
5128 return false;
5129}
5130
Pete Cooper80d21cb2015-06-22 19:35:57 +00005131namespace llvm {
5132namespace MCParserUtils {
5133
5134/// Returns whether the given symbol is used anywhere in the given expression,
5135/// or subexpressions.
5136static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5137 switch (Value->getKind()) {
5138 case MCExpr::Binary: {
5139 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5140 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5141 isSymbolUsedInExpression(Sym, BE->getRHS());
5142 }
5143 case MCExpr::Target:
5144 case MCExpr::Constant:
5145 return false;
5146 case MCExpr::SymbolRef: {
5147 const MCSymbol &S =
5148 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5149 if (S.isVariable())
5150 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5151 return &S == Sym;
5152 }
5153 case MCExpr::Unary:
5154 return isSymbolUsedInExpression(
5155 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5156 }
5157
5158 llvm_unreachable("Unknown expr kind!");
5159}
5160
5161bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5162 MCAsmParser &Parser, MCSymbol *&Sym,
5163 const MCExpr *&Value) {
5164 MCAsmLexer &Lexer = Parser.getLexer();
5165
5166 // FIXME: Use better location, we should use proper tokens.
5167 SMLoc EqualLoc = Lexer.getLoc();
5168
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
5179 if (Lexer.isNot(AsmToken::EndOfStatement))
5180 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}