blob: 1332ef4cde92e1984a20fd6c5fa6e1671d44eb1d [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,
David Majnemer408b5e62016-02-05 01:55:49 +0000361 DK_CV_DEF_RANGE, 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 Majnemer408b5e62016-02-05 01:55:49 +0000399 // ".cv_file", ".cv_loc", ".cv_linetable", "cv_inline_linetable",
400 // ".cv_def_range"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000401 bool parseDirectiveCVFile();
402 bool parseDirectiveCVLoc();
403 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000404 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000405 bool parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000406 bool parseDirectiveCVStringTable();
407 bool parseDirectiveCVFileChecksums();
408
Eli Bendersky17233942013-01-15 22:59:42 +0000409 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000410 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000411 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000412 bool parseDirectiveCFISections();
413 bool parseDirectiveCFIStartProc();
414 bool parseDirectiveCFIEndProc();
415 bool parseDirectiveCFIDefCfaOffset();
416 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
417 bool parseDirectiveCFIAdjustCfaOffset();
418 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
419 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
420 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
421 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
422 bool parseDirectiveCFIRememberState();
423 bool parseDirectiveCFIRestoreState();
424 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
425 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
426 bool parseDirectiveCFIEscape();
427 bool parseDirectiveCFISignalFrame();
428 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000429
430 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000431 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000432 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000433 bool parseDirectiveEndMacro(StringRef Directive);
434 bool parseDirectiveMacro(SMLoc DirectiveLoc);
435 bool parseDirectiveMacrosOnOff(StringRef Directive);
Eli Bendersky17233942013-01-15 22:59:42 +0000436
Eli Benderskyf483ff92012-12-20 19:05:53 +0000437 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000438 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000439 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000440 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000441 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000442 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000443
Eli Bendersky17233942013-01-15 22:59:42 +0000444 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000445 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000446
447 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000448 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000449
Jim Grosbach4b905842013-09-20 23:08:21 +0000450 /// \brief Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000451 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000452 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000453
Jim Grosbach4b905842013-09-20 23:08:21 +0000454 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000455
Jim Grosbach4b905842013-09-20 23:08:21 +0000456 bool parseDirectiveAbort(); // ".abort"
457 bool parseDirectiveInclude(); // ".include"
458 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000459
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000460 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
461 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000462 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000463 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000464 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000465 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000466 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
467 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000468 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000469 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
470 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
471 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
472 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000473 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000474
Jim Grosbach4b905842013-09-20 23:08:21 +0000475 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000476 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000477
Rafael Espindola34b9c512012-06-03 23:57:14 +0000478 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000479 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
480 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000481 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000482 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000483 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
484 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
485 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000486
Chad Rosierc7f552c2013-02-12 21:33:51 +0000487 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000488 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000489 size_t Len);
490
491 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000492 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000493
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000494 // "end"
495 bool parseDirectiveEnd(SMLoc DirectiveLoc);
496
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000497 // ".err" or ".error"
498 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000499
Nico Weber404012b2014-07-24 16:26:06 +0000500 // ".warning"
501 bool parseDirectiveWarning(SMLoc DirectiveLoc);
502
Eli Bendersky17233942013-01-15 22:59:42 +0000503 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000504};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000505}
Daniel Dunbar86033402010-07-12 17:54:38 +0000506
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000507namespace llvm {
508
509extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000510extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000511extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000512
513}
514
Chris Lattnerc35681b2010-01-19 19:46:13 +0000515enum { DEFAULT_ADDRSPACE = 0 };
516
David Blaikie9f380a32015-03-16 18:06:57 +0000517AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
518 const MCAsmInfo &MAI)
519 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
520 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
Alp Tokera55b95b2014-07-06 10:33:31 +0000521 MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
Oliver Stannardcf6bfb12014-11-03 12:19:03 +0000522 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000523 // Save the old handler.
524 SavedDiagHandler = SrcMgr.getDiagHandler();
525 SavedDiagContext = SrcMgr.getDiagContext();
526 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000527 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000528 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000529
Daniel Dunbarc5011082010-07-12 18:12:02 +0000530 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000531 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
532 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000533 PlatformParser.reset(createCOFFAsmParser());
534 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000535 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000536 PlatformParser.reset(createDarwinAsmParser());
537 IsDarwin = true;
538 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000539 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000540 PlatformParser.reset(createELFAsmParser());
541 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000542 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000543
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000544 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000545 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000546
547 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000548}
549
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000550AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000551 assert((HadError || ActiveMacros.empty()) &&
552 "Unexpected active macro instantiation!");
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000553}
554
Jim Grosbach4b905842013-09-20 23:08:21 +0000555void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000556 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000557 for (std::vector<MacroInstantiation *>::const_reverse_iterator
558 it = ActiveMacros.rbegin(),
559 ie = ActiveMacros.rend();
560 it != ie; ++it)
561 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000562 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000563}
564
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000565void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
566 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
567 printMacroInstantiations();
568}
569
Chris Lattnera3a06812011-10-16 04:47:35 +0000570bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000571 if(getTargetParser().getTargetOptions().MCNoWarn)
572 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000573 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Chris Lattnera3a06812011-10-16 04:47:35 +0000574 return Error(L, Msg, Ranges);
Jim Grosbach4b905842013-09-20 23:08:21 +0000575 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
576 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000577 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000578}
579
Chris Lattnera3a06812011-10-16 04:47:35 +0000580bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000581 HadError = true;
Jim Grosbach4b905842013-09-20 23:08:21 +0000582 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
583 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000584 return true;
585}
586
Jim Grosbach4b905842013-09-20 23:08:21 +0000587bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000588 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000589 unsigned NewBuf =
590 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
591 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000592 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000593
Sean Callanan7a77eae2010-01-21 00:19:58 +0000594 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000595 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000596 return false;
597}
Daniel Dunbar43235712010-07-18 18:54:11 +0000598
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000599/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000600/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000601/// returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000602bool AsmParser::processIncbinFile(const std::string &Filename) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000603 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000604 unsigned NewBuf =
605 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
606 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000607 return true;
608
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000609 // Pick up the bytes from the file and emit them.
Rafael Espindola64e1af82013-07-02 15:49:13 +0000610 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
Kevin Enderby109f25c2011-12-14 21:47:48 +0000611 return false;
612}
613
Alp Tokera55b95b2014-07-06 10:33:31 +0000614void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
615 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000616 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
617 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000618}
619
Sean Callanan7a77eae2010-01-21 00:19:58 +0000620const AsmToken &AsmParser::Lex() {
621 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000622
Sean Callanan7a77eae2010-01-21 00:19:58 +0000623 if (tok->is(AsmToken::Eof)) {
624 // If this is the end of an included file, pop the parent file off the
625 // include stack.
626 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
627 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000628 jumpToLoc(ParentIncludeLoc);
Sean Callanan7a77eae2010-01-21 00:19:58 +0000629 tok = &Lexer.Lex();
630 }
631 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000632
Sean Callanan7a77eae2010-01-21 00:19:58 +0000633 if (tok->is(AsmToken::Error))
Daniel Dunbard8a18452010-07-18 18:31:45 +0000634 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencer530ce852010-10-09 11:00:50 +0000635
Sean Callanan7a77eae2010-01-21 00:19:58 +0000636 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000637}
638
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000639bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000640 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000641 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000642 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000643
Chris Lattner36e02122009-06-21 20:54:55 +0000644 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000645 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000646
647 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000648 AsmCond StartingCondState = TheCondState;
649
Kevin Enderby6469fc22011-11-01 22:27:22 +0000650 // If we are generating dwarf for assembly source files save the initial text
651 // section and generate a .file directive.
652 if (getContext().getGenDwarfForAssembly()) {
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000653 MCSection *Sec = getStreamer().getCurrentSection().first;
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000654 if (!Sec->getBeginSymbol()) {
655 MCSymbol *SectionStartSym = getContext().createTempSymbol();
656 getStreamer().EmitLabel(SectionStartSym);
657 Sec->setBeginSymbol(SectionStartSym);
658 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000659 bool InsertResult = getContext().addGenDwarfSection(Sec);
660 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000661 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000662 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
663 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000664 }
665
Chris Lattner73f36112009-07-02 21:53:43 +0000666 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000667 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman0f4871d2012-10-22 23:58:19 +0000668 ParseStatementInfo Info;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000669 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000670 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000671
Daniel Dunbar43325c42010-09-09 22:42:56 +0000672 // We had an error, validate that one was emitted and recover by skipping to
673 // the next line.
674 assert(HadError && "Parse statement returned an error, but none emitted!");
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000675 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000676 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000677
678 if (TheCondState.TheCond != StartingCondState.TheCond ||
679 TheCondState.Ignore != StartingCondState.Ignore)
680 return TokError("unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000681
682 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000683 const auto &LineTables = getContext().getMCDwarfLineTables();
684 if (!LineTables.empty()) {
685 unsigned Index = 0;
686 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
687 if (File.Name.empty() && Index != 0)
688 TokError("unassigned file number: " + Twine(Index) +
689 " for .file directives");
690 ++Index;
691 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000692 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000693
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000694 // Check to see that all assembler local symbols were actually defined.
695 // Targets that don't do subsections via symbols may not want this, though,
696 // so conservatively exclude them. Only do this if we're finalizing, though,
697 // as otherwise we won't necessarilly have seen everything yet.
698 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
Craig Topper84008482015-10-10 05:38:14 +0000699 for (const auto &TableEntry : getContext().getSymbols()) {
700 MCSymbol *Sym = TableEntry.getValue();
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000701 // Variable symbols may not be marked as defined, so check those
702 // explicitly. If we know it's a variable, we have a definition for
703 // the purposes of this check.
704 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
705 // FIXME: We would really like to refer back to where the symbol was
706 // first referenced for a source location. We need to add something
707 // to track that. Currently, we just point to the end of the file.
Jim Grosbach0fdd5722015-10-16 22:07:59 +0000708 return Error(getLexer().getLoc(), "assembler local symbol '" +
709 Sym->getName() + "' not defined");
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000710 }
711 }
712
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000713 // Finalize the output stream if there are no errors and if the client wants
714 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000715 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000716 Out.Finish();
717
Oliver Stannard07b43d32015-11-17 09:58:07 +0000718 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000719}
720
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000721void AsmParser::checkForValidSection() {
Peter Collingbourne2f495b92013-04-17 21:18:16 +0000722 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
Daniel Dunbare5444a82010-09-09 22:42:59 +0000723 TokError("expected section directive before assembly directive");
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000724 Out.InitSections(false);
Daniel Dunbare5444a82010-09-09 22:42:59 +0000725 }
726}
727
Jim Grosbach4b905842013-09-20 23:08:21 +0000728/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000729void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000730 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Sean Callanan686ed8d2010-01-19 20:22:31 +0000731 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000732
Chris Lattnere5074c42009-06-22 01:29:09 +0000733 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000734 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan686ed8d2010-01-19 20:22:31 +0000735 Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000736}
737
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000738StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000739 const char *Start = getTok().getLoc().getPointer();
740
Jim Grosbach4b905842013-09-20 23:08:21 +0000741 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000742 Lex();
743
744 const char *End = getTok().getLoc().getPointer();
745 return StringRef(Start, End - Start);
746}
Chris Lattner78db3622009-06-22 05:51:26 +0000747
Jim Grosbach4b905842013-09-20 23:08:21 +0000748StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000749 const char *Start = getTok().getLoc().getPointer();
750
751 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000752 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000753 Lex();
754
755 const char *End = getTok().getLoc().getPointer();
756 return StringRef(Start, End - Start);
757}
758
Jim Grosbach4b905842013-09-20 23:08:21 +0000759/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000760/// NOTE: This assumes the leading '(' has already been consumed.
761///
762/// parenexpr ::= expr)
763///
Jim Grosbach4b905842013-09-20 23:08:21 +0000764bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
765 if (parseExpression(Res))
766 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000767 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +0000768 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000769 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000770 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +0000771 return false;
772}
Chris Lattner78db3622009-06-22 05:51:26 +0000773
Jim Grosbach4b905842013-09-20 23:08:21 +0000774/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000775/// NOTE: This assumes the leading '[' has already been consumed.
776///
777/// bracketexpr ::= expr]
778///
Jim Grosbach4b905842013-09-20 23:08:21 +0000779bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
780 if (parseExpression(Res))
781 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000782 if (Lexer.isNot(AsmToken::RBrac))
783 return TokError("expected ']' in brackets expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000784 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000785 Lex();
786 return false;
787}
788
Jim Grosbach4b905842013-09-20 23:08:21 +0000789/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000790/// primaryexpr ::= (parenexpr
791/// primaryexpr ::= symbol
792/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +0000793/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +0000794/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +0000795bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000796 SMLoc FirstTokenLoc = getLexer().getLoc();
797 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
798 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +0000799 default:
800 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +0000801 // If we have an error assume that we've already handled it.
802 case AsmToken::Error:
803 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000804 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000805 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000806 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000807 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000808 Res = MCUnaryExpr::createLNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000809 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +0000810 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +0000811 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +0000812 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +0000813 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +0000814 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000815 if (parseIdentifier(Identifier)) {
David Majnemer0c58bc62013-09-25 10:47:21 +0000816 if (FirstTokenKind == AsmToken::Dollar) {
817 if (Lexer.getMAI().getDollarIsPC()) {
818 // This is a '$' reference, which references the current PC. Emit a
819 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000820 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +0000821 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000822 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +0000823 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +0000824 EndLoc = FirstTokenLoc;
825 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +0000826 }
827 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +0000828 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000829 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000830 // Parse symbol variant
831 std::pair<StringRef, StringRef> Split;
832 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +0000833 if (FirstTokenKind == AsmToken::String) {
834 if (Lexer.is(AsmToken::At)) {
835 Lexer.Lex(); // eat @
836 SMLoc AtLoc = getLexer().getLoc();
837 StringRef VName;
838 if (parseIdentifier(VName))
839 return Error(AtLoc, "expected symbol variant after '@'");
840
841 Split = std::make_pair(Identifier, VName);
842 }
843 } else {
844 Split = Identifier.split('@');
845 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000846 } else if (Lexer.is(AsmToken::LParen)) {
847 Lexer.Lex(); // eat (
848 StringRef VName;
849 parseIdentifier(VName);
850 if (Lexer.isNot(AsmToken::RParen)) {
851 return Error(Lexer.getTok().getLoc(),
852 "unexpected token in variant, expected ')'");
853 }
854 Lexer.Lex(); // eat )
855 Split = std::make_pair(Identifier, VName);
856 }
Daniel Dunbar24764322010-08-24 19:13:42 +0000857
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000858 EndLoc = SMLoc::getFromPointer(Identifier.end());
859
Daniel Dunbard20cda02009-10-16 01:34:54 +0000860 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +0000861 StringRef SymbolName = Identifier;
862 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +0000863
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000864 // Lookup the symbol variant if used.
David Peixotto8ad70b32013-12-04 22:43:20 +0000865 if (Split.second.size()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000866 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +0000867 if (Variant != MCSymbolRefExpr::VK_Invalid) {
868 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +0000869 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +0000870 Variant = MCSymbolRefExpr::VK_None;
871 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +0000872 return Error(SMLoc::getFromPointer(Split.second.begin()),
873 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000874 }
875 }
Daniel Dunbar55992562010-03-15 23:51:06 +0000876
Jim Grosbach6f482002015-05-18 18:43:14 +0000877 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +0000878
Daniel Dunbard20cda02009-10-16 01:34:54 +0000879 // If this is an absolute variable reference, substitute it now to preserve
880 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +0000881 if (Sym->isVariable() &&
882 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +0000883 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +0000884 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +0000885
Vedant Kumar86dbd922015-08-31 17:44:53 +0000886 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +0000887 return false;
888 }
889
890 // Otherwise create a symbol ref.
Jim Grosbach13760bd2015-05-30 01:25:56 +0000891 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Chris Lattner78db3622009-06-22 05:51:26 +0000892 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +0000893 }
David Woodhousef42a6662014-02-01 16:20:54 +0000894 case AsmToken::BigNum:
895 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +0000896 case AsmToken::Integer: {
897 SMLoc Loc = getTok().getLoc();
898 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +0000899 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000900 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000901 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +0000902 // Look for 'b' or 'f' following an Integer as a directional label
903 if (Lexer.getKind() == AsmToken::Identifier) {
904 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +0000905 // Lookup the symbol variant if used.
906 std::pair<StringRef, StringRef> Split = IDVal.split('@');
907 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
908 if (Split.first.size() != IDVal.size()) {
909 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +0000910 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +0000911 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000912 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +0000913 }
Jim Grosbach4b905842013-09-20 23:08:21 +0000914 if (IDVal == "f" || IDVal == "b") {
915 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +0000916 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +0000917 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +0000918 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderby0510b482010-05-17 23:08:19 +0000919 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000920 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +0000921 Lex(); // Eat identifier.
922 }
923 }
Chris Lattner78db3622009-06-22 05:51:26 +0000924 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +0000925 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +0000926 case AsmToken::Real: {
927 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +0000928 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +0000929 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000930 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +0000931 Lex(); // Eat token.
932 return false;
933 }
Chris Lattner6b55cb92010-04-14 04:40:28 +0000934 case AsmToken::Dot: {
935 // This is a '.' reference, which references the current PC. Emit a
936 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000937 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +0000938 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000939 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000940 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +0000941 Lex(); // Eat identifier.
942 return false;
943 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000944 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000945 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +0000946 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000947 case AsmToken::LBrac:
948 if (!PlatformParser->HasBracketExpressions())
949 return TokError("brackets expression not supported on this target");
950 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +0000951 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000952 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000953 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000954 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000955 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000956 Res = MCUnaryExpr::createMinus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000957 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000958 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000959 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000960 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000961 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000962 Res = MCUnaryExpr::createPlus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000963 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000964 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000965 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000966 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000967 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000968 Res = MCUnaryExpr::createNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000969 return false;
Chris Lattner78db3622009-06-22 05:51:26 +0000970 }
971}
Chris Lattner7fdbce72009-06-22 06:32:03 +0000972
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000973bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +0000974 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000975 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +0000976}
977
Daniel Dunbar55f16672010-09-17 02:47:07 +0000978const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +0000979AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000980 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +0000981 // Ask the target implementation about this expression first.
982 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
983 if (NewE)
984 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000985 // Recurse over the given expression, rebuilding it to apply the given variant
986 // if there is exactly one symbol.
987 switch (E->getKind()) {
988 case MCExpr::Target:
989 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +0000990 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000991
992 case MCExpr::SymbolRef: {
993 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
994
995 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000996 TokError("invalid variant on expression '" + getTok().getIdentifier() +
997 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000998 return E;
999 }
1000
Jim Grosbach13760bd2015-05-30 01:25:56 +00001001 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001002 }
1003
1004 case MCExpr::Unary: {
1005 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001006 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001007 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001008 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001009 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001010 }
1011
1012 case MCExpr::Binary: {
1013 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001014 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1015 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001016
1017 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001018 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001019
Jim Grosbach4b905842013-09-20 23:08:21 +00001020 if (!LHS)
1021 LHS = BE->getLHS();
1022 if (!RHS)
1023 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001024
Jim Grosbach13760bd2015-05-30 01:25:56 +00001025 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001026 }
1027 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001028
Craig Toppera2886c22012-02-07 05:05:23 +00001029 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001030}
1031
Jim Grosbach4b905842013-09-20 23:08:21 +00001032/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001033///
Jim Grosbachbd164242011-08-20 16:24:13 +00001034/// expr ::= expr &&,|| expr -> lowest.
1035/// expr ::= expr |,^,&,! expr
1036/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1037/// expr ::= expr <<,>> expr
1038/// expr ::= expr +,- expr
1039/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001040/// expr ::= primaryexpr
1041///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001042bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001043 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001044 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001045 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001046 return true;
1047
Daniel Dunbar55f16672010-09-17 02:47:07 +00001048 // As a special case, we support 'a op b @ modifier' by rewriting the
1049 // expression to include the modifier. This is inefficient, but in general we
1050 // expect users to use 'a@modifier op b'.
1051 if (Lexer.getKind() == AsmToken::At) {
1052 Lex();
1053
1054 if (Lexer.isNot(AsmToken::Identifier))
1055 return TokError("unexpected symbol modifier following '@'");
1056
1057 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001058 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001059 if (Variant == MCSymbolRefExpr::VK_Invalid)
1060 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1061
Jim Grosbach4b905842013-09-20 23:08:21 +00001062 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001063 if (!ModifiedRes) {
1064 return TokError("invalid modifier '" + getTok().getIdentifier() +
1065 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001066 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001067
Daniel Dunbar55f16672010-09-17 02:47:07 +00001068 Res = ModifiedRes;
1069 Lex();
1070 }
1071
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001072 // Try to constant fold it up front, if possible.
1073 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001074 if (Res->evaluateAsAbsolute(Value))
1075 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001076
1077 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001078}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001079
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001080bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001081 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001082 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001083}
1084
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001085bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1086 SMLoc &EndLoc) {
1087 if (parseParenExpr(Res, EndLoc))
1088 return true;
1089
1090 for (; ParenDepth > 0; --ParenDepth) {
1091 if (parseBinOpRHS(1, Res, EndLoc))
1092 return true;
1093
1094 // We don't Lex() the last RParen.
1095 // This is the same behavior as parseParenExpression().
1096 if (ParenDepth - 1 > 0) {
1097 if (Lexer.isNot(AsmToken::RParen))
1098 return TokError("expected ')' in parentheses expression");
1099 EndLoc = Lexer.getTok().getEndLoc();
1100 Lex();
1101 }
1102 }
1103 return false;
1104}
1105
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001106bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001107 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001108
Daniel Dunbar75630b32009-06-30 02:10:03 +00001109 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001110 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001111 return true;
1112
Jim Grosbach13760bd2015-05-30 01:25:56 +00001113 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001114 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001115
1116 return false;
1117}
1118
David Majnemer0993e0b2015-10-26 03:15:34 +00001119static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1120 MCBinaryExpr::Opcode &Kind,
1121 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001122 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001123 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001124 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001125
Jim Grosbach4b905842013-09-20 23:08:21 +00001126 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001127 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001128 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001129 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001130 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001131 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001132 return 1;
1133
Jim Grosbach4b905842013-09-20 23:08:21 +00001134 // Low Precedence: |, &, ^
1135 //
1136 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001137 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001138 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001139 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001140 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001141 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001142 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001143 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001144 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001145 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001146
Jim Grosbach4b905842013-09-20 23:08:21 +00001147 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001148 case AsmToken::EqualEqual:
1149 Kind = MCBinaryExpr::EQ;
1150 return 3;
1151 case AsmToken::ExclaimEqual:
1152 case AsmToken::LessGreater:
1153 Kind = MCBinaryExpr::NE;
1154 return 3;
1155 case AsmToken::Less:
1156 Kind = MCBinaryExpr::LT;
1157 return 3;
1158 case AsmToken::LessEqual:
1159 Kind = MCBinaryExpr::LTE;
1160 return 3;
1161 case AsmToken::Greater:
1162 Kind = MCBinaryExpr::GT;
1163 return 3;
1164 case AsmToken::GreaterEqual:
1165 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001166 return 3;
1167
Jim Grosbach4b905842013-09-20 23:08:21 +00001168 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001169 case AsmToken::LessLess:
1170 Kind = MCBinaryExpr::Shl;
1171 return 4;
1172 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001173 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001174 return 4;
1175
Jim Grosbach4b905842013-09-20 23:08:21 +00001176 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001177 case AsmToken::Plus:
1178 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001179 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001180 case AsmToken::Minus:
1181 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001182 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001183
Jim Grosbach4b905842013-09-20 23:08:21 +00001184 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001185 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001186 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001187 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001188 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001189 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001190 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001191 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001192 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001193 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001194 }
1195}
1196
David Majnemer0993e0b2015-10-26 03:15:34 +00001197static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1198 MCBinaryExpr::Opcode &Kind,
1199 bool ShouldUseLogicalShr) {
1200 switch (K) {
1201 default:
1202 return 0; // not a binop.
1203
1204 // Lowest Precedence: &&, ||
1205 case AsmToken::AmpAmp:
1206 Kind = MCBinaryExpr::LAnd;
1207 return 2;
1208 case AsmToken::PipePipe:
1209 Kind = MCBinaryExpr::LOr;
1210 return 1;
1211
1212 // Low Precedence: ==, !=, <>, <, <=, >, >=
1213 case AsmToken::EqualEqual:
1214 Kind = MCBinaryExpr::EQ;
1215 return 3;
1216 case AsmToken::ExclaimEqual:
1217 case AsmToken::LessGreater:
1218 Kind = MCBinaryExpr::NE;
1219 return 3;
1220 case AsmToken::Less:
1221 Kind = MCBinaryExpr::LT;
1222 return 3;
1223 case AsmToken::LessEqual:
1224 Kind = MCBinaryExpr::LTE;
1225 return 3;
1226 case AsmToken::Greater:
1227 Kind = MCBinaryExpr::GT;
1228 return 3;
1229 case AsmToken::GreaterEqual:
1230 Kind = MCBinaryExpr::GTE;
1231 return 3;
1232
1233 // Low Intermediate Precedence: +, -
1234 case AsmToken::Plus:
1235 Kind = MCBinaryExpr::Add;
1236 return 4;
1237 case AsmToken::Minus:
1238 Kind = MCBinaryExpr::Sub;
1239 return 4;
1240
1241 // High Intermediate Precedence: |, &, ^
1242 //
1243 // FIXME: gas seems to support '!' as an infix operator?
1244 case AsmToken::Pipe:
1245 Kind = MCBinaryExpr::Or;
1246 return 5;
1247 case AsmToken::Caret:
1248 Kind = MCBinaryExpr::Xor;
1249 return 5;
1250 case AsmToken::Amp:
1251 Kind = MCBinaryExpr::And;
1252 return 5;
1253
1254 // Highest Precedence: *, /, %, <<, >>
1255 case AsmToken::Star:
1256 Kind = MCBinaryExpr::Mul;
1257 return 6;
1258 case AsmToken::Slash:
1259 Kind = MCBinaryExpr::Div;
1260 return 6;
1261 case AsmToken::Percent:
1262 Kind = MCBinaryExpr::Mod;
1263 return 6;
1264 case AsmToken::LessLess:
1265 Kind = MCBinaryExpr::Shl;
1266 return 6;
1267 case AsmToken::GreaterGreater:
1268 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1269 return 6;
1270 }
1271}
1272
1273unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1274 MCBinaryExpr::Opcode &Kind) {
1275 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1276 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1277 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1278}
1279
Jim Grosbach4b905842013-09-20 23:08:21 +00001280/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001281/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001282bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001283 SMLoc &EndLoc) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001284 while (1) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001285 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001286 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001287
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001288 // If the next token is lower precedence than we are allowed to eat, return
1289 // successfully with what we ate already.
1290 if (TokPrec < Precedence)
1291 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001292
Sean Callanan686ed8d2010-01-19 20:22:31 +00001293 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001294
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001295 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001296 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001297 if (parsePrimaryExpr(RHS, EndLoc))
1298 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001299
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001300 // If BinOp binds less tightly with RHS than the operator after RHS, let
1301 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001302 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001303 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001304 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1305 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001306
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001307 // Merge LHS and RHS according to operator.
Jim Grosbach13760bd2015-05-30 01:25:56 +00001308 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001309 }
1310}
1311
Chris Lattner36e02122009-06-21 20:54:55 +00001312/// ParseStatement:
1313/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001314/// ::= Label* Directive ...Operands... EndOfStatement
1315/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001316bool AsmParser::parseStatement(ParseStatementInfo &Info,
1317 MCAsmParserSemaCallback *SI) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001318 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar8271d1bb2010-05-23 18:36:34 +00001319 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001320 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001321 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001322 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001323
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001324 // Statements always start with an identifier or are a full line comment.
Sean Callanan936b0d32010-01-19 21:44:56 +00001325 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001326 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001327 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001328 int64_t LocalLabelVal = -1;
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001329 // A full line comment is a '#' as the first token.
Kevin Enderby72553612011-09-13 23:45:18 +00001330 if (Lexer.is(AsmToken::Hash))
Jim Grosbach4b905842013-09-20 23:08:21 +00001331 return parseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar3f561042011-03-25 17:47:14 +00001332
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001333 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001334 if (Lexer.is(AsmToken::Integer)) {
1335 LocalLabelVal = getTok().getIntVal();
1336 if (LocalLabelVal < 0) {
1337 if (!TheCondState.Ignore)
1338 return TokError("unexpected token at start of statement");
1339 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001340 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001341 IDVal = getTok().getString();
1342 Lex(); // Consume the integer token to be used as an identifier token.
1343 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands41b4a6b2010-07-12 08:16:59 +00001344 if (!TheCondState.Ignore)
1345 return TokError("unexpected token at start of statement");
Kevin Enderby0510b482010-05-17 23:08:19 +00001346 }
1347 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001348 } else if (Lexer.is(AsmToken::Dot)) {
1349 // Treat '.' as a valid identifier in this context.
1350 Lex();
1351 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001352 } else if (Lexer.is(AsmToken::LCurly)) {
1353 // Treat '{' as a valid identifier in this context.
1354 Lex();
1355 IDVal = "{";
1356
1357 } else if (Lexer.is(AsmToken::RCurly)) {
1358 // Treat '}' as a valid identifier in this context.
1359 Lex();
1360 IDVal = "}";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001361 } else if (parseIdentifier(IDVal)) {
Chris Lattner926885c2010-04-17 18:14:27 +00001362 if (!TheCondState.Ignore)
1363 return TokError("unexpected token at start of statement");
1364 IDVal = "";
1365 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001366
Chris Lattner926885c2010-04-17 18:14:27 +00001367 // Handle conditional assembly here before checking for skipping. We
1368 // have to do this so that .endif isn't skipped in a ".if 0" block for
1369 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001370 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001371 DirectiveKindMap.find(IDVal);
1372 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1373 ? DK_NO_DIRECTIVE
1374 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001375 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001376 default:
1377 break;
1378 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001379 case DK_IFEQ:
1380 case DK_IFGE:
1381 case DK_IFGT:
1382 case DK_IFLE:
1383 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001384 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001385 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001386 case DK_IFB:
1387 return parseDirectiveIfb(IDLoc, true);
1388 case DK_IFNB:
1389 return parseDirectiveIfb(IDLoc, false);
1390 case DK_IFC:
1391 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001392 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001393 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001394 case DK_IFNC:
1395 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001396 case DK_IFNES:
1397 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001398 case DK_IFDEF:
1399 return parseDirectiveIfdef(IDLoc, true);
1400 case DK_IFNDEF:
1401 case DK_IFNOTDEF:
1402 return parseDirectiveIfdef(IDLoc, false);
1403 case DK_ELSEIF:
1404 return parseDirectiveElseIf(IDLoc);
1405 case DK_ELSE:
1406 return parseDirectiveElse(IDLoc);
1407 case DK_ENDIF:
1408 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001409 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001410
Eli Bendersky88024712013-01-16 19:32:36 +00001411 // Ignore the statement if in the middle of inactive conditional
1412 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001413 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001414 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001415 return false;
1416 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001417
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001418 // FIXME: Recurse on local labels?
1419
1420 // See what kind of statement we have.
1421 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001422 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001423 if (!getTargetParser().isLabel(ID))
1424 break;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001425 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00001426
Chris Lattner36e02122009-06-21 20:54:55 +00001427 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001428 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001429
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001430 // Diagnose attempt to use '.' as a label.
1431 if (IDVal == ".")
1432 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1433
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001434 // Diagnose attempt to use a variable as a label.
1435 //
1436 // FIXME: Diagnostics. Note the location of the definition as a label.
1437 // FIXME: This doesn't diagnose assignment to a symbol which has been
1438 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001439 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001440 if (LocalLabelVal == -1) {
1441 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001442 StringRef RewrittenLabel =
1443 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1444 assert(RewrittenLabel.size() &&
1445 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001446 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1447 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001448 IDVal = RewrittenLabel;
1449 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001450 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001451 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001452 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
David Majnemer58cb80c2014-12-24 10:27:50 +00001453
1454 Sym->redefineIfPossible();
1455
Daniel Dunbardeb7ba92010-05-05 19:01:00 +00001456 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001457 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencer530ce852010-10-09 11:00:50 +00001458
Daniel Dunbare73b2672009-08-26 22:13:22 +00001459 // Emit the label.
Chad Rosierf3feab32013-01-07 20:34:12 +00001460 if (!ParsingInlineAsm)
1461 Out.EmitLabel(Sym);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001462
Kevin Enderbye7739d42011-12-09 18:09:40 +00001463 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001464 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001465 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001466 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1467 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001468
Tim Northover1744d0a2013-10-25 12:49:50 +00001469 getTargetParser().onLabelParsed(Sym);
1470
Daniel Dunbar8271d1bb2010-05-23 18:36:34 +00001471 // Consume any end of statement token, if present, to avoid spurious
1472 // AddBlankLine calls().
1473 if (Lexer.is(AsmToken::EndOfStatement)) {
1474 Lex();
1475 if (Lexer.is(AsmToken::Eof))
1476 return false;
1477 }
1478
Eli Friedman0f4871d2012-10-22 23:58:19 +00001479 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001480 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001481
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001482 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001483 if (!getTargetParser().equalIsAsmAssignment())
1484 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001485 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001486 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001487
Jim Grosbach4b905842013-09-20 23:08:21 +00001488 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001489
1490 default: // Normal instruction or directive.
1491 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001492 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001493
1494 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001495 if (areMacrosEnabled())
1496 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1497 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001498 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001499
Michael J. Spencer530ce852010-10-09 11:00:50 +00001500 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001501
Eli Bendersky17233942013-01-15 22:59:42 +00001502 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001503 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001504 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001505 //
Eli Bendersky17233942013-01-15 22:59:42 +00001506 // 1. The target-specific assembly parser. Some directives are target
1507 // specific or may potentially behave differently on certain targets.
1508 // 2. Asm parser extensions. For example, platform-specific parsers
1509 // (like the ELF parser) register themselves as extensions.
1510 // 3. The generic directive parser implemented by this class. These are
1511 // all the directives that behave in a target and platform independent
1512 // manner, or at least have a default behavior that's shared between
1513 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001514
Eli Bendersky17233942013-01-15 22:59:42 +00001515 // First query the target-specific parser. It will return 'true' if it
1516 // isn't interested in this directive.
Akira Hatanakad3590752012-07-05 19:09:33 +00001517 if (!getTargetParser().ParseDirective(ID))
1518 return false;
1519
Alp Tokercb402912014-01-24 17:20:08 +00001520 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001521 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001522 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1523 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001524 if (Handler.first)
1525 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1526
1527 // Finally, if no one else is interested in this directive, it must be
1528 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001529 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001530 default:
1531 break;
1532 case DK_SET:
1533 case DK_EQU:
1534 return parseDirectiveSet(IDVal, true);
1535 case DK_EQUIV:
1536 return parseDirectiveSet(IDVal, false);
1537 case DK_ASCII:
1538 return parseDirectiveAscii(IDVal, false);
1539 case DK_ASCIZ:
1540 case DK_STRING:
1541 return parseDirectiveAscii(IDVal, true);
1542 case DK_BYTE:
1543 return parseDirectiveValue(1);
1544 case DK_SHORT:
1545 case DK_VALUE:
1546 case DK_2BYTE:
1547 return parseDirectiveValue(2);
1548 case DK_LONG:
1549 case DK_INT:
1550 case DK_4BYTE:
1551 return parseDirectiveValue(4);
1552 case DK_QUAD:
1553 case DK_8BYTE:
1554 return parseDirectiveValue(8);
David Woodhoused6de0d92014-02-01 16:20:59 +00001555 case DK_OCTA:
1556 return parseDirectiveOctaValue();
Jim Grosbach4b905842013-09-20 23:08:21 +00001557 case DK_SINGLE:
1558 case DK_FLOAT:
1559 return parseDirectiveRealValue(APFloat::IEEEsingle);
1560 case DK_DOUBLE:
1561 return parseDirectiveRealValue(APFloat::IEEEdouble);
1562 case DK_ALIGN: {
1563 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1564 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1565 }
1566 case DK_ALIGN32: {
1567 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1568 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1569 }
1570 case DK_BALIGN:
1571 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1572 case DK_BALIGNW:
1573 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1574 case DK_BALIGNL:
1575 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1576 case DK_P2ALIGN:
1577 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1578 case DK_P2ALIGNW:
1579 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1580 case DK_P2ALIGNL:
1581 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1582 case DK_ORG:
1583 return parseDirectiveOrg();
1584 case DK_FILL:
1585 return parseDirectiveFill();
1586 case DK_ZERO:
1587 return parseDirectiveZero();
1588 case DK_EXTERN:
1589 eatToEndOfStatement(); // .extern is the default, ignore it.
1590 return false;
1591 case DK_GLOBL:
1592 case DK_GLOBAL:
1593 return parseDirectiveSymbolAttribute(MCSA_Global);
1594 case DK_LAZY_REFERENCE:
1595 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1596 case DK_NO_DEAD_STRIP:
1597 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1598 case DK_SYMBOL_RESOLVER:
1599 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1600 case DK_PRIVATE_EXTERN:
1601 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1602 case DK_REFERENCE:
1603 return parseDirectiveSymbolAttribute(MCSA_Reference);
1604 case DK_WEAK_DEFINITION:
1605 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1606 case DK_WEAK_REFERENCE:
1607 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1608 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1609 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1610 case DK_COMM:
1611 case DK_COMMON:
1612 return parseDirectiveComm(/*IsLocal=*/false);
1613 case DK_LCOMM:
1614 return parseDirectiveComm(/*IsLocal=*/true);
1615 case DK_ABORT:
1616 return parseDirectiveAbort();
1617 case DK_INCLUDE:
1618 return parseDirectiveInclude();
1619 case DK_INCBIN:
1620 return parseDirectiveIncbin();
1621 case DK_CODE16:
1622 case DK_CODE16GCC:
1623 return TokError(Twine(IDVal) + " not supported yet");
1624 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001625 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001626 case DK_IRP:
1627 return parseDirectiveIrp(IDLoc);
1628 case DK_IRPC:
1629 return parseDirectiveIrpc(IDLoc);
1630 case DK_ENDR:
1631 return parseDirectiveEndr(IDLoc);
1632 case DK_BUNDLE_ALIGN_MODE:
1633 return parseDirectiveBundleAlignMode();
1634 case DK_BUNDLE_LOCK:
1635 return parseDirectiveBundleLock();
1636 case DK_BUNDLE_UNLOCK:
1637 return parseDirectiveBundleUnlock();
1638 case DK_SLEB128:
1639 return parseDirectiveLEB128(true);
1640 case DK_ULEB128:
1641 return parseDirectiveLEB128(false);
1642 case DK_SPACE:
1643 case DK_SKIP:
1644 return parseDirectiveSpace(IDVal);
1645 case DK_FILE:
1646 return parseDirectiveFile(IDLoc);
1647 case DK_LINE:
1648 return parseDirectiveLine();
1649 case DK_LOC:
1650 return parseDirectiveLoc();
1651 case DK_STABS:
1652 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001653 case DK_CV_FILE:
1654 return parseDirectiveCVFile();
1655 case DK_CV_LOC:
1656 return parseDirectiveCVLoc();
1657 case DK_CV_LINETABLE:
1658 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00001659 case DK_CV_INLINE_LINETABLE:
1660 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00001661 case DK_CV_DEF_RANGE:
1662 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001663 case DK_CV_STRINGTABLE:
1664 return parseDirectiveCVStringTable();
1665 case DK_CV_FILECHECKSUMS:
1666 return parseDirectiveCVFileChecksums();
Jim Grosbach4b905842013-09-20 23:08:21 +00001667 case DK_CFI_SECTIONS:
1668 return parseDirectiveCFISections();
1669 case DK_CFI_STARTPROC:
1670 return parseDirectiveCFIStartProc();
1671 case DK_CFI_ENDPROC:
1672 return parseDirectiveCFIEndProc();
1673 case DK_CFI_DEF_CFA:
1674 return parseDirectiveCFIDefCfa(IDLoc);
1675 case DK_CFI_DEF_CFA_OFFSET:
1676 return parseDirectiveCFIDefCfaOffset();
1677 case DK_CFI_ADJUST_CFA_OFFSET:
1678 return parseDirectiveCFIAdjustCfaOffset();
1679 case DK_CFI_DEF_CFA_REGISTER:
1680 return parseDirectiveCFIDefCfaRegister(IDLoc);
1681 case DK_CFI_OFFSET:
1682 return parseDirectiveCFIOffset(IDLoc);
1683 case DK_CFI_REL_OFFSET:
1684 return parseDirectiveCFIRelOffset(IDLoc);
1685 case DK_CFI_PERSONALITY:
1686 return parseDirectiveCFIPersonalityOrLsda(true);
1687 case DK_CFI_LSDA:
1688 return parseDirectiveCFIPersonalityOrLsda(false);
1689 case DK_CFI_REMEMBER_STATE:
1690 return parseDirectiveCFIRememberState();
1691 case DK_CFI_RESTORE_STATE:
1692 return parseDirectiveCFIRestoreState();
1693 case DK_CFI_SAME_VALUE:
1694 return parseDirectiveCFISameValue(IDLoc);
1695 case DK_CFI_RESTORE:
1696 return parseDirectiveCFIRestore(IDLoc);
1697 case DK_CFI_ESCAPE:
1698 return parseDirectiveCFIEscape();
1699 case DK_CFI_SIGNAL_FRAME:
1700 return parseDirectiveCFISignalFrame();
1701 case DK_CFI_UNDEFINED:
1702 return parseDirectiveCFIUndefined(IDLoc);
1703 case DK_CFI_REGISTER:
1704 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00001705 case DK_CFI_WINDOW_SAVE:
1706 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00001707 case DK_MACROS_ON:
1708 case DK_MACROS_OFF:
1709 return parseDirectiveMacrosOnOff(IDVal);
1710 case DK_MACRO:
1711 return parseDirectiveMacro(IDLoc);
Nico Weber155dccd12014-07-24 17:08:39 +00001712 case DK_EXITM:
1713 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001714 case DK_ENDM:
1715 case DK_ENDMACRO:
1716 return parseDirectiveEndMacro(IDVal);
1717 case DK_PURGEM:
1718 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00001719 case DK_END:
1720 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00001721 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00001722 return parseDirectiveError(IDLoc, false);
1723 case DK_ERROR:
1724 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00001725 case DK_WARNING:
1726 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00001727 case DK_RELOC:
1728 return parseDirectiveReloc(IDLoc);
Eli Friedman20b02642010-07-19 04:17:25 +00001729 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00001730
Jim Grosbach758e0cc2012-05-01 18:38:27 +00001731 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00001732 }
Chris Lattner36e02122009-06-21 20:54:55 +00001733
Chad Rosierc7f552c2013-02-12 21:33:51 +00001734 // __asm _emit or __asm __emit
1735 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1736 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001737 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00001738
1739 // __asm align
1740 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001741 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00001742
Michael Zuckerman02ecd432015-12-13 17:07:23 +00001743 if (ParsingInlineAsm && (IDVal == "even"))
1744 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001745 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00001746
Chris Lattner7cbfa442010-05-19 23:34:33 +00001747 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00001748 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00001749 ParseInstructionInfo IInfo(Info.AsmRewrites);
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001750 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001751 Info.ParsedOperands);
Chad Rosier149e8e02012-12-12 22:45:52 +00001752 Info.ParseError = HadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00001753
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001754 // Dump the parsed representation, if requested.
1755 if (getShowParsedOperands()) {
1756 SmallString<256> Str;
1757 raw_svector_ostream OS(Str);
1758 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001759 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001760 if (i != 0)
1761 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001762 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001763 }
1764 OS << "]";
1765
Jim Grosbach4b905842013-09-20 23:08:21 +00001766 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001767 }
1768
Oliver Stannard8b273082014-06-19 15:52:37 +00001769 // If we are generating dwarf for the current section then generate a .loc
1770 // directive for the instruction.
Kevin Enderby6469fc22011-11-01 22:27:22 +00001771 if (!HadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00001772 getContext().getGenDwarfSectionSyms().count(
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00001773 getStreamer().getCurrentSection().first)) {
1774 unsigned Line;
1775 if (ActiveMacros.empty())
1776 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1777 else
Frederic Riss16238d92015-06-25 21:57:33 +00001778 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
1779 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001780
Eli Bendersky88024712013-01-16 19:32:36 +00001781 // If we previously parsed a cpp hash file line comment then make sure the
1782 // current Dwarf File is for the CppHashFilename if not then emit the
1783 // Dwarf File table for it and adjust the line number for the .loc.
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00001784 if (CppHashFilename.size()) {
David Blaikiec714ef42014-03-17 01:52:11 +00001785 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1786 0, StringRef(), CppHashFilename);
1787 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001788
Jim Grosbach4b905842013-09-20 23:08:21 +00001789 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1790 // cache with the different Loc from the call above we save the last
1791 // info we queried here with SrcMgr.FindLineNumber().
1792 unsigned CppHashLocLineNo;
1793 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1794 CppHashLocLineNo = LastQueryLine;
1795 else {
1796 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1797 LastQueryLine = CppHashLocLineNo;
1798 LastQueryIDLoc = CppHashLoc;
1799 LastQueryBuffer = CppHashBuf;
1800 }
1801 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00001802 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001803
Jim Grosbach4b905842013-09-20 23:08:21 +00001804 getStreamer().EmitDwarfLocDirective(
1805 getContext().getGenDwarfFileNumber(), Line, 0,
1806 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1807 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00001808 }
1809
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00001810 // If parsing succeeded, match the instruction.
Chad Rosier49963552012-10-13 00:26:04 +00001811 if (!HadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00001812 uint64_t ErrorInfo;
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001813 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1814 Info.ParsedOperands, Out,
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00001815 ErrorInfo, ParsingInlineAsm);
Chad Rosier49963552012-10-13 00:26:04 +00001816 }
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001817
Chris Lattnera2a9d162010-09-11 16:18:25 +00001818 // Don't skip the rest of the line, the instruction parser is responsible for
1819 // that.
1820 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00001821}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00001822
Jim Grosbach4b905842013-09-20 23:08:21 +00001823/// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
Kevin Enderby72553612011-09-13 23:45:18 +00001824/// since they may not be able to be tokenized to get to the end of line token.
Jim Grosbach4b905842013-09-20 23:08:21 +00001825void AsmParser::eatToEndOfLine() {
Rafael Espindolae0d09082011-10-19 18:48:52 +00001826 if (!Lexer.is(AsmToken::EndOfStatement))
1827 Lexer.LexUntilEndOfLine();
Jim Grosbach4b905842013-09-20 23:08:21 +00001828 // Eat EOL.
1829 Lex();
Kevin Enderby72553612011-09-13 23:45:18 +00001830}
1831
Jim Grosbach4b905842013-09-20 23:08:21 +00001832/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00001833/// ::= # number "filename"
1834/// or just as a full line comment if it doesn't have a number and a string.
Craig Topper3c76c522015-09-20 23:35:59 +00001835bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00001836 Lex(); // Eat the hash token.
1837
1838 if (getLexer().isNot(AsmToken::Integer)) {
1839 // Consume the line since in cases it is not a well-formed line directive,
1840 // as if were simply a full line comment.
Jim Grosbach4b905842013-09-20 23:08:21 +00001841 eatToEndOfLine();
Kevin Enderby72553612011-09-13 23:45:18 +00001842 return false;
1843 }
1844
1845 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00001846 Lex();
1847
1848 if (getLexer().isNot(AsmToken::String)) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001849 eatToEndOfLine();
Kevin Enderby72553612011-09-13 23:45:18 +00001850 return false;
1851 }
1852
1853 StringRef Filename = getTok().getString();
1854 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00001855 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00001856
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001857 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1858 CppHashLoc = L;
1859 CppHashFilename = Filename;
1860 CppHashLineNumber = LineNumber;
Kevin Enderby27121c12012-11-05 21:55:41 +00001861 CppHashBuf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00001862
1863 // Ignore any trailing characters, they're just comment.
Jim Grosbach4b905842013-09-20 23:08:21 +00001864 eatToEndOfLine();
Kevin Enderby72553612011-09-13 23:45:18 +00001865 return false;
1866}
1867
Jim Grosbach4b905842013-09-20 23:08:21 +00001868/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001869/// for the Filename and LineNo if any in the diagnostic.
1870void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001871 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001872 raw_ostream &OS = errs();
1873
1874 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00001875 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00001876 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1877 unsigned CppHashBuf =
1878 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001879
Jim Grosbach4b905842013-09-20 23:08:21 +00001880 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001881 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00001882 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1883 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1884 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001885 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1886 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001887 }
1888
Eric Christophera7c32732012-12-18 00:30:54 +00001889 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001890 // manager changed or buffer changed (like in a nested include) then just
1891 // print the normal diagnostic using its Filename and LineNo.
Jim Grosbach4b905842013-09-20 23:08:21 +00001892 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001893 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00001894 if (Parser->SavedDiagHandler)
1895 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1896 else
Craig Topper353eda42014-04-24 06:44:33 +00001897 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001898 return;
1899 }
1900
Eric Christophera7c32732012-12-18 00:30:54 +00001901 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001902 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1903 // the diagnostic.
Jakub Staszakec2ffa92013-09-16 22:03:38 +00001904 const std::string &Filename = Parser->CppHashFilename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001905
1906 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1907 int CppHashLocLineNo =
1908 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00001909 int LineNo =
1910 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001911
Jim Grosbach4b905842013-09-20 23:08:21 +00001912 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1913 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00001914 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001915
Benjamin Kramer47f5e302011-10-16 10:48:29 +00001916 if (Parser->SavedDiagHandler)
1917 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1918 else
Craig Topper353eda42014-04-24 06:44:33 +00001919 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001920}
1921
Rafael Espindola2c064482012-08-21 18:29:30 +00001922// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1923// difference being that that function accepts '@' as part of identifiers and
1924// we can't do that. AsmLexer.cpp should probably be changed to handle
1925// '@' as a special case when needed.
1926static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001927 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1928 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00001929}
1930
Rafael Espindola34b9c512012-06-03 23:57:14 +00001931bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00001932 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00001933 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00001934 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00001935 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00001936 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00001937 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00001938 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001939
Preston Gurd05500642012-09-19 20:36:12 +00001940 // A macro without parameters is handled differently on Darwin:
1941 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001942 while (!Body.empty()) {
1943 // Scan for the next substitution.
1944 std::size_t End = Body.size(), Pos = 0;
1945 for (; Pos != End; ++Pos) {
1946 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00001947 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00001948 // This macro has no parameters, look for $0, $1, etc.
1949 if (Body[Pos] != '$' || Pos + 1 == End)
1950 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001951
Rafael Espindola1134ab232011-06-05 02:43:45 +00001952 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00001953 if (Next == '$' || Next == 'n' ||
1954 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00001955 break;
1956 } else {
1957 // This macro has parameters, look for \foo, \bar, etc.
1958 if (Body[Pos] == '\\' && Pos + 1 != End)
1959 break;
1960 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001961 }
1962
1963 // Add the prefix.
1964 OS << Body.slice(0, Pos);
1965
1966 // Check if we reached the end.
1967 if (Pos == End)
1968 break;
1969
Benjamin Kramer513e7442014-02-20 13:36:32 +00001970 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001971 switch (Body[Pos + 1]) {
1972 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00001973 case '$':
1974 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001975 break;
1976
Jim Grosbach4b905842013-09-20 23:08:21 +00001977 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00001978 case 'n':
1979 OS << A.size();
1980 break;
1981
Jim Grosbach4b905842013-09-20 23:08:21 +00001982 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00001983 default: {
1984 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00001985 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00001986 if (Index >= A.size())
1987 break;
1988
1989 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00001990 for (const AsmToken &Token : A[Index])
1991 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00001992 break;
1993 }
1994 }
1995 Pos += 2;
1996 } else {
1997 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00001998
1999 // Check for the \@ pseudo-variable.
2000 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002001 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002002 else
2003 while (isIdentifierChar(Body[I]) && I + 1 != End)
2004 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002005
Jim Grosbach4b905842013-09-20 23:08:21 +00002006 const char *Begin = Body.data() + Pos + 1;
2007 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002008 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002009
Toma Tabacu217116e2015-04-27 10:50:29 +00002010 if (Argument == "@") {
2011 OS << NumOfMacroInstantiations;
2012 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002013 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002014 for (; Index < NParameters; ++Index)
2015 if (Parameters[Index].Name == Argument)
2016 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002017
Toma Tabacu217116e2015-04-27 10:50:29 +00002018 if (Index == NParameters) {
2019 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2020 Pos += 3;
2021 else {
2022 OS << '\\' << Argument;
2023 Pos = I;
2024 }
2025 } else {
2026 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002027 for (const AsmToken &Token : A[Index])
Toma Tabacu217116e2015-04-27 10:50:29 +00002028 // We expect no quotes around the string's contents when
2029 // parsing for varargs.
Craig Topper84008482015-10-10 05:38:14 +00002030 if (Token.getKind() != AsmToken::String || VarargParameter)
2031 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002032 else
Craig Topper84008482015-10-10 05:38:14 +00002033 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002034
2035 Pos += 1 + Argument.size();
2036 }
Preston Gurd05500642012-09-19 20:36:12 +00002037 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002038 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002039 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002040 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002041 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002042
Rafael Espindola1134ab232011-06-05 02:43:45 +00002043 return false;
2044}
Daniel Dunbar43235712010-07-18 18:54:11 +00002045
Nico Weber2a8f9222014-07-24 16:29:04 +00002046MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002047 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002048 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002049 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002050
Jim Grosbach4b905842013-09-20 23:08:21 +00002051static bool isOperator(AsmToken::TokenKind kind) {
2052 switch (kind) {
2053 default:
2054 return false;
2055 case AsmToken::Plus:
2056 case AsmToken::Minus:
2057 case AsmToken::Tilde:
2058 case AsmToken::Slash:
2059 case AsmToken::Star:
2060 case AsmToken::Dot:
2061 case AsmToken::Equal:
2062 case AsmToken::EqualEqual:
2063 case AsmToken::Pipe:
2064 case AsmToken::PipePipe:
2065 case AsmToken::Caret:
2066 case AsmToken::Amp:
2067 case AsmToken::AmpAmp:
2068 case AsmToken::Exclaim:
2069 case AsmToken::ExclaimEqual:
2070 case AsmToken::Percent:
2071 case AsmToken::Less:
2072 case AsmToken::LessEqual:
2073 case AsmToken::LessLess:
2074 case AsmToken::LessGreater:
2075 case AsmToken::Greater:
2076 case AsmToken::GreaterEqual:
2077 case AsmToken::GreaterGreater:
2078 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002079 }
2080}
2081
David Majnemer16252452014-01-29 00:07:39 +00002082namespace {
2083class AsmLexerSkipSpaceRAII {
2084public:
2085 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2086 Lexer.setSkipSpace(SkipSpace);
2087 }
2088
2089 ~AsmLexerSkipSpaceRAII() {
2090 Lexer.setSkipSpace(true);
2091 }
2092
2093private:
2094 AsmLexer &Lexer;
2095};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002096}
David Majnemer16252452014-01-29 00:07:39 +00002097
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002098bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2099
2100 if (Vararg) {
2101 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2102 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002103 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002104 }
2105 return false;
2106 }
2107
Rafael Espindola768b41c2012-06-15 14:02:34 +00002108 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002109 unsigned AddTokens = 0;
2110
David Majnemer16252452014-01-29 00:07:39 +00002111 // Darwin doesn't use spaces to delmit arguments.
2112 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002113
2114 for (;;) {
David Majnemer16252452014-01-29 00:07:39 +00002115 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002116 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002117
David Majnemer91fc4c22014-01-29 18:57:46 +00002118 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
Preston Gurd05500642012-09-19 20:36:12 +00002119 break;
Preston Gurd05500642012-09-19 20:36:12 +00002120
2121 if (Lexer.is(AsmToken::Space)) {
2122 Lex(); // Eat spaces
2123
2124 // Spaces can delimit parameters, but could also be part an expression.
2125 // If the token after a space is an operator, add the token and the next
2126 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002127 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002128 if (isOperator(Lexer.getKind())) {
Preston Gurd05500642012-09-19 20:36:12 +00002129 // Check to see whether the token is used as an operator,
2130 // or part of an identifier
Jordan Rosee8f1eae2013-01-07 19:00:49 +00002131 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd05500642012-09-19 20:36:12 +00002132 if (*NextChar == ' ')
2133 AddTokens = 2;
2134 }
2135
2136 if (!AddTokens && ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002137 break;
2138 }
2139 }
2140 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002141
Jim Grosbach4b905842013-09-20 23:08:21 +00002142 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002143 // to be able to fill in the remaining default parameter values
2144 if (Lexer.is(AsmToken::EndOfStatement))
2145 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002146
2147 // Adjust the current parentheses level.
2148 if (Lexer.is(AsmToken::LParen))
2149 ++ParenLevel;
2150 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2151 --ParenLevel;
2152
2153 // Append the token to the current argument list.
2154 MA.push_back(getTok());
Preston Gurd05500642012-09-19 20:36:12 +00002155 if (AddTokens)
2156 AddTokens--;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002157 Lex();
2158 }
Preston Gurd05500642012-09-19 20:36:12 +00002159
Rafael Espindola768b41c2012-06-15 14:02:34 +00002160 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002161 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002162 return false;
2163}
2164
2165// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002166bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002167 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002168 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002169 bool NamedParametersFound = false;
2170 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002171
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002172 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002173 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002174
Rafael Espindola768b41c2012-06-15 14:02:34 +00002175 // Parse two kinds of macro invocations:
2176 // - macros defined without any parameters accept an arbitrary number of them
2177 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002178 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002179 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2180 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002181 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002182 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002183
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002184 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002185 if (parseIdentifier(FA.Name)) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002186 Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002187 eatToEndOfStatement();
2188 return true;
2189 }
2190
2191 if (!Lexer.is(AsmToken::Equal)) {
2192 TokError("expected '=' after formal parameter identifier");
2193 eatToEndOfStatement();
2194 return true;
2195 }
2196 Lex();
2197
2198 NamedParametersFound = true;
2199 }
2200
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002201 if (NamedParametersFound && FA.Name.empty()) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002202 Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002203 eatToEndOfStatement();
2204 return true;
2205 }
2206
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002207 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2208 if (parseMacroArgument(FA.Value, Vararg))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002209 return true;
2210
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002211 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002212 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002213 unsigned FAI = 0;
2214 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002215 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002216 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002217
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002218 if (FAI >= NParameters) {
Oliver Stannard8b273082014-06-19 15:52:37 +00002219 assert(M && "expected macro to be defined");
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002220 Error(IDLoc,
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002221 "parameter named '" + FA.Name + "' does not exist for macro '" +
Saleem Abdulrasool3f44cd72014-03-17 17:13:57 +00002222 M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002223 return true;
2224 }
2225 PI = FAI;
2226 }
2227
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002228 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002229 if (A.size() <= PI)
2230 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002231 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002232
2233 if (FALocs.size() <= PI)
2234 FALocs.resize(PI + 1);
2235
2236 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002237 }
Jim Grosbach206661622012-07-30 22:44:17 +00002238
Preston Gurd242ed3152012-09-19 20:29:04 +00002239 // At the end of the statement, fill in remaining arguments that have
2240 // default values. If there aren't any, then the next argument is
2241 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002242 if (Lexer.is(AsmToken::EndOfStatement)) {
2243 bool Failure = false;
2244 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2245 if (A[FAI].empty()) {
2246 if (M->Parameters[FAI].Required) {
2247 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2248 "missing value for required parameter "
2249 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2250 Failure = true;
2251 }
2252
2253 if (!M->Parameters[FAI].Value.empty())
2254 A[FAI] = M->Parameters[FAI].Value;
2255 }
2256 }
2257 return Failure;
2258 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002259
2260 if (Lexer.is(AsmToken::Comma))
2261 Lex();
2262 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002263
2264 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002265}
2266
Jim Grosbach4b905842013-09-20 23:08:21 +00002267const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002268 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2269 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002270}
2271
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002272void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2273 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002274}
2275
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002276void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002277
Jim Grosbach4b905842013-09-20 23:08:21 +00002278bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbar43235712010-07-18 18:54:11 +00002279 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2280 // this, although we should protect against infinite loops.
2281 if (ActiveMacros.size() == 20)
2282 return TokError("macros cannot be nested more than 20 levels deep");
2283
Eli Bendersky38274122013-01-14 23:22:36 +00002284 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002285 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002286 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002287
Rafael Espindola1134ab232011-06-05 02:43:45 +00002288 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2289 // to hold the macro body with substitutions.
2290 SmallString<256> Buf;
2291 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002292 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002293
Toma Tabacu217116e2015-04-27 10:50:29 +00002294 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002295 return true;
2296
Eli Bendersky38274122013-01-14 23:22:36 +00002297 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002298 // instantiation.
2299 OS << ".endmacro\n";
2300
Rafael Espindola3560ff22014-08-27 20:03:13 +00002301 std::unique_ptr<MemoryBuffer> Instantiation =
2302 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002303
Daniel Dunbar43235712010-07-18 18:54:11 +00002304 // Create the macro instantiation object and add to the current macro
2305 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002306 MacroInstantiation *MI = new MacroInstantiation(
2307 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002308 ActiveMacros.push_back(MI);
2309
Toma Tabacu217116e2015-04-27 10:50:29 +00002310 ++NumOfMacroInstantiations;
2311
Daniel Dunbar43235712010-07-18 18:54:11 +00002312 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002313 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002314 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002315 Lex();
2316
2317 return false;
2318}
2319
Jim Grosbach4b905842013-09-20 23:08:21 +00002320void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002321 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002322 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002323 Lex();
2324
2325 // Pop the instantiation entry.
2326 delete ActiveMacros.back();
2327 ActiveMacros.pop_back();
2328}
2329
Jim Grosbach4b905842013-09-20 23:08:21 +00002330bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002331 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002332 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002333 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002334 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2335 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002336 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002337
Pete Cooper80d21cb2015-06-22 19:35:57 +00002338 if (!Sym) {
2339 // In the case where we parse an expression starting with a '.', we will
2340 // not generate an error, nor will we create a symbol. In this case we
2341 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002342 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002343 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002344
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002345 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002346 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002347 if (NoDeadStrip)
2348 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2349
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002350 return false;
2351}
2352
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002353/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002354/// ::= identifier
2355/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002356bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002357 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002358 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2359 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002360 // handle this as a context dependent token, instead we detect adjacent tokens
2361 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002362 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2363 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002364
Hans Wennborgce69d772013-10-18 20:46:28 +00002365 // Consume the prefix character, and check for a following identifier.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002366 Lex();
2367 if (Lexer.isNot(AsmToken::Identifier))
2368 return true;
2369
Hans Wennborgce69d772013-10-18 20:46:28 +00002370 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2371 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002372 return true;
2373
2374 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002375 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002376 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002377 Lex();
2378 return false;
2379 }
2380
Jim Grosbach4b905842013-09-20 23:08:21 +00002381 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002382 return true;
2383
Sean Callanan936b0d32010-01-19 21:44:56 +00002384 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002385
Sean Callanan686ed8d2010-01-19 20:22:31 +00002386 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002387
2388 return false;
2389}
2390
Jim Grosbach4b905842013-09-20 23:08:21 +00002391/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002392/// ::= .equ identifier ',' expression
2393/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002394/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002395bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002396 StringRef Name;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002397
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002398 if (parseIdentifier(Name))
Roman Divacky41e6ceb2010-10-28 16:57:58 +00002399 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencer530ce852010-10-09 11:00:50 +00002400
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002401 if (getLexer().isNot(AsmToken::Comma))
Roman Divacky41e6ceb2010-10-28 16:57:58 +00002402 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002403 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002404
Jim Grosbach4b905842013-09-20 23:08:21 +00002405 return parseAssignment(Name, allow_redef, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002406}
2407
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002408bool AsmParser::parseEscapedString(std::string &Data) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002409 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbaref668c12009-08-14 18:19:52 +00002410
2411 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002412 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002413 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2414 if (Str[i] != '\\') {
2415 Data += Str[i];
2416 continue;
2417 }
2418
2419 // Recognize escaped characters. Note that this escape semantics currently
2420 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2421 ++i;
2422 if (i == e)
2423 return TokError("unexpected backslash at end of string");
2424
2425 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002426 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002427 // Consume up to three octal characters.
2428 unsigned Value = 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
Jim Grosbach4b905842013-09-20 23:08:21 +00002434 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002435 ++i;
2436 Value = Value * 8 + (Str[i] - '0');
2437 }
2438 }
2439
2440 if (Value > 255)
2441 return TokError("invalid octal escape sequence (out of range)");
2442
Jim Grosbach4b905842013-09-20 23:08:21 +00002443 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002444 continue;
2445 }
2446
2447 // Otherwise recognize individual escapes.
2448 switch (Str[i]) {
2449 default:
2450 // Just reject invalid escape sequences for now.
2451 return TokError("invalid escape sequence (unrecognized character)");
2452
2453 case 'b': Data += '\b'; break;
2454 case 'f': Data += '\f'; break;
2455 case 'n': Data += '\n'; break;
2456 case 'r': Data += '\r'; break;
2457 case 't': Data += '\t'; break;
2458 case '"': Data += '"'; break;
2459 case '\\': Data += '\\'; break;
2460 }
2461 }
2462
2463 return false;
2464}
2465
Jim Grosbach4b905842013-09-20 23:08:21 +00002466/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002467/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002468bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002469 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002470 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002471
Daniel Dunbara10e5192009-06-24 23:30:00 +00002472 for (;;) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002473 if (getLexer().isNot(AsmToken::String))
Rafael Espindola63760ba2010-10-28 20:02:27 +00002474 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002475
Daniel Dunbaref668c12009-08-14 18:19:52 +00002476 std::string Data;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002477 if (parseEscapedString(Data))
Daniel Dunbaref668c12009-08-14 18:19:52 +00002478 return true;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002479
Rafael Espindola64e1af82013-07-02 15:49:13 +00002480 getStreamer().EmitBytes(Data);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002481 if (ZeroTerminated)
Rafael Espindola64e1af82013-07-02 15:49:13 +00002482 getStreamer().EmitBytes(StringRef("\0", 1));
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002483
Sean Callanan686ed8d2010-01-19 20:22:31 +00002484 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002485
2486 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002487 break;
2488
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002489 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola63760ba2010-10-28 20:02:27 +00002490 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002491 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002492 }
2493 }
2494
Sean Callanan686ed8d2010-01-19 20:22:31 +00002495 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002496 return false;
2497}
2498
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002499/// parseDirectiveReloc
2500/// ::= .reloc expression , identifier [ , expression ]
2501bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2502 const MCExpr *Offset;
2503 const MCExpr *Expr = nullptr;
2504
2505 SMLoc OffsetLoc = Lexer.getTok().getLoc();
2506 if (parseExpression(Offset))
2507 return true;
2508
2509 // We can only deal with constant expressions at the moment.
2510 int64_t OffsetValue;
2511 if (!Offset->evaluateAsAbsolute(OffsetValue))
2512 return Error(OffsetLoc, "expression is not a constant value");
2513
David Majnemerce108422016-01-19 23:05:27 +00002514 if (OffsetValue < 0)
2515 return Error(OffsetLoc, "expression is negative");
2516
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002517 if (Lexer.isNot(AsmToken::Comma))
2518 return TokError("expected comma");
2519 Lexer.Lex();
2520
2521 if (Lexer.isNot(AsmToken::Identifier))
2522 return TokError("expected relocation name");
2523 SMLoc NameLoc = Lexer.getTok().getLoc();
2524 StringRef Name = Lexer.getTok().getIdentifier();
2525 Lexer.Lex();
2526
2527 if (Lexer.is(AsmToken::Comma)) {
2528 Lexer.Lex();
2529 SMLoc ExprLoc = Lexer.getLoc();
2530 if (parseExpression(Expr))
2531 return true;
2532
2533 MCValue Value;
2534 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2535 return Error(ExprLoc, "expression must be relocatable");
2536 }
2537
2538 if (Lexer.isNot(AsmToken::EndOfStatement))
2539 return TokError("unexpected token in .reloc directive");
2540
2541 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2542 return Error(NameLoc, "unknown relocation name");
2543
2544 return false;
2545}
2546
Jim Grosbach4b905842013-09-20 23:08:21 +00002547/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002548/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002549bool AsmParser::parseDirectiveValue(unsigned Size) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002550 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002551 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002552
Daniel Dunbara10e5192009-06-24 23:30:00 +00002553 for (;;) {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002554 const MCExpr *Value;
Jim Grosbach76346c32011-06-29 16:05:14 +00002555 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002556 if (parseExpression(Value))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002557 return true;
2558
Daniel Dunbar6738a2e2010-05-23 18:36:38 +00002559 // Special case constant expressions to match code generator.
Jim Grosbach76346c32011-06-29 16:05:14 +00002560 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2561 assert(Size <= 8 && "Invalid size");
2562 uint64_t IntValue = MCE->getValue();
2563 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2564 return Error(ExprLoc, "literal value out of range for directive");
Rafael Espindola64e1af82013-07-02 15:49:13 +00002565 getStreamer().EmitIntValue(IntValue, Size);
Jim Grosbach76346c32011-06-29 16:05:14 +00002566 } else
Kevin Enderby96918bc2014-04-22 17:27:29 +00002567 getStreamer().EmitValue(Value, Size, ExprLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002568
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002569 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002570 break;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002571
Daniel Dunbara10e5192009-06-24 23:30:00 +00002572 // FIXME: Improve diagnostic.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002573 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002574 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002575 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002576 }
2577 }
2578
Sean Callanan686ed8d2010-01-19 20:22:31 +00002579 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002580 return false;
2581}
2582
David Woodhoused6de0d92014-02-01 16:20:59 +00002583/// ParseDirectiveOctaValue
2584/// ::= .octa [ hexconstant (, hexconstant)* ]
2585bool AsmParser::parseDirectiveOctaValue() {
2586 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2587 checkForValidSection();
2588
2589 for (;;) {
2590 if (Lexer.getKind() == AsmToken::Error)
2591 return true;
2592 if (Lexer.getKind() != AsmToken::Integer &&
2593 Lexer.getKind() != AsmToken::BigNum)
2594 return TokError("unknown token in expression");
2595
2596 SMLoc ExprLoc = getLexer().getLoc();
2597 APInt IntValue = getTok().getAPIntVal();
2598 Lex();
2599
2600 uint64_t hi, lo;
2601 if (IntValue.isIntN(64)) {
2602 hi = 0;
2603 lo = IntValue.getZExtValue();
2604 } else if (IntValue.isIntN(128)) {
David Woodhouse6c9a6f92014-02-01 16:52:33 +00002605 // It might actually have more than 128 bits, but the top ones are zero.
2606 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002607 lo = IntValue.getLoBits(64).getZExtValue();
2608 } else
2609 return Error(ExprLoc, "literal value out of range for directive");
2610
2611 if (MAI.isLittleEndian()) {
2612 getStreamer().EmitIntValue(lo, 8);
2613 getStreamer().EmitIntValue(hi, 8);
2614 } else {
2615 getStreamer().EmitIntValue(hi, 8);
2616 getStreamer().EmitIntValue(lo, 8);
2617 }
2618
2619 if (getLexer().is(AsmToken::EndOfStatement))
2620 break;
2621
2622 // FIXME: Improve diagnostic.
2623 if (getLexer().isNot(AsmToken::Comma))
2624 return TokError("unexpected token in directive");
2625 Lex();
2626 }
2627 }
2628
2629 Lex();
2630 return false;
2631}
2632
Jim Grosbach4b905842013-09-20 23:08:21 +00002633/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00002634/// ::= (.single | .double) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002635bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
Daniel Dunbar2af16532010-09-24 01:59:56 +00002636 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002637 checkForValidSection();
Daniel Dunbar2af16532010-09-24 01:59:56 +00002638
2639 for (;;) {
2640 // We don't truly support arithmetic on floating point expressions, so we
2641 // have to manually parse unary prefixes.
2642 bool IsNeg = false;
2643 if (getLexer().is(AsmToken::Minus)) {
2644 Lex();
2645 IsNeg = true;
2646 } else if (getLexer().is(AsmToken::Plus))
2647 Lex();
2648
Michael J. Spencer530ce852010-10-09 11:00:50 +00002649 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby5bbe9572011-03-29 21:11:52 +00002650 getLexer().isNot(AsmToken::Real) &&
2651 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbar2af16532010-09-24 01:59:56 +00002652 return TokError("unexpected token in directive");
2653
2654 // Convert to an APFloat.
2655 APFloat Value(Semantics);
Kevin Enderby5bbe9572011-03-29 21:11:52 +00002656 StringRef IDVal = getTok().getString();
2657 if (getLexer().is(AsmToken::Identifier)) {
2658 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2659 Value = APFloat::getInf(Semantics);
2660 else if (!IDVal.compare_lower("nan"))
2661 Value = APFloat::getNaN(Semantics, false, ~0);
2662 else
2663 return TokError("invalid floating point literal");
2664 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Jim Grosbach4b905842013-09-20 23:08:21 +00002665 APFloat::opInvalidOp)
Daniel Dunbar2af16532010-09-24 01:59:56 +00002666 return TokError("invalid floating point literal");
2667 if (IsNeg)
2668 Value.changeSign();
2669
2670 // Consume the numeric token.
2671 Lex();
2672
2673 // Emit the value as an integer.
2674 APInt AsInt = Value.bitcastToAPInt();
2675 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
Rafael Espindola64e1af82013-07-02 15:49:13 +00002676 AsInt.getBitWidth() / 8);
Daniel Dunbar2af16532010-09-24 01:59:56 +00002677
2678 if (getLexer().is(AsmToken::EndOfStatement))
2679 break;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002680
Daniel Dunbar2af16532010-09-24 01:59:56 +00002681 if (getLexer().isNot(AsmToken::Comma))
2682 return TokError("unexpected token in directive");
2683 Lex();
2684 }
2685 }
2686
2687 Lex();
2688 return false;
2689}
2690
Jim Grosbach4b905842013-09-20 23:08:21 +00002691/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00002692/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002693bool AsmParser::parseDirectiveZero() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002694 checkForValidSection();
Rafael Espindola922e3f42010-09-16 15:03:59 +00002695
2696 int64_t NumBytes;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002697 if (parseAbsoluteExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00002698 return true;
2699
Rafael Espindolab91bac62010-10-05 19:42:57 +00002700 int64_t Val = 0;
2701 if (getLexer().is(AsmToken::Comma)) {
2702 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002703 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00002704 return true;
2705 }
2706
Rafael Espindola922e3f42010-09-16 15:03:59 +00002707 if (getLexer().isNot(AsmToken::EndOfStatement))
2708 return TokError("unexpected token in '.zero' directive");
2709
2710 Lex();
2711
Rafael Espindola64e1af82013-07-02 15:49:13 +00002712 getStreamer().EmitFill(NumBytes, Val);
Rafael Espindola922e3f42010-09-16 15:03:59 +00002713
2714 return false;
2715}
2716
Jim Grosbach4b905842013-09-20 23:08:21 +00002717/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00002718/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002719bool AsmParser::parseDirectiveFill() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002720 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002721
David Majnemer522d3db2014-02-01 07:19:38 +00002722 SMLoc RepeatLoc = getLexer().getLoc();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002723 int64_t NumValues;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002724 if (parseAbsoluteExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002725 return true;
2726
David Majnemer522d3db2014-02-01 07:19:38 +00002727 if (NumValues < 0) {
2728 Warning(RepeatLoc,
2729 "'.fill' directive with negative repeat count has no effect");
2730 NumValues = 0;
2731 }
2732
Roman Divackye33098f2013-09-24 17:44:41 +00002733 int64_t FillSize = 1;
2734 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002735
David Majnemer522d3db2014-02-01 07:19:38 +00002736 SMLoc SizeLoc, ExprLoc;
Roman Divackye33098f2013-09-24 17:44:41 +00002737 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2738 if (getLexer().isNot(AsmToken::Comma))
2739 return TokError("unexpected token in '.fill' directive");
2740 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002741
David Majnemer522d3db2014-02-01 07:19:38 +00002742 SizeLoc = getLexer().getLoc();
Roman Divackye33098f2013-09-24 17:44:41 +00002743 if (parseAbsoluteExpression(FillSize))
2744 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002745
Roman Divackye33098f2013-09-24 17:44:41 +00002746 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2747 if (getLexer().isNot(AsmToken::Comma))
2748 return TokError("unexpected token in '.fill' directive");
2749 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002750
David Majnemer522d3db2014-02-01 07:19:38 +00002751 ExprLoc = getLexer().getLoc();
Roman Divackye33098f2013-09-24 17:44:41 +00002752 if (parseAbsoluteExpression(FillExpr))
2753 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002754
Roman Divackye33098f2013-09-24 17:44:41 +00002755 if (getLexer().isNot(AsmToken::EndOfStatement))
2756 return TokError("unexpected token in '.fill' directive");
2757
2758 Lex();
2759 }
2760 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002761
David Majnemer522d3db2014-02-01 07:19:38 +00002762 if (FillSize < 0) {
2763 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2764 NumValues = 0;
2765 }
2766 if (FillSize > 8) {
2767 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2768 FillSize = 8;
2769 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002770
David Majnemer522d3db2014-02-01 07:19:38 +00002771 if (!isUInt<32>(FillExpr) && FillSize > 4)
2772 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2773
Alexey Samsonov1b0713c2014-09-02 17:25:29 +00002774 if (NumValues > 0) {
2775 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2776 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2777 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2778 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2779 if (NonZeroFillSize < FillSize)
2780 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2781 }
David Majnemer522d3db2014-02-01 07:19:38 +00002782 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002783
2784 return false;
2785}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002786
Jim Grosbach4b905842013-09-20 23:08:21 +00002787/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002788/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002789bool AsmParser::parseDirectiveOrg() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002790 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002791
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002792 const MCExpr *Offset;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002793 if (parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002794 return true;
2795
2796 // Parse optional fill expression.
2797 int64_t FillExpr = 0;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002798 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2799 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002800 return TokError("unexpected token in '.org' directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002801 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00002802
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002803 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002804 return true;
2805
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002806 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002807 return TokError("unexpected token in '.org' directive");
2808 }
2809
Sean Callanan686ed8d2010-01-19 20:22:31 +00002810 Lex();
Rafael Espindola7ae65d82015-11-04 23:59:18 +00002811 getStreamer().emitValueToOffset(Offset, FillExpr);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002812 return false;
2813}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002814
Jim Grosbach4b905842013-09-20 23:08:21 +00002815/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002816/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00002817bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002818 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002819
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002820 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002821 int64_t Alignment;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002822 if (parseAbsoluteExpression(Alignment))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002823 return true;
2824
2825 SMLoc MaxBytesLoc;
2826 bool HasFillExpr = false;
2827 int64_t FillExpr = 0;
2828 int64_t MaxBytesToFill = 0;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002829 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2830 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002831 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002832 Lex();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002833
2834 // The fill expression can be omitted while specifying a maximum number of
2835 // alignment bytes, e.g:
2836 // .align 3,,4
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002837 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002838 HasFillExpr = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002839 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002840 return true;
2841 }
2842
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002843 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2844 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002845 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002846 Lex();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002847
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002848 MaxBytesLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002849 if (parseAbsoluteExpression(MaxBytesToFill))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002850 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002851
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002852 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002853 return TokError("unexpected token in directive");
2854 }
2855 }
2856
Sean Callanan686ed8d2010-01-19 20:22:31 +00002857 Lex();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002858
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002859 if (!HasFillExpr)
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002860 FillExpr = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002861
2862 // Compute alignment in bytes.
2863 if (IsPow2) {
2864 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002865 if (Alignment >= 32) {
2866 Error(AlignmentLoc, "invalid alignment value");
2867 Alignment = 31;
2868 }
2869
Benjamin Kramer63951ad2009-09-06 09:35:10 +00002870 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00002871 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00002872 // Reject alignments that aren't either a power of two or zero,
2873 // for gas compatibility. Alignment of zero is silently rounded
2874 // up to one.
2875 if (Alignment == 0)
2876 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00002877 if (!isPowerOf2_64(Alignment))
2878 Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002879 }
2880
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002881 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002882 if (MaxBytesLoc.isValid()) {
2883 if (MaxBytesToFill < 1) {
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002884 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00002885 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00002886 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002887 }
2888
2889 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00002890 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00002891 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002892 MaxBytesToFill = 0;
2893 }
2894 }
2895
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002896 // Check whether we should use optimal code alignment for this .align
2897 // directive.
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00002898 const MCSection *Section = getStreamer().getCurrentSection().first;
2899 assert(Section && "must have section to emit alignment");
2900 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002901 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2902 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002903 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002904 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00002905 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00002906 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2907 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002908 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002909
2910 return false;
2911}
2912
Jim Grosbach4b905842013-09-20 23:08:21 +00002913/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00002914/// ::= .file [number] filename
2915/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00002916bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00002917 // FIXME: I'm not sure what this is.
2918 int64_t FileNumber = -1;
2919 SMLoc FileNumberLoc = getLexer().getLoc();
2920 if (getLexer().is(AsmToken::Integer)) {
2921 FileNumber = getTok().getIntVal();
2922 Lex();
2923
2924 if (FileNumber < 1)
2925 return TokError("file number less than one");
2926 }
2927
2928 if (getLexer().isNot(AsmToken::String))
2929 return TokError("unexpected token in '.file' directive");
2930
2931 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002932 // Allow the strings to have escaped octal character sequence.
2933 std::string Path = getTok().getString();
2934 if (parseEscapedString(Path))
2935 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00002936 Lex();
2937
2938 StringRef Directory;
2939 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002940 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00002941 if (getLexer().is(AsmToken::String)) {
2942 if (FileNumber == -1)
2943 return TokError("explicit path specified, but no file number");
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002944 if (parseEscapedString(FilenameData))
2945 return true;
2946 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00002947 Directory = Path;
2948 Lex();
2949 } else {
2950 Filename = Path;
2951 }
2952
2953 if (getLexer().isNot(AsmToken::EndOfStatement))
2954 return TokError("unexpected token in '.file' directive");
2955
2956 if (FileNumber == -1)
2957 getStreamer().EmitFileDirective(Filename);
2958 else {
David Blaikiedc3f01e2015-03-09 01:57:13 +00002959 if (getContext().getGenDwarfForAssembly())
Jim Grosbach4b905842013-09-20 23:08:21 +00002960 Error(DirectiveLoc,
2961 "input can't have .file dwarf directives when -g is "
2962 "used to generate dwarf debug info for assembly code");
Eli Bendersky17233942013-01-15 22:59:42 +00002963
David Blaikiec714ef42014-03-17 01:52:11 +00002964 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2965 0)
Eli Bendersky17233942013-01-15 22:59:42 +00002966 Error(FileNumberLoc, "file number already allocated");
2967 }
2968
2969 return false;
2970}
2971
Jim Grosbach4b905842013-09-20 23:08:21 +00002972/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00002973/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00002974bool AsmParser::parseDirectiveLine() {
Eli Bendersky17233942013-01-15 22:59:42 +00002975 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2976 if (getLexer().isNot(AsmToken::Integer))
2977 return TokError("unexpected token in '.line' directive");
2978
2979 int64_t LineNumber = getTok().getIntVal();
Jim Grosbach4b905842013-09-20 23:08:21 +00002980 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00002981 Lex();
2982
2983 // FIXME: Do something with the .line.
2984 }
2985
2986 if (getLexer().isNot(AsmToken::EndOfStatement))
2987 return TokError("unexpected token in '.line' directive");
2988
2989 return false;
2990}
2991
Jim Grosbach4b905842013-09-20 23:08:21 +00002992/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00002993/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2994/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2995/// The first number is a file number, must have been previously assigned with
2996/// a .file directive, the second number is the line number and optionally the
2997/// third number is a column position (zero if not specified). The remaining
2998/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00002999bool AsmParser::parseDirectiveLoc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003000 if (getLexer().isNot(AsmToken::Integer))
3001 return TokError("unexpected token in '.loc' directive");
3002 int64_t FileNumber = getTok().getIntVal();
3003 if (FileNumber < 1)
3004 return TokError("file number less than one in '.loc' directive");
3005 if (!getContext().isValidDwarfFileNumber(FileNumber))
3006 return TokError("unassigned file number in '.loc' directive");
3007 Lex();
3008
3009 int64_t LineNumber = 0;
3010 if (getLexer().is(AsmToken::Integer)) {
3011 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003012 if (LineNumber < 0)
3013 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003014 Lex();
3015 }
3016
3017 int64_t ColumnPos = 0;
3018 if (getLexer().is(AsmToken::Integer)) {
3019 ColumnPos = getTok().getIntVal();
3020 if (ColumnPos < 0)
3021 return TokError("column position less than zero in '.loc' directive");
3022 Lex();
3023 }
3024
3025 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3026 unsigned Isa = 0;
3027 int64_t Discriminator = 0;
3028 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3029 for (;;) {
3030 if (getLexer().is(AsmToken::EndOfStatement))
3031 break;
3032
3033 StringRef Name;
3034 SMLoc Loc = getTok().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003035 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003036 return TokError("unexpected token in '.loc' directive");
3037
3038 if (Name == "basic_block")
3039 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3040 else if (Name == "prologue_end")
3041 Flags |= DWARF2_FLAG_PROLOGUE_END;
3042 else if (Name == "epilogue_begin")
3043 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3044 else if (Name == "is_stmt") {
3045 Loc = getTok().getLoc();
3046 const MCExpr *Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003047 if (parseExpression(Value))
Eli Bendersky17233942013-01-15 22:59:42 +00003048 return true;
3049 // The expression must be the constant 0 or 1.
3050 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3051 int Value = MCE->getValue();
3052 if (Value == 0)
3053 Flags &= ~DWARF2_FLAG_IS_STMT;
3054 else if (Value == 1)
3055 Flags |= DWARF2_FLAG_IS_STMT;
3056 else
3057 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003058 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003059 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3060 }
Craig Topperf15655b2013-04-22 04:22:40 +00003061 } else if (Name == "isa") {
Eli Bendersky17233942013-01-15 22:59:42 +00003062 Loc = getTok().getLoc();
3063 const MCExpr *Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003064 if (parseExpression(Value))
Eli Bendersky17233942013-01-15 22:59:42 +00003065 return true;
3066 // The expression must be a constant greater or equal to 0.
3067 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3068 int Value = MCE->getValue();
3069 if (Value < 0)
3070 return Error(Loc, "isa number less than zero");
3071 Isa = Value;
Craig Topperf15655b2013-04-22 04:22:40 +00003072 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003073 return Error(Loc, "isa number not a constant value");
3074 }
Craig Topperf15655b2013-04-22 04:22:40 +00003075 } else if (Name == "discriminator") {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003076 if (parseAbsoluteExpression(Discriminator))
Eli Bendersky17233942013-01-15 22:59:42 +00003077 return true;
Craig Topperf15655b2013-04-22 04:22:40 +00003078 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003079 return Error(Loc, "unknown sub-directive in '.loc' directive");
3080 }
3081
3082 if (getLexer().is(AsmToken::EndOfStatement))
3083 break;
3084 }
3085 }
3086
3087 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3088 Isa, Discriminator, StringRef());
3089
3090 return false;
3091}
3092
Jim Grosbach4b905842013-09-20 23:08:21 +00003093/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003094/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003095bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003096 return TokError("unsupported directive '.stabs'");
3097}
3098
Reid Kleckner2214ed82016-01-29 00:49:42 +00003099/// parseDirectiveCVFile
3100/// ::= .cv_file number filename
3101bool AsmParser::parseDirectiveCVFile() {
3102 SMLoc FileNumberLoc = getLexer().getLoc();
3103 if (getLexer().isNot(AsmToken::Integer))
3104 return TokError("expected file number in '.cv_file' directive");
3105
3106 int64_t FileNumber = getTok().getIntVal();
3107 Lex();
3108
3109 if (FileNumber < 1)
3110 return TokError("file number less than one");
3111
3112 if (getLexer().isNot(AsmToken::String))
3113 return TokError("unexpected token in '.cv_file' directive");
3114
3115 // Usually the directory and filename together, otherwise just the directory.
3116 // Allow the strings to have escaped octal character sequence.
3117 std::string Filename;
3118 if (parseEscapedString(Filename))
3119 return true;
3120 Lex();
3121
3122 if (getLexer().isNot(AsmToken::EndOfStatement))
3123 return TokError("unexpected token in '.cv_file' directive");
3124
3125 if (getStreamer().EmitCVFileDirective(FileNumber, Filename) == 0)
3126 Error(FileNumberLoc, "file number already allocated");
3127
3128 return false;
3129}
3130
3131/// parseDirectiveCVLoc
3132/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3133/// [is_stmt VALUE]
3134/// The first number is a file number, must have been previously assigned with
3135/// a .file directive, the second number is the line number and optionally the
3136/// third number is a column position (zero if not specified). The remaining
3137/// optional items are .loc sub-directives.
3138bool AsmParser::parseDirectiveCVLoc() {
3139 if (getLexer().isNot(AsmToken::Integer))
3140 return TokError("unexpected token in '.cv_loc' directive");
3141
3142 int64_t FunctionId = getTok().getIntVal();
3143 if (FunctionId < 0)
3144 return TokError("function id less than zero in '.cv_loc' directive");
3145 Lex();
3146
3147 int64_t FileNumber = getTok().getIntVal();
3148 if (FileNumber < 1)
3149 return TokError("file number less than one in '.cv_loc' directive");
3150 if (!getContext().isValidCVFileNumber(FileNumber))
3151 return TokError("unassigned file number in '.cv_loc' directive");
3152 Lex();
3153
3154 int64_t LineNumber = 0;
3155 if (getLexer().is(AsmToken::Integer)) {
3156 LineNumber = getTok().getIntVal();
3157 if (LineNumber < 0)
3158 return TokError("line number less than zero in '.cv_loc' directive");
3159 Lex();
3160 }
3161
3162 int64_t ColumnPos = 0;
3163 if (getLexer().is(AsmToken::Integer)) {
3164 ColumnPos = getTok().getIntVal();
3165 if (ColumnPos < 0)
3166 return TokError("column position less than zero in '.cv_loc' directive");
3167 Lex();
3168 }
3169
3170 bool PrologueEnd = false;
3171 uint64_t IsStmt = 0;
3172 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3173 StringRef Name;
3174 SMLoc Loc = getTok().getLoc();
3175 if (parseIdentifier(Name))
3176 return TokError("unexpected token in '.cv_loc' directive");
3177
3178 if (Name == "prologue_end")
3179 PrologueEnd = true;
3180 else if (Name == "is_stmt") {
3181 Loc = getTok().getLoc();
3182 const MCExpr *Value;
3183 if (parseExpression(Value))
3184 return true;
3185 // The expression must be the constant 0 or 1.
3186 IsStmt = ~0ULL;
3187 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3188 IsStmt = MCE->getValue();
3189
3190 if (IsStmt > 1)
3191 return Error(Loc, "is_stmt value not 0 or 1");
3192 } else {
3193 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3194 }
3195 }
3196
3197 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
3198 ColumnPos, PrologueEnd, IsStmt, StringRef());
3199 return false;
3200}
3201
3202/// parseDirectiveCVLinetable
3203/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3204bool AsmParser::parseDirectiveCVLinetable() {
3205 int64_t FunctionId = getTok().getIntVal();
3206 if (FunctionId < 0)
3207 return TokError("function id less than zero in '.cv_linetable' directive");
3208 Lex();
3209
3210 if (Lexer.isNot(AsmToken::Comma))
3211 return TokError("unexpected token in '.cv_linetable' directive");
3212 Lex();
3213
3214 SMLoc Loc = getLexer().getLoc();
3215 StringRef FnStartName;
3216 if (parseIdentifier(FnStartName))
3217 return Error(Loc, "expected identifier in directive");
3218
3219 if (Lexer.isNot(AsmToken::Comma))
3220 return TokError("unexpected token in '.cv_linetable' directive");
3221 Lex();
3222
3223 Loc = getLexer().getLoc();
3224 StringRef FnEndName;
3225 if (parseIdentifier(FnEndName))
3226 return Error(Loc, "expected identifier in directive");
3227
3228 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3229 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3230
3231 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3232 return false;
3233}
3234
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003235/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003236/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003237/// ("contains" SecondaryFunctionId+)?
3238bool AsmParser::parseDirectiveCVInlineLinetable() {
3239 int64_t PrimaryFunctionId = getTok().getIntVal();
3240 if (PrimaryFunctionId < 0)
3241 return TokError(
3242 "function id less than zero in '.cv_inline_linetable' directive");
3243 Lex();
3244
3245 int64_t SourceFileId = getTok().getIntVal();
3246 if (SourceFileId <= 0)
3247 return TokError(
3248 "File id less than zero in '.cv_inline_linetable' directive");
3249 Lex();
3250
3251 int64_t SourceLineNum = getTok().getIntVal();
3252 if (SourceLineNum < 0)
3253 return TokError(
3254 "Line number less than zero in '.cv_inline_linetable' directive");
3255 Lex();
3256
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003257 SMLoc Loc = getLexer().getLoc();
3258 StringRef FnStartName;
3259 if (parseIdentifier(FnStartName))
3260 return Error(Loc, "expected identifier in directive");
3261 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3262
David Majnemerc9911f22016-02-02 19:22:34 +00003263 Loc = getLexer().getLoc();
3264 StringRef FnEndName;
3265 if (parseIdentifier(FnEndName))
3266 return Error(Loc, "expected identifier in directive");
3267 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3268
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003269 SmallVector<unsigned, 8> SecondaryFunctionIds;
3270 if (getLexer().is(AsmToken::Identifier)) {
3271 if (getTok().getIdentifier() != "contains")
3272 return TokError(
3273 "unexpected identifier in '.cv_inline_linetable' directive");
3274 Lex();
3275
3276 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3277 int64_t SecondaryFunctionId = getTok().getIntVal();
3278 if (SecondaryFunctionId < 0)
3279 return TokError(
3280 "function id less than zero in '.cv_inline_linetable' directive");
3281 Lex();
3282
3283 SecondaryFunctionIds.push_back(SecondaryFunctionId);
3284 }
3285 }
3286
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003287 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3288 SourceLineNum, FnStartSym,
David Majnemerc9911f22016-02-02 19:22:34 +00003289 FnEndSym, SecondaryFunctionIds);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003290 return false;
3291}
3292
David Majnemer408b5e62016-02-05 01:55:49 +00003293/// parseDirectiveCVDefRange
3294/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3295bool AsmParser::parseDirectiveCVDefRange() {
3296 SMLoc Loc;
3297 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3298 while (getLexer().is(AsmToken::Identifier)) {
3299 Loc = getLexer().getLoc();
3300 StringRef GapStartName;
3301 if (parseIdentifier(GapStartName))
3302 return Error(Loc, "expected identifier in directive");
3303 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3304
3305 Loc = getLexer().getLoc();
3306 StringRef GapEndName;
3307 if (parseIdentifier(GapEndName))
3308 return Error(Loc, "expected identifier in directive");
3309 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3310
3311 Ranges.push_back({GapStartSym, GapEndSym});
3312 }
3313
3314 if (getLexer().isNot(AsmToken::Comma))
3315 return TokError("unexpected token in directive");
3316 Lex();
3317
3318 std::string FixedSizePortion;
3319 if (parseEscapedString(FixedSizePortion))
3320 return true;
3321 Lex();
3322
3323 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3324 return false;
3325}
3326
Reid Kleckner2214ed82016-01-29 00:49:42 +00003327/// parseDirectiveCVStringTable
3328/// ::= .cv_stringtable
3329bool AsmParser::parseDirectiveCVStringTable() {
3330 getStreamer().EmitCVStringTableDirective();
3331 return false;
3332}
3333
3334/// parseDirectiveCVFileChecksums
3335/// ::= .cv_filechecksums
3336bool AsmParser::parseDirectiveCVFileChecksums() {
3337 getStreamer().EmitCVFileChecksumsDirective();
3338 return false;
3339}
3340
Jim Grosbach4b905842013-09-20 23:08:21 +00003341/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003342/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003343bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003344 StringRef Name;
3345 bool EH = false;
3346 bool Debug = false;
3347
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003348 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003349 return TokError("Expected an identifier");
3350
3351 if (Name == ".eh_frame")
3352 EH = true;
3353 else if (Name == ".debug_frame")
3354 Debug = true;
3355
3356 if (getLexer().is(AsmToken::Comma)) {
3357 Lex();
3358
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003359 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003360 return TokError("Expected an identifier");
3361
3362 if (Name == ".eh_frame")
3363 EH = true;
3364 else if (Name == ".debug_frame")
3365 Debug = true;
3366 }
3367
3368 getStreamer().EmitCFISections(EH, Debug);
3369 return false;
3370}
3371
Jim Grosbach4b905842013-09-20 23:08:21 +00003372/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003373/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003374bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003375 StringRef Simple;
3376 if (getLexer().isNot(AsmToken::EndOfStatement))
3377 if (parseIdentifier(Simple) || Simple != "simple")
3378 return TokError("unexpected token in .cfi_startproc directive");
3379
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003380 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003381 return false;
3382}
3383
Jim Grosbach4b905842013-09-20 23:08:21 +00003384/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003385/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003386bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003387 getStreamer().EmitCFIEndProc();
3388 return false;
3389}
3390
Jim Grosbach4b905842013-09-20 23:08:21 +00003391/// \brief parse register name or number.
3392bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003393 SMLoc DirectiveLoc) {
3394 unsigned RegNo;
3395
3396 if (getLexer().isNot(AsmToken::Integer)) {
3397 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3398 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003399 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003400 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003401 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003402
3403 return false;
3404}
3405
Jim Grosbach4b905842013-09-20 23:08:21 +00003406/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003407/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003408bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003409 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003410 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003411 return true;
3412
3413 if (getLexer().isNot(AsmToken::Comma))
3414 return TokError("unexpected token in directive");
3415 Lex();
3416
3417 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003418 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003419 return true;
3420
3421 getStreamer().EmitCFIDefCfa(Register, Offset);
3422 return false;
3423}
3424
Jim Grosbach4b905842013-09-20 23:08:21 +00003425/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003426/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003427bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003428 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003429 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003430 return true;
3431
3432 getStreamer().EmitCFIDefCfaOffset(Offset);
3433 return false;
3434}
3435
Jim Grosbach4b905842013-09-20 23:08:21 +00003436/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003437/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003438bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003439 int64_t Register1 = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003440 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003441 return true;
3442
3443 if (getLexer().isNot(AsmToken::Comma))
3444 return TokError("unexpected token in directive");
3445 Lex();
3446
3447 int64_t Register2 = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003448 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003449 return true;
3450
3451 getStreamer().EmitCFIRegister(Register1, Register2);
3452 return false;
3453}
3454
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003455/// parseDirectiveCFIWindowSave
3456/// ::= .cfi_window_save
3457bool AsmParser::parseDirectiveCFIWindowSave() {
3458 getStreamer().EmitCFIWindowSave();
3459 return false;
3460}
3461
Jim Grosbach4b905842013-09-20 23:08:21 +00003462/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003463/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003464bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003465 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003466 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003467 return true;
3468
3469 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3470 return false;
3471}
3472
Jim Grosbach4b905842013-09-20 23:08:21 +00003473/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003474/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003475bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003476 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003477 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003478 return true;
3479
3480 getStreamer().EmitCFIDefCfaRegister(Register);
3481 return false;
3482}
3483
Jim Grosbach4b905842013-09-20 23:08:21 +00003484/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003485/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003486bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003487 int64_t Register = 0;
3488 int64_t Offset = 0;
3489
Jim Grosbach4b905842013-09-20 23:08:21 +00003490 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003491 return true;
3492
3493 if (getLexer().isNot(AsmToken::Comma))
3494 return TokError("unexpected token in directive");
3495 Lex();
3496
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003497 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003498 return true;
3499
3500 getStreamer().EmitCFIOffset(Register, Offset);
3501 return false;
3502}
3503
Jim Grosbach4b905842013-09-20 23:08:21 +00003504/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003505/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003506bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003507 int64_t Register = 0;
3508
Jim Grosbach4b905842013-09-20 23:08:21 +00003509 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003510 return true;
3511
3512 if (getLexer().isNot(AsmToken::Comma))
3513 return TokError("unexpected token in directive");
3514 Lex();
3515
3516 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003517 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003518 return true;
3519
3520 getStreamer().EmitCFIRelOffset(Register, Offset);
3521 return false;
3522}
3523
3524static bool isValidEncoding(int64_t Encoding) {
3525 if (Encoding & ~0xff)
3526 return false;
3527
3528 if (Encoding == dwarf::DW_EH_PE_omit)
3529 return true;
3530
3531 const unsigned Format = Encoding & 0xf;
3532 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3533 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3534 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3535 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3536 return false;
3537
3538 const unsigned Application = Encoding & 0x70;
3539 if (Application != dwarf::DW_EH_PE_absptr &&
3540 Application != dwarf::DW_EH_PE_pcrel)
3541 return false;
3542
3543 return true;
3544}
3545
Jim Grosbach4b905842013-09-20 23:08:21 +00003546/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003547/// IsPersonality true for cfi_personality, false for cfi_lsda
3548/// ::= .cfi_personality encoding, [symbol_name]
3549/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003550bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003551 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003552 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003553 return true;
3554 if (Encoding == dwarf::DW_EH_PE_omit)
3555 return false;
3556
3557 if (!isValidEncoding(Encoding))
3558 return TokError("unsupported encoding.");
3559
3560 if (getLexer().isNot(AsmToken::Comma))
3561 return TokError("unexpected token in directive");
3562 Lex();
3563
3564 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003565 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003566 return TokError("expected identifier in directive");
3567
Jim Grosbach6f482002015-05-18 18:43:14 +00003568 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003569
3570 if (IsPersonality)
3571 getStreamer().EmitCFIPersonality(Sym, Encoding);
3572 else
3573 getStreamer().EmitCFILsda(Sym, Encoding);
3574 return false;
3575}
3576
Jim Grosbach4b905842013-09-20 23:08:21 +00003577/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00003578/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003579bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003580 getStreamer().EmitCFIRememberState();
3581 return false;
3582}
3583
Jim Grosbach4b905842013-09-20 23:08:21 +00003584/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00003585/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003586bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003587 getStreamer().EmitCFIRestoreState();
3588 return false;
3589}
3590
Jim Grosbach4b905842013-09-20 23:08:21 +00003591/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00003592/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00003593bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003594 int64_t Register = 0;
3595
Jim Grosbach4b905842013-09-20 23:08:21 +00003596 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003597 return true;
3598
3599 getStreamer().EmitCFISameValue(Register);
3600 return false;
3601}
3602
Jim Grosbach4b905842013-09-20 23:08:21 +00003603/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00003604/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00003605bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003606 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003607 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003608 return true;
3609
3610 getStreamer().EmitCFIRestore(Register);
3611 return false;
3612}
3613
Jim Grosbach4b905842013-09-20 23:08:21 +00003614/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00003615/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003616bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00003617 std::string Values;
3618 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003619 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003620 return true;
3621
3622 Values.push_back((uint8_t)CurrValue);
3623
3624 while (getLexer().is(AsmToken::Comma)) {
3625 Lex();
3626
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003627 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003628 return true;
3629
3630 Values.push_back((uint8_t)CurrValue);
3631 }
3632
3633 getStreamer().EmitCFIEscape(Values);
3634 return false;
3635}
3636
Jim Grosbach4b905842013-09-20 23:08:21 +00003637/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00003638/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00003639bool AsmParser::parseDirectiveCFISignalFrame() {
Eli Bendersky17233942013-01-15 22:59:42 +00003640 if (getLexer().isNot(AsmToken::EndOfStatement))
3641 return Error(getLexer().getLoc(),
3642 "unexpected token in '.cfi_signal_frame'");
3643
3644 getStreamer().EmitCFISignalFrame();
3645 return false;
3646}
3647
Jim Grosbach4b905842013-09-20 23:08:21 +00003648/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00003649/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00003650bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003651 int64_t Register = 0;
3652
Jim Grosbach4b905842013-09-20 23:08:21 +00003653 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003654 return true;
3655
3656 getStreamer().EmitCFIUndefined(Register);
3657 return false;
3658}
3659
Jim Grosbach4b905842013-09-20 23:08:21 +00003660/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00003661/// ::= .macros_on
3662/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00003663bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00003664 if (getLexer().isNot(AsmToken::EndOfStatement))
3665 return Error(getLexer().getLoc(),
3666 "unexpected token in '" + Directive + "' directive");
3667
Jim Grosbach4b905842013-09-20 23:08:21 +00003668 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00003669 return false;
3670}
3671
Jim Grosbach4b905842013-09-20 23:08:21 +00003672/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003673/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00003674bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003675 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003676 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003677 return TokError("expected identifier in '.macro' directive");
3678
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003679 if (getLexer().is(AsmToken::Comma))
3680 Lex();
3681
Eli Bendersky17233942013-01-15 22:59:42 +00003682 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00003683 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003684
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003685 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003686 return Error(Lexer.getLoc(),
3687 "Vararg parameter '" + Parameters.back().Name +
3688 "' should be last one in the list of parameters.");
3689
David Majnemer91fc4c22014-01-29 18:57:46 +00003690 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003691 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00003692 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003693
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003694 if (Lexer.is(AsmToken::Colon)) {
3695 Lex(); // consume ':'
3696
3697 SMLoc QualLoc;
3698 StringRef Qualifier;
3699
3700 QualLoc = Lexer.getLoc();
3701 if (parseIdentifier(Qualifier))
3702 return Error(QualLoc, "missing parameter qualifier for "
3703 "'" + Parameter.Name + "' in macro '" + Name + "'");
3704
3705 if (Qualifier == "req")
3706 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00003707 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003708 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003709 else
3710 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3711 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3712 }
3713
David Majnemer91fc4c22014-01-29 18:57:46 +00003714 if (getLexer().is(AsmToken::Equal)) {
3715 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003716
3717 SMLoc ParamLoc;
3718
3719 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003720 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00003721 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003722
3723 if (Parameter.Required)
3724 Warning(ParamLoc, "pointless default value for required parameter "
3725 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00003726 }
David Majnemer91fc4c22014-01-29 18:57:46 +00003727
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003728 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00003729
3730 if (getLexer().is(AsmToken::Comma))
3731 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003732 }
3733
3734 // Eat the end of statement.
3735 Lex();
3736
3737 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003738 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003739
3740 // Lex the macro definition.
3741 for (;;) {
3742 // Check whether we have reached the end of the file.
3743 if (getLexer().is(AsmToken::Eof))
3744 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3745
3746 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003747 if (getLexer().is(AsmToken::Identifier)) {
3748 if (getTok().getIdentifier() == ".endm" ||
3749 getTok().getIdentifier() == ".endmacro") {
3750 if (MacroDepth == 0) { // Outermost macro.
3751 EndToken = getTok();
3752 Lex();
3753 if (getLexer().isNot(AsmToken::EndOfStatement))
3754 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3755 "' directive");
3756 break;
3757 } else {
3758 // Otherwise we just found the end of an inner macro.
3759 --MacroDepth;
3760 }
3761 } else if (getTok().getIdentifier() == ".macro") {
3762 // We allow nested macros. Those aren't instantiated until the outermost
3763 // macro is expanded so just ignore them for now.
3764 ++MacroDepth;
3765 }
Eli Bendersky17233942013-01-15 22:59:42 +00003766 }
3767
3768 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003769 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00003770 }
3771
Jim Grosbach4b905842013-09-20 23:08:21 +00003772 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00003773 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3774 }
3775
3776 const char *BodyStart = StartToken.getLoc().getPointer();
3777 const char *BodyEnd = EndToken.getLoc().getPointer();
3778 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00003779 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003780 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00003781 return false;
3782}
3783
Jim Grosbach4b905842013-09-20 23:08:21 +00003784/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00003785///
3786/// With the support added for named parameters there may be code out there that
3787/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00003788/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00003789/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00003790/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00003791/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3792/// warning that the positional parameter found in body which have no effect.
3793/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00003794/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00003795/// intended or change the macro to use the named parameters. It is possible
3796/// this warning will trigger when the none of the named parameters are used
3797/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00003798void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00003799 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00003800 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00003801 // If this macro is not defined with named parameters the warning we are
3802 // checking for here doesn't apply.
3803 unsigned NParameters = Parameters.size();
3804 if (NParameters == 0)
3805 return;
3806
3807 bool NamedParametersFound = false;
3808 bool PositionalParametersFound = false;
3809
3810 // Look at the body of the macro for use of both the named parameters and what
3811 // are likely to be positional parameters. This is what expandMacro() is
3812 // doing when it finds the parameters in the body.
3813 while (!Body.empty()) {
3814 // Scan for the next possible parameter.
3815 std::size_t End = Body.size(), Pos = 0;
3816 for (; Pos != End; ++Pos) {
3817 // Check for a substitution or escape.
3818 // This macro is defined with parameters, look for \foo, \bar, etc.
3819 if (Body[Pos] == '\\' && Pos + 1 != End)
3820 break;
3821
3822 // This macro should have parameters, but look for $0, $1, ..., $n too.
3823 if (Body[Pos] != '$' || Pos + 1 == End)
3824 continue;
3825 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00003826 if (Next == '$' || Next == 'n' ||
3827 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00003828 break;
3829 }
3830
3831 // Check if we reached the end.
3832 if (Pos == End)
3833 break;
3834
3835 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00003836 switch (Body[Pos + 1]) {
3837 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00003838 case '$':
3839 break;
3840
Jim Grosbach4b905842013-09-20 23:08:21 +00003841 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00003842 case 'n':
3843 PositionalParametersFound = true;
3844 break;
3845
Jim Grosbach4b905842013-09-20 23:08:21 +00003846 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00003847 default: {
3848 PositionalParametersFound = true;
3849 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00003850 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00003851 }
3852 Pos += 2;
3853 } else {
3854 unsigned I = Pos + 1;
3855 while (isIdentifierChar(Body[I]) && I + 1 != End)
3856 ++I;
3857
Jim Grosbach4b905842013-09-20 23:08:21 +00003858 const char *Begin = Body.data() + Pos + 1;
3859 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00003860 unsigned Index = 0;
3861 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003862 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00003863 break;
3864
3865 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00003866 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3867 Pos += 3;
3868 else {
3869 Pos = I;
3870 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00003871 } else {
3872 NamedParametersFound = true;
3873 Pos += 1 + Argument.size();
3874 }
3875 }
3876 // Update the scan point.
3877 Body = Body.substr(Pos);
3878 }
3879
3880 if (!NamedParametersFound && PositionalParametersFound)
3881 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3882 "used in macro body, possible positional parameter "
3883 "found in body which will have no effect");
3884}
3885
Nico Weber155dccd12014-07-24 17:08:39 +00003886/// parseDirectiveExitMacro
3887/// ::= .exitm
3888bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3889 if (getLexer().isNot(AsmToken::EndOfStatement))
3890 return TokError("unexpected token in '" + Directive + "' directive");
3891
3892 if (!isInsideMacroInstantiation())
3893 return TokError("unexpected '" + Directive + "' in file, "
3894 "no current macro definition");
3895
3896 // Exit all conditionals that are active in the current macro.
3897 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3898 TheCondState = TheCondStack.back();
3899 TheCondStack.pop_back();
3900 }
3901
3902 handleMacroExit();
3903 return false;
3904}
3905
Jim Grosbach4b905842013-09-20 23:08:21 +00003906/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00003907/// ::= .endm
3908/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00003909bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00003910 if (getLexer().isNot(AsmToken::EndOfStatement))
3911 return TokError("unexpected token in '" + Directive + "' directive");
3912
3913 // If we are inside a macro instantiation, terminate the current
3914 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00003915 if (isInsideMacroInstantiation()) {
3916 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00003917 return false;
3918 }
3919
3920 // Otherwise, this .endmacro is a stray entry in the file; well formed
3921 // .endmacro directives are handled during the macro definition parsing.
3922 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00003923 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00003924}
3925
Jim Grosbach4b905842013-09-20 23:08:21 +00003926/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00003927/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00003928bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003929 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003930 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003931 return TokError("expected identifier in '.purgem' directive");
3932
3933 if (getLexer().isNot(AsmToken::EndOfStatement))
3934 return TokError("unexpected token in '.purgem' directive");
3935
Jim Grosbach4b905842013-09-20 23:08:21 +00003936 if (!lookupMacro(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003937 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3938
Jim Grosbach4b905842013-09-20 23:08:21 +00003939 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003940 return false;
3941}
Eli Benderskyf483ff92012-12-20 19:05:53 +00003942
Jim Grosbach4b905842013-09-20 23:08:21 +00003943/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00003944/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003945bool AsmParser::parseDirectiveBundleAlignMode() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003946 checkForValidSection();
Eli Benderskyf483ff92012-12-20 19:05:53 +00003947
3948 // Expect a single argument: an expression that evaluates to a constant
3949 // in the inclusive range 0-30.
3950 SMLoc ExprLoc = getLexer().getLoc();
3951 int64_t AlignSizePow2;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003952 if (parseAbsoluteExpression(AlignSizePow2))
Eli Benderskyf483ff92012-12-20 19:05:53 +00003953 return true;
3954 else if (getLexer().isNot(AsmToken::EndOfStatement))
3955 return TokError("unexpected token after expression in"
3956 " '.bundle_align_mode' directive");
3957 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3958 return Error(ExprLoc,
3959 "invalid bundle alignment size (expected between 0 and 30)");
3960
3961 Lex();
3962
3963 // Because of AlignSizePow2's verified range we can safely truncate it to
3964 // unsigned.
3965 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3966 return false;
3967}
3968
Jim Grosbach4b905842013-09-20 23:08:21 +00003969/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00003970/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00003971bool AsmParser::parseDirectiveBundleLock() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003972 checkForValidSection();
Eli Bendersky802b6282013-01-07 21:51:08 +00003973 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00003974
Eli Bendersky802b6282013-01-07 21:51:08 +00003975 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3976 StringRef Option;
3977 SMLoc Loc = getTok().getLoc();
3978 const char *kInvalidOptionError =
Jim Grosbach4b905842013-09-20 23:08:21 +00003979 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00003980
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003981 if (parseIdentifier(Option))
Eli Bendersky802b6282013-01-07 21:51:08 +00003982 return Error(Loc, kInvalidOptionError);
3983
3984 if (Option != "align_to_end")
3985 return Error(Loc, kInvalidOptionError);
3986 else if (getLexer().isNot(AsmToken::EndOfStatement))
3987 return Error(Loc,
3988 "unexpected token after '.bundle_lock' directive option");
3989 AlignToEnd = true;
3990 }
3991
Eli Benderskyf483ff92012-12-20 19:05:53 +00003992 Lex();
3993
Eli Bendersky802b6282013-01-07 21:51:08 +00003994 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00003995 return false;
3996}
3997
Jim Grosbach4b905842013-09-20 23:08:21 +00003998/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00003999/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004000bool AsmParser::parseDirectiveBundleUnlock() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004001 checkForValidSection();
Eli Benderskyf483ff92012-12-20 19:05:53 +00004002
4003 if (getLexer().isNot(AsmToken::EndOfStatement))
4004 return TokError("unexpected token in '.bundle_unlock' directive");
4005 Lex();
4006
4007 getStreamer().EmitBundleUnlock();
4008 return false;
4009}
4010
Jim Grosbach4b905842013-09-20 23:08:21 +00004011/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004012/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004013bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004014 checkForValidSection();
Eli Bendersky17233942013-01-15 22:59:42 +00004015
4016 int64_t NumBytes;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004017 if (parseAbsoluteExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004018 return true;
4019
4020 int64_t FillExpr = 0;
4021 if (getLexer().isNot(AsmToken::EndOfStatement)) {
4022 if (getLexer().isNot(AsmToken::Comma))
4023 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
4024 Lex();
4025
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004026 if (parseAbsoluteExpression(FillExpr))
Eli Bendersky17233942013-01-15 22:59:42 +00004027 return true;
4028
4029 if (getLexer().isNot(AsmToken::EndOfStatement))
4030 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
4031 }
4032
4033 Lex();
4034
4035 if (NumBytes <= 0)
Jim Grosbach4b905842013-09-20 23:08:21 +00004036 return TokError("invalid number of bytes in '" + Twine(IDVal) +
4037 "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004038
4039 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Rafael Espindola64e1af82013-07-02 15:49:13 +00004040 getStreamer().EmitFill(NumBytes, FillExpr);
Eli Bendersky17233942013-01-15 22:59:42 +00004041
4042 return false;
4043}
4044
Jim Grosbach4b905842013-09-20 23:08:21 +00004045/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004046/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004047bool AsmParser::parseDirectiveLEB128(bool Signed) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004048 checkForValidSection();
Eli Bendersky17233942013-01-15 22:59:42 +00004049 const MCExpr *Value;
4050
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004051 for (;;) {
4052 if (parseExpression(Value))
4053 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004054
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004055 if (Signed)
4056 getStreamer().EmitSLEB128Value(Value);
4057 else
4058 getStreamer().EmitULEB128Value(Value);
Eli Bendersky17233942013-01-15 22:59:42 +00004059
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004060 if (getLexer().is(AsmToken::EndOfStatement))
4061 break;
4062
4063 if (getLexer().isNot(AsmToken::Comma))
4064 return TokError("unexpected token in directive");
4065 Lex();
4066 }
Eli Bendersky17233942013-01-15 22:59:42 +00004067
4068 return false;
4069}
4070
Jim Grosbach4b905842013-09-20 23:08:21 +00004071/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004072/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004073bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004074 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbara5508c82009-06-30 00:33:19 +00004075 for (;;) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004076 StringRef Name;
Jim Grosbachebdf32f2011-09-15 17:56:49 +00004077 SMLoc Loc = getTok().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004078
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004079 if (parseIdentifier(Name))
Jim Grosbachebdf32f2011-09-15 17:56:49 +00004080 return Error(Loc, "expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004081
Jim Grosbach6f482002015-05-18 18:43:14 +00004082 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbara5508c82009-06-30 00:33:19 +00004083
Jim Grosbachebdf32f2011-09-15 17:56:49 +00004084 // Assembler local symbols don't make any sense here. Complain loudly.
4085 if (Sym->isTemporary())
4086 return Error(Loc, "non-local symbol required in directive");
4087
Saleem Abdulrasool4208b612013-08-09 01:52:03 +00004088 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4089 return Error(Loc, "unable to emit symbol attribute");
Daniel Dunbara5508c82009-06-30 00:33:19 +00004090
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004091 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara5508c82009-06-30 00:33:19 +00004092 break;
4093
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004094 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara5508c82009-06-30 00:33:19 +00004095 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004096 Lex();
Daniel Dunbara5508c82009-06-30 00:33:19 +00004097 }
4098 }
4099
Sean Callanan686ed8d2010-01-19 20:22:31 +00004100 Lex();
Jan Wen Voungc7682872010-09-30 01:09:20 +00004101 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004102}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004103
Jim Grosbach4b905842013-09-20 23:08:21 +00004104/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004105/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004106bool AsmParser::parseDirectiveComm(bool IsLocal) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004107 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00004108
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004109 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004110 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004111 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004112 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004113
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004114 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004115 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004116
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004117 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004118 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004119 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004120
4121 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004122 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004123 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004124 return true;
4125
4126 int64_t Pow2Alignment = 0;
4127 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004128 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004129 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004130 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004131 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004132 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004133
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004134 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4135 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004136 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4137
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004138 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004139 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4140 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004141 if (!isPowerOf2_64(Pow2Alignment))
4142 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4143 Pow2Alignment = Log2_64(Pow2Alignment);
4144 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004145 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004146
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004147 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner28ad7542009-07-09 17:25:12 +00004148 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004149
Sean Callanan686ed8d2010-01-19 20:22:31 +00004150 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004151
Chris Lattner28ad7542009-07-09 17:25:12 +00004152 // NOTE: a size of zero for a .comm should create a undefined symbol
4153 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004154 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004155 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004156 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004157
Eric Christopherbc818852010-05-14 01:38:54 +00004158 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004159 // may internally end up wanting an alignment in bytes.
4160 // FIXME: Diagnose overflow.
4161 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004162 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004163 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004164
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004165 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004166 return Error(IDLoc, "invalid symbol redefinition");
4167
Chris Lattner28ad7542009-07-09 17:25:12 +00004168 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004169 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004170 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004171 return false;
4172 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004173
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004174 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004175 return false;
4176}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004177
Jim Grosbach4b905842013-09-20 23:08:21 +00004178/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004179/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004180bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004181 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004182 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004183
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004184 StringRef Str = parseStringToEndOfStatement();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004185 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby56523ce2009-07-13 23:15:14 +00004186 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004187
Sean Callanan686ed8d2010-01-19 20:22:31 +00004188 Lex();
Kevin Enderby56523ce2009-07-13 23:15:14 +00004189
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004190 if (Str.empty())
4191 Error(Loc, ".abort detected. Assembly stopping.");
4192 else
4193 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004194 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004195
4196 return false;
4197}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004198
Jim Grosbach4b905842013-09-20 23:08:21 +00004199/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004200/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004201bool AsmParser::parseDirectiveInclude() {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004202 if (getLexer().isNot(AsmToken::String))
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004203 return TokError("expected string in '.include' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004204
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004205 // Allow the strings to have escaped octal character sequence.
4206 std::string Filename;
4207 if (parseEscapedString(Filename))
4208 return true;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004209 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00004210 Lex();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004211
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004212 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004213 return TokError("unexpected token in '.include' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004214
Chris Lattner693fbb82009-07-16 06:14:39 +00004215 // Attempt to switch the lexer to the included file before consuming the end
4216 // of statement to avoid losing it when we switch.
Jim Grosbach4b905842013-09-20 23:08:21 +00004217 if (enterIncludeFile(Filename)) {
Daniel Dunbard8a18452010-07-18 18:31:45 +00004218 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner693fbb82009-07-16 06:14:39 +00004219 return true;
4220 }
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004221
4222 return false;
4223}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004224
Jim Grosbach4b905842013-09-20 23:08:21 +00004225/// parseDirectiveIncbin
Kevin Enderby109f25c2011-12-14 21:47:48 +00004226/// ::= .incbin "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004227bool AsmParser::parseDirectiveIncbin() {
Kevin Enderby109f25c2011-12-14 21:47:48 +00004228 if (getLexer().isNot(AsmToken::String))
4229 return TokError("expected string in '.incbin' directive");
4230
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004231 // Allow the strings to have escaped octal character sequence.
4232 std::string Filename;
4233 if (parseEscapedString(Filename))
4234 return true;
Kevin Enderby109f25c2011-12-14 21:47:48 +00004235 SMLoc IncbinLoc = getLexer().getLoc();
4236 Lex();
4237
4238 if (getLexer().isNot(AsmToken::EndOfStatement))
4239 return TokError("unexpected token in '.incbin' directive");
4240
Kevin Enderby109f25c2011-12-14 21:47:48 +00004241 // Attempt to process the included file.
Jim Grosbach4b905842013-09-20 23:08:21 +00004242 if (processIncbinFile(Filename)) {
Kevin Enderby109f25c2011-12-14 21:47:48 +00004243 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
4244 return true;
4245 }
4246
4247 return false;
4248}
4249
Jim Grosbach4b905842013-09-20 23:08:21 +00004250/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004251/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4252bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004253 TheCondStack.push_back(TheCondState);
4254 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004255 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004256 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004257 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004258 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004259 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004260 return true;
4261
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004262 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004263 return TokError("unexpected token in '.if' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004264
Sean Callanan686ed8d2010-01-19 20:22:31 +00004265 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004266
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004267 switch (DirKind) {
4268 default:
4269 llvm_unreachable("unsupported directive");
4270 case DK_IF:
4271 case DK_IFNE:
4272 break;
4273 case DK_IFEQ:
4274 ExprValue = ExprValue == 0;
4275 break;
4276 case DK_IFGE:
4277 ExprValue = ExprValue >= 0;
4278 break;
4279 case DK_IFGT:
4280 ExprValue = ExprValue > 0;
4281 break;
4282 case DK_IFLE:
4283 ExprValue = ExprValue <= 0;
4284 break;
4285 case DK_IFLT:
4286 ExprValue = ExprValue < 0;
4287 break;
4288 }
4289
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004290 TheCondState.CondMet = ExprValue;
4291 TheCondState.Ignore = !TheCondState.CondMet;
4292 }
4293
4294 return false;
4295}
4296
Jim Grosbach4b905842013-09-20 23:08:21 +00004297/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004298/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004299bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004300 TheCondStack.push_back(TheCondState);
4301 TheCondState.TheCond = AsmCond::IfCond;
4302
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004303 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004304 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004305 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004306 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004307
4308 if (getLexer().isNot(AsmToken::EndOfStatement))
4309 return TokError("unexpected token in '.ifb' directive");
4310
4311 Lex();
4312
4313 TheCondState.CondMet = ExpectBlank == Str.empty();
4314 TheCondState.Ignore = !TheCondState.CondMet;
4315 }
4316
4317 return false;
4318}
4319
Jim Grosbach4b905842013-09-20 23:08:21 +00004320/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004321/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004322/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004323bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004324 TheCondStack.push_back(TheCondState);
4325 TheCondState.TheCond = AsmCond::IfCond;
4326
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004327 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004328 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004329 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004330 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004331
4332 if (getLexer().isNot(AsmToken::Comma))
4333 return TokError("unexpected token in '.ifc' directive");
4334
4335 Lex();
4336
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004337 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004338
4339 if (getLexer().isNot(AsmToken::EndOfStatement))
4340 return TokError("unexpected token in '.ifc' directive");
4341
4342 Lex();
4343
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004344 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004345 TheCondState.Ignore = !TheCondState.CondMet;
4346 }
4347
4348 return false;
4349}
4350
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004351/// parseDirectiveIfeqs
4352/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004353bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004354 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004355 if (ExpectEqual)
4356 TokError("expected string parameter for '.ifeqs' directive");
4357 else
4358 TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004359 eatToEndOfStatement();
4360 return true;
4361 }
4362
4363 StringRef String1 = getTok().getStringContents();
4364 Lex();
4365
4366 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004367 if (ExpectEqual)
4368 TokError("expected comma after first string for '.ifeqs' directive");
4369 else
4370 TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004371 eatToEndOfStatement();
4372 return true;
4373 }
4374
4375 Lex();
4376
4377 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004378 if (ExpectEqual)
4379 TokError("expected string parameter for '.ifeqs' directive");
4380 else
4381 TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004382 eatToEndOfStatement();
4383 return true;
4384 }
4385
4386 StringRef String2 = getTok().getStringContents();
4387 Lex();
4388
4389 TheCondStack.push_back(TheCondState);
4390 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004391 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004392 TheCondState.Ignore = !TheCondState.CondMet;
4393
4394 return false;
4395}
4396
Jim Grosbach4b905842013-09-20 23:08:21 +00004397/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004398/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004399bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004400 StringRef Name;
4401 TheCondStack.push_back(TheCondState);
4402 TheCondState.TheCond = AsmCond::IfCond;
4403
4404 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004405 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004406 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004407 if (parseIdentifier(Name))
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004408 return TokError("expected identifier after '.ifdef'");
4409
4410 Lex();
4411
Jim Grosbach6f482002015-05-18 18:43:14 +00004412 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004413
4414 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004415 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004416 else
Craig Topper353eda42014-04-24 06:44:33 +00004417 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004418 TheCondState.Ignore = !TheCondState.CondMet;
4419 }
4420
4421 return false;
4422}
4423
Jim Grosbach4b905842013-09-20 23:08:21 +00004424/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004425/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004426bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004427 if (TheCondState.TheCond != AsmCond::IfCond &&
4428 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper2172ad62013-04-22 04:24:02 +00004429 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4430 " an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004431 TheCondState.TheCond = AsmCond::ElseIfCond;
4432
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004433 bool LastIgnoreState = false;
4434 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004435 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004436 if (LastIgnoreState || TheCondState.CondMet) {
4437 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004438 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004439 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004440 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004441 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004442 return true;
4443
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004444 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004445 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004446
Sean Callanan686ed8d2010-01-19 20:22:31 +00004447 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004448 TheCondState.CondMet = ExprValue;
4449 TheCondState.Ignore = !TheCondState.CondMet;
4450 }
4451
4452 return false;
4453}
4454
Jim Grosbach4b905842013-09-20 23:08:21 +00004455/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004456/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004457bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004458 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004459 return TokError("unexpected token in '.else' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004460
Sean Callanan686ed8d2010-01-19 20:22:31 +00004461 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004462
4463 if (TheCondState.TheCond != AsmCond::IfCond &&
4464 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper2172ad62013-04-22 04:24:02 +00004465 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4466 ".elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004467 TheCondState.TheCond = AsmCond::ElseCond;
4468 bool LastIgnoreState = false;
4469 if (!TheCondStack.empty())
4470 LastIgnoreState = TheCondStack.back().Ignore;
4471 if (LastIgnoreState || TheCondState.CondMet)
4472 TheCondState.Ignore = true;
4473 else
4474 TheCondState.Ignore = false;
4475
4476 return false;
4477}
4478
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004479/// parseDirectiveEnd
4480/// ::= .end
4481bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4482 if (getLexer().isNot(AsmToken::EndOfStatement))
4483 return TokError("unexpected token in '.end' directive");
4484
4485 Lex();
4486
4487 while (Lexer.isNot(AsmToken::Eof))
4488 Lex();
4489
4490 return false;
4491}
4492
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004493/// parseDirectiveError
4494/// ::= .err
4495/// ::= .error [string]
4496bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4497 if (!TheCondStack.empty()) {
4498 if (TheCondStack.back().Ignore) {
4499 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004500 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004501 }
4502 }
4503
4504 if (!WithMessage)
4505 return Error(L, ".err encountered");
4506
4507 StringRef Message = ".error directive invoked in source file";
4508 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4509 if (Lexer.isNot(AsmToken::String)) {
4510 TokError(".error argument must be a string");
4511 eatToEndOfStatement();
4512 return true;
4513 }
4514
4515 Message = getTok().getStringContents();
4516 Lex();
4517 }
4518
4519 Error(L, Message);
4520 return true;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004521}
4522
Nico Weber404012b2014-07-24 16:26:06 +00004523/// parseDirectiveWarning
4524/// ::= .warning [string]
4525bool AsmParser::parseDirectiveWarning(SMLoc L) {
4526 if (!TheCondStack.empty()) {
4527 if (TheCondStack.back().Ignore) {
4528 eatToEndOfStatement();
4529 return false;
4530 }
4531 }
4532
4533 StringRef Message = ".warning directive invoked in source file";
4534 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4535 if (Lexer.isNot(AsmToken::String)) {
4536 TokError(".warning argument must be a string");
4537 eatToEndOfStatement();
4538 return true;
4539 }
4540
4541 Message = getTok().getStringContents();
4542 Lex();
4543 }
4544
4545 Warning(L, Message);
4546 return false;
4547}
4548
Jim Grosbach4b905842013-09-20 23:08:21 +00004549/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004550/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00004551bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004552 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004553 return TokError("unexpected token in '.endif' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004554
Sean Callanan686ed8d2010-01-19 20:22:31 +00004555 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004556
Jim Grosbach4b905842013-09-20 23:08:21 +00004557 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004558 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4559 ".else");
4560 if (!TheCondStack.empty()) {
4561 TheCondState = TheCondStack.back();
4562 TheCondStack.pop_back();
4563 }
4564
4565 return false;
4566}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00004567
Eli Bendersky17233942013-01-15 22:59:42 +00004568void AsmParser::initializeDirectiveKindMap() {
4569 DirectiveKindMap[".set"] = DK_SET;
4570 DirectiveKindMap[".equ"] = DK_EQU;
4571 DirectiveKindMap[".equiv"] = DK_EQUIV;
4572 DirectiveKindMap[".ascii"] = DK_ASCII;
4573 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4574 DirectiveKindMap[".string"] = DK_STRING;
4575 DirectiveKindMap[".byte"] = DK_BYTE;
4576 DirectiveKindMap[".short"] = DK_SHORT;
4577 DirectiveKindMap[".value"] = DK_VALUE;
4578 DirectiveKindMap[".2byte"] = DK_2BYTE;
4579 DirectiveKindMap[".long"] = DK_LONG;
4580 DirectiveKindMap[".int"] = DK_INT;
4581 DirectiveKindMap[".4byte"] = DK_4BYTE;
4582 DirectiveKindMap[".quad"] = DK_QUAD;
4583 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00004584 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00004585 DirectiveKindMap[".single"] = DK_SINGLE;
4586 DirectiveKindMap[".float"] = DK_FLOAT;
4587 DirectiveKindMap[".double"] = DK_DOUBLE;
4588 DirectiveKindMap[".align"] = DK_ALIGN;
4589 DirectiveKindMap[".align32"] = DK_ALIGN32;
4590 DirectiveKindMap[".balign"] = DK_BALIGN;
4591 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4592 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4593 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4594 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4595 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4596 DirectiveKindMap[".org"] = DK_ORG;
4597 DirectiveKindMap[".fill"] = DK_FILL;
4598 DirectiveKindMap[".zero"] = DK_ZERO;
4599 DirectiveKindMap[".extern"] = DK_EXTERN;
4600 DirectiveKindMap[".globl"] = DK_GLOBL;
4601 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00004602 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4603 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4604 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4605 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4606 DirectiveKindMap[".reference"] = DK_REFERENCE;
4607 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4608 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4609 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4610 DirectiveKindMap[".comm"] = DK_COMM;
4611 DirectiveKindMap[".common"] = DK_COMMON;
4612 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4613 DirectiveKindMap[".abort"] = DK_ABORT;
4614 DirectiveKindMap[".include"] = DK_INCLUDE;
4615 DirectiveKindMap[".incbin"] = DK_INCBIN;
4616 DirectiveKindMap[".code16"] = DK_CODE16;
4617 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4618 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004619 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00004620 DirectiveKindMap[".irp"] = DK_IRP;
4621 DirectiveKindMap[".irpc"] = DK_IRPC;
4622 DirectiveKindMap[".endr"] = DK_ENDR;
4623 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4624 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4625 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4626 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004627 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4628 DirectiveKindMap[".ifge"] = DK_IFGE;
4629 DirectiveKindMap[".ifgt"] = DK_IFGT;
4630 DirectiveKindMap[".ifle"] = DK_IFLE;
4631 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00004632 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00004633 DirectiveKindMap[".ifb"] = DK_IFB;
4634 DirectiveKindMap[".ifnb"] = DK_IFNB;
4635 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004636 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00004637 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00004638 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00004639 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4640 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4641 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4642 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4643 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004644 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00004645 DirectiveKindMap[".endif"] = DK_ENDIF;
4646 DirectiveKindMap[".skip"] = DK_SKIP;
4647 DirectiveKindMap[".space"] = DK_SPACE;
4648 DirectiveKindMap[".file"] = DK_FILE;
4649 DirectiveKindMap[".line"] = DK_LINE;
4650 DirectiveKindMap[".loc"] = DK_LOC;
4651 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004652 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
4653 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
4654 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00004655 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
David Majnemer408b5e62016-02-05 01:55:49 +00004656 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004657 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
4658 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Eli Bendersky17233942013-01-15 22:59:42 +00004659 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4660 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4661 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4662 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4663 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4664 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4665 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4666 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4667 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4668 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4669 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4670 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4671 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4672 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4673 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4674 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4675 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4676 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4677 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4678 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4679 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00004680 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00004681 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4682 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4683 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00004684 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00004685 DirectiveKindMap[".endm"] = DK_ENDM;
4686 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4687 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004688 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004689 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00004690 DirectiveKindMap[".warning"] = DK_WARNING;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00004691 DirectiveKindMap[".reloc"] = DK_RELOC;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00004692}
4693
Jim Grosbach4b905842013-09-20 23:08:21 +00004694MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004695 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004696
Rafael Espindola34b9c512012-06-03 23:57:14 +00004697 unsigned NestLevel = 0;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004698 for (;;) {
4699 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00004700 if (getLexer().is(AsmToken::Eof)) {
4701 Error(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00004702 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004703 }
4704
Rafael Espindola34b9c512012-06-03 23:57:14 +00004705 if (Lexer.is(AsmToken::Identifier) &&
4706 (getTok().getIdentifier() == ".rept")) {
4707 ++NestLevel;
4708 }
4709
4710 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00004711 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004712 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004713 EndToken = getTok();
4714 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004715 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4716 TokError("unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00004717 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004718 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004719 break;
4720 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004721 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004722 }
4723
Rafael Espindola34b9c512012-06-03 23:57:14 +00004724 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004725 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004726 }
4727
4728 const char *BodyStart = StartToken.getLoc().getPointer();
4729 const char *BodyEnd = EndToken.getLoc().getPointer();
4730 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4731
Rafael Espindola34b9c512012-06-03 23:57:14 +00004732 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004733 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00004734 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004735}
4736
Jim Grosbach4b905842013-09-20 23:08:21 +00004737void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00004738 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004739 OS << ".endr\n";
4740
Rafael Espindola3560ff22014-08-27 20:03:13 +00004741 std::unique_ptr<MemoryBuffer> Instantiation =
4742 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004743
Rafael Espindola34b9c512012-06-03 23:57:14 +00004744 // Create the macro instantiation object and add to the current macro
4745 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00004746 MacroInstantiation *MI = new MacroInstantiation(
4747 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00004748 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004749
Rafael Espindola34b9c512012-06-03 23:57:14 +00004750 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00004751 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00004752 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00004753 Lex();
4754}
4755
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004756/// parseDirectiveRept
4757/// ::= .rep | .rept count
4758bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004759 const MCExpr *CountExpr;
4760 SMLoc CountLoc = getTok().getLoc();
4761 if (parseExpression(CountExpr))
4762 return true;
4763
Rafael Espindola34b9c512012-06-03 23:57:14 +00004764 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00004765 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004766 eatToEndOfStatement();
4767 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4768 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004769
4770 if (Count < 0)
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004771 return Error(CountLoc, "Count is negative");
Rafael Espindola34b9c512012-06-03 23:57:14 +00004772
4773 if (Lexer.isNot(AsmToken::EndOfStatement))
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004774 return TokError("unexpected token in '" + Dir + "' directive");
Rafael Espindola34b9c512012-06-03 23:57:14 +00004775
4776 // Eat the end of statement.
4777 Lex();
4778
4779 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004780 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +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;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004787 raw_svector_ostream OS(Buf);
4788 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00004789 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4790 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00004791 return true;
4792 }
Jim Grosbach4b905842013-09-20 23:08:21 +00004793 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004794
4795 return false;
4796}
4797
Jim Grosbach4b905842013-09-20 23:08:21 +00004798/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00004799/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00004800bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00004801 MCAsmMacroParameter Parameter;
Rafael Espindola768b41c2012-06-15 14:02:34 +00004802
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004803 if (parseIdentifier(Parameter.Name))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004804 return TokError("expected identifier in '.irp' directive");
4805
Rafael Espindola768b41c2012-06-15 14:02:34 +00004806 if (Lexer.isNot(AsmToken::Comma))
4807 return TokError("expected comma in '.irp' directive");
4808
4809 Lex();
4810
Eli Bendersky38274122013-01-14 23:22:36 +00004811 MCAsmMacroArguments A;
Craig Topper353eda42014-04-24 06:44:33 +00004812 if (parseMacroArguments(nullptr, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004813 return true;
4814
4815 // Eat the end of statement.
4816 Lex();
4817
4818 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004819 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00004820 if (!M)
4821 return true;
4822
4823 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4824 // to hold the macro body with substitutions.
4825 SmallString<256> Buf;
4826 raw_svector_ostream OS(Buf);
4827
Craig Topper84008482015-10-10 05:38:14 +00004828 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00004829 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4830 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00004831 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004832 return true;
4833 }
4834
Jim Grosbach4b905842013-09-20 23:08:21 +00004835 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00004836
4837 return false;
4838}
4839
Jim Grosbach4b905842013-09-20 23:08:21 +00004840/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004841/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00004842bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00004843 MCAsmMacroParameter Parameter;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004844
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004845 if (parseIdentifier(Parameter.Name))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004846 return TokError("expected identifier in '.irpc' directive");
4847
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004848 if (Lexer.isNot(AsmToken::Comma))
4849 return TokError("expected comma in '.irpc' directive");
4850
4851 Lex();
4852
Eli Bendersky38274122013-01-14 23:22:36 +00004853 MCAsmMacroArguments A;
Craig Topper353eda42014-04-24 06:44:33 +00004854 if (parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004855 return true;
4856
4857 if (A.size() != 1 || A.front().size() != 1)
4858 return TokError("unexpected token in '.irpc' directive");
4859
4860 // Eat the end of statement.
4861 Lex();
4862
4863 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004864 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004865 if (!M)
4866 return true;
4867
4868 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4869 // to hold the macro body with substitutions.
4870 SmallString<256> Buf;
4871 raw_svector_ostream OS(Buf);
4872
4873 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004874 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00004875 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004876 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004877
Toma Tabacu217116e2015-04-27 10:50:29 +00004878 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
4879 // This is undocumented, but GAS seems to support it.
4880 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004881 return true;
4882 }
4883
Jim Grosbach4b905842013-09-20 23:08:21 +00004884 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004885
4886 return false;
4887}
4888
Jim Grosbach4b905842013-09-20 23:08:21 +00004889bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004890 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00004891 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004892
4893 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00004894 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004895 assert(getLexer().is(AsmToken::EndOfStatement));
4896
Jim Grosbach4b905842013-09-20 23:08:21 +00004897 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004898 return false;
4899}
Rafael Espindola12d73d12010-09-11 16:45:15 +00004900
Jim Grosbach4b905842013-09-20 23:08:21 +00004901bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00004902 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00004903 const MCExpr *Value;
4904 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004905 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00004906 return true;
4907 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4908 if (!MCE)
4909 return Error(ExprLoc, "unexpected expression in _emit");
4910 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00004911 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00004912 return Error(ExprLoc, "literal value out of range for directive");
4913
Craig Topper7d5b2312015-10-10 05:25:02 +00004914 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00004915 return false;
4916}
4917
Jim Grosbach4b905842013-09-20 23:08:21 +00004918bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00004919 const MCExpr *Value;
4920 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004921 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00004922 return true;
4923 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4924 if (!MCE)
4925 return Error(ExprLoc, "unexpected expression in align");
4926 uint64_t IntValue = MCE->getValue();
4927 if (!isPowerOf2_64(IntValue))
4928 return Error(ExprLoc, "literal value not a power of two greater then zero");
4929
Craig Topper7d5b2312015-10-10 05:25:02 +00004930 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00004931 return false;
4932}
4933
Chad Rosierf43fcf52013-02-13 21:27:17 +00004934// We are comparing pointers, but the pointers are relative to a single string.
4935// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00004936static int rewritesSort(const AsmRewrite *AsmRewriteA,
4937 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00004938 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4939 return -1;
4940 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4941 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004942
Chad Rosierfce4fab2013-04-08 17:43:47 +00004943 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4944 // rewrite to the same location. Make sure the SizeDirective rewrite is
4945 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4946 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00004947 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4948 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004949 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00004950
Jim Grosbach4b905842013-09-20 23:08:21 +00004951 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4952 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004953 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00004954 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00004955}
4956
Jim Grosbach4b905842013-09-20 23:08:21 +00004957bool AsmParser::parseMSInlineAsm(
4958 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4959 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4960 SmallVectorImpl<std::string> &Constraints,
4961 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4962 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00004963 SmallVector<void *, 4> InputDecls;
4964 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00004965 SmallVector<bool, 4> InputDeclsAddressOf;
4966 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00004967 SmallVector<std::string, 4> InputConstraints;
4968 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00004969 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00004970
Benjamin Kramer1a136112013-02-15 20:37:21 +00004971 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00004972
4973 // Prime the lexer.
4974 Lex();
4975
4976 // While we have input, parse each statement.
4977 unsigned InputIdx = 0;
4978 unsigned OutputIdx = 0;
4979 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00004980 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00004981 if (parseStatement(Info, &SI))
Chad Rosierf1f6a722012-10-19 22:57:33 +00004982 return true;
Chad Rosier8bce6642012-10-18 15:49:34 +00004983
Chad Rosier149e8e02012-12-12 22:45:52 +00004984 if (Info.ParseError)
4985 return true;
4986
Benjamin Kramer1a136112013-02-15 20:37:21 +00004987 if (Info.Opcode == ~0U)
4988 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00004989
Benjamin Kramer1a136112013-02-15 20:37:21 +00004990 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00004991
Benjamin Kramer1a136112013-02-15 20:37:21 +00004992 // Build the list of clobbers, outputs and inputs.
4993 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00004994 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00004995
Benjamin Kramer1a136112013-02-15 20:37:21 +00004996 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00004997 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00004998 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00004999
Benjamin Kramer1a136112013-02-15 20:37:21 +00005000 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005001 if (Operand.isReg() && !Operand.needAddressOf() &&
5002 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005003 unsigned NumDefs = Desc.getNumDefs();
5004 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005005 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5006 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005007 continue;
5008 }
5009
5010 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005011 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005012 if (SymName.empty())
5013 continue;
5014
David Blaikie960ea3f2014-06-08 16:18:35 +00005015 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005016 if (!OpDecl)
5017 continue;
5018
5019 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005020 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005021 if (isOutput) {
5022 ++InputIdx;
5023 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005024 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005025 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005026 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005027 } else {
5028 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005029 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5030 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005031 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005032 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005033 }
Reid Kleckneree088972013-12-10 18:27:32 +00005034
5035 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005036 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5037 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005038 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005039 }
5040
5041 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005042 NumOutputs = OutputDecls.size();
5043 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005044
5045 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005046 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5047 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5048 ClobberRegs.end());
5049 Clobbers.assign(ClobberRegs.size(), std::string());
5050 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5051 raw_string_ostream OS(Clobbers[I]);
5052 IP->printRegName(OS, ClobberRegs[I]);
5053 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005054
5055 // Merge the various outputs and inputs. Output are expected first.
5056 if (NumOutputs || NumInputs) {
5057 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005058 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005059 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005060 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005061 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005062 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005063 }
5064 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005065 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005066 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005067 }
5068 }
5069
5070 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005071 std::string AsmStringIR;
5072 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005073 StringRef ASMString =
5074 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5075 const char *AsmStart = ASMString.begin();
5076 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005077 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005078 for (const AsmRewrite &AR : AsmStrRewrites) {
5079 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005080 if (Kind == AOK_Delete)
5081 continue;
5082
David Majnemer8114c1a2014-06-23 02:17:16 +00005083 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005084 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005085
Chad Rosier120eefd2013-03-19 17:32:17 +00005086 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005087 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005088 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005089
Chad Rosier37e755c2012-10-23 17:43:43 +00005090 // Skip the original expression.
5091 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005092 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005093 continue;
5094 }
5095
Chad Rosierff10ed12013-04-12 16:26:42 +00005096 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005097 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005098 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005099 default:
5100 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005101 case AOK_Imm:
David Majnemer8114c1a2014-06-23 02:17:16 +00005102 OS << "$$" << AR.Val;
Chad Rosier11c42f22012-10-26 18:04:20 +00005103 break;
5104 case AOK_ImmPrefix:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005105 OS << "$$";
Chad Rosier8bce6642012-10-18 15:49:34 +00005106 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005107 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005108 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005109 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005110 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005111 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005112 break;
5113 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005114 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005115 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005116 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005117 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005118 default: break;
5119 case 8: OS << "byte ptr "; break;
5120 case 16: OS << "word ptr "; break;
5121 case 32: OS << "dword ptr "; break;
5122 case 64: OS << "qword ptr "; break;
5123 case 80: OS << "xword ptr "; break;
5124 case 128: OS << "xmmword ptr "; break;
5125 case 256: OS << "ymmword ptr "; break;
5126 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005127 break;
5128 case AOK_Emit:
5129 OS << ".byte";
5130 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005131 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005132 // MS alignment directives are measured in bytes. If the native assembler
5133 // measures alignment in bytes, we can pass it straight through.
5134 OS << ".align";
5135 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5136 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005137
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005138 // Alignment is in log2 form, so print that instead and skip the original
5139 // immediate.
5140 unsigned Val = AR.Val;
5141 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005142 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005143 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5144 break;
5145 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005146 case AOK_EVEN:
5147 OS << ".even";
5148 break;
Chad Rosierf0e87202012-10-25 20:41:34 +00005149 case AOK_DotOperator:
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005150 // Insert the dot if the user omitted it.
Alp Tokere69170a2014-06-26 22:52:05 +00005151 OS.flush();
5152 if (AsmStringIR.back() != '.')
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005153 OS << '.';
David Majnemer8114c1a2014-06-23 02:17:16 +00005154 OS << AR.Val;
Chad Rosierf0e87202012-10-25 20:41:34 +00005155 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005156 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005157
Chad Rosier8bce6642012-10-18 15:49:34 +00005158 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005159 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005160 }
5161
5162 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005163 if (AsmStart != AsmEnd)
5164 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005165
5166 AsmString = OS.str();
5167 return false;
5168}
5169
Pete Cooper80d21cb2015-06-22 19:35:57 +00005170namespace llvm {
5171namespace MCParserUtils {
5172
5173/// Returns whether the given symbol is used anywhere in the given expression,
5174/// or subexpressions.
5175static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5176 switch (Value->getKind()) {
5177 case MCExpr::Binary: {
5178 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5179 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5180 isSymbolUsedInExpression(Sym, BE->getRHS());
5181 }
5182 case MCExpr::Target:
5183 case MCExpr::Constant:
5184 return false;
5185 case MCExpr::SymbolRef: {
5186 const MCSymbol &S =
5187 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5188 if (S.isVariable())
5189 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5190 return &S == Sym;
5191 }
5192 case MCExpr::Unary:
5193 return isSymbolUsedInExpression(
5194 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5195 }
5196
5197 llvm_unreachable("Unknown expr kind!");
5198}
5199
5200bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5201 MCAsmParser &Parser, MCSymbol *&Sym,
5202 const MCExpr *&Value) {
5203 MCAsmLexer &Lexer = Parser.getLexer();
5204
5205 // FIXME: Use better location, we should use proper tokens.
5206 SMLoc EqualLoc = Lexer.getLoc();
5207
5208 if (Parser.parseExpression(Value)) {
5209 Parser.TokError("missing expression");
5210 Parser.eatToEndOfStatement();
5211 return true;
5212 }
5213
5214 // Note: we don't count b as used in "a = b". This is to allow
5215 // a = b
5216 // b = c
5217
5218 if (Lexer.isNot(AsmToken::EndOfStatement))
5219 return Parser.TokError("unexpected token in assignment");
5220
5221 // Eat the end of statement marker.
5222 Parser.Lex();
5223
5224 // Validate that the LHS is allowed to be a variable (either it has not been
5225 // used as a symbol, or it is an absolute symbol).
5226 Sym = Parser.getContext().lookupSymbol(Name);
5227 if (Sym) {
5228 // Diagnose assignment to a label.
5229 //
5230 // FIXME: Diagnostics. Note the location of the definition as a label.
5231 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5232 if (isSymbolUsedInExpression(Sym, Value))
5233 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005234 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5235 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005236 ; // Allow redefinitions of undefined symbols only used in directives.
5237 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5238 ; // Allow redefinitions of variables that haven't yet been used.
5239 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5240 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5241 else if (!Sym->isVariable())
5242 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5243 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5244 return Parser.Error(EqualLoc,
5245 "invalid reassignment of non-absolute variable '" +
5246 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005247 } else if (Name == ".") {
Rafael Espindola7ae65d82015-11-04 23:59:18 +00005248 Parser.getStreamer().emitValueToOffset(Value, 0);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005249 return false;
5250 } else
5251 Sym = Parser.getContext().getOrCreateSymbol(Name);
5252
5253 Sym->setRedefinable(allow_redef);
5254
5255 return false;
5256}
5257
5258} // namespace MCParserUtils
5259} // namespace llvm
5260
Daniel Dunbar01e36072010-07-17 02:26:10 +00005261/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005262MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
5263 MCStreamer &Out, const MCAsmInfo &MAI) {
Jim Grosbach345768c2011-08-16 18:33:49 +00005264 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005265}