blob: e86e0d657dc0da046617046cbb01327a5201d6d8 [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"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000015#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/None.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000018#include "llvm/ADT/STLExtras.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000019#include "llvm/ADT/SmallString.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000020#include "llvm/ADT/SmallVector.h"
Reid Kleckner26fa1bf2017-09-19 18:14:45 +000021#include "llvm/ADT/StringExtras.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000022#include "llvm/ADT/StringMap.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000023#include "llvm/ADT/StringRef.h"
Daniel Dunbareb6bb322009-07-27 23:20:52 +000024#include "llvm/ADT/Twine.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000025#include "llvm/BinaryFormat/Dwarf.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000026#include "llvm/MC/MCAsmInfo.h"
Reid Klecknera5b1eef2016-08-26 17:58:37 +000027#include "llvm/MC/MCCodeView.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000028#include "llvm/MC/MCContext.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000029#include "llvm/MC/MCDirectives.h"
Evan Cheng11424442011-07-26 00:24:13 +000030#include "llvm/MC/MCDwarf.h"
Daniel Dunbar115e4d62009-08-31 08:06:59 +000031#include "llvm/MC/MCExpr.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000032#include "llvm/MC/MCInstPrinter.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000033#include "llvm/MC/MCInstrDesc.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000034#include "llvm/MC/MCInstrInfo.h"
Rafael Espindolae28610d2013-12-09 20:26:40 +000035#include "llvm/MC/MCObjectFileInfo.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000036#include "llvm/MC/MCParser/AsmCond.h"
37#include "llvm/MC/MCParser/AsmLexer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000038#include "llvm/MC/MCParser/MCAsmLexer.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000039#include "llvm/MC/MCParser/MCAsmParser.h"
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000040#include "llvm/MC/MCParser/MCAsmParserExtension.h"
Pete Cooper80d21cb2015-06-22 19:35:57 +000041#include "llvm/MC/MCParser/MCAsmParserUtils.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000042#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000043#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Cheng76792992011-07-20 05:58:47 +000044#include "llvm/MC/MCRegisterInfo.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000045#include "llvm/MC/MCSection.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000046#include "llvm/MC/MCStreamer.h"
Daniel Dunbarae7ac012009-06-29 23:43:14 +000047#include "llvm/MC/MCSymbol.h"
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000048#include "llvm/MC/MCTargetOptions.h"
Daniel Sanders9f6ad492015-11-12 13:33:00 +000049#include "llvm/MC/MCValue.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000050#include "llvm/Support/Casting.h"
Davide Italiano7c9fc732016-07-27 05:51:56 +000051#include "llvm/Support/CommandLine.h"
Benjamin Kramer4efe5062012-01-28 15:28:41 +000052#include "llvm/Support/ErrorHandling.h"
Paul Robinson29f5f982018-01-09 23:31:48 +000053#include "llvm/Support/MD5.h"
Jim Grosbach76346c32011-06-29 16:05:14 +000054#include "llvm/Support/MathExtras.h"
Kevin Enderbye233dda2010-06-28 21:45:58 +000055#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000056#include "llvm/Support/SMLoc.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000057#include "llvm/Support/SourceMgr.h"
Chris Lattner36e02122009-06-21 20:54:55 +000058#include "llvm/Support/raw_ostream.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000059#include <algorithm>
60#include <cassert>
Nick Lewycky0de20af2010-12-19 20:43:38 +000061#include <cctype>
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000062#include <climits>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000063#include <cstddef>
64#include <cstdint>
Benjamin Kramerd59664f2014-04-29 23:26:49 +000065#include <deque>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000066#include <memory>
Davide Italiano7c9fc732016-07-27 05:51:56 +000067#include <sstream>
Chad Rosier8bce6642012-10-18 15:49:34 +000068#include <string>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000069#include <tuple>
70#include <utility>
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000071#include <vector>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000072
Chris Lattnerb0133452009-06-21 20:16:42 +000073using namespace llvm;
74
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000075MCAsmParserSemaCallback::~MCAsmParserSemaCallback() = default;
Nick Lewyckyac612272012-10-19 07:00:09 +000076
Davide Italiano7c9fc732016-07-27 05:51:56 +000077static cl::opt<unsigned> AsmMacroMaxNestingDepth(
78 "asm-macro-max-nesting-depth", cl::init(20), cl::Hidden,
79 cl::desc("The maximum nesting depth allowed for assembly macros."));
80
Daniel Dunbar86033402010-07-12 17:54:38 +000081namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +000082
Eli Benderskya313ae62013-01-16 18:56:50 +000083/// \brief Helper types for tracking macro definitions.
84typedef std::vector<AsmToken> MCAsmMacroArgument;
85typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000086
Daniel Dunbar43235712010-07-18 18:54:11 +000087/// \brief Helper class for storing information about an active macro
88/// instantiation.
89struct MacroInstantiation {
Daniel Dunbar43235712010-07-18 18:54:11 +000090 /// The location of the instantiation.
91 SMLoc InstantiationLoc;
92
Daniel Dunbar40f1d852012-12-01 01:38:48 +000093 /// The buffer where parsing should resume upon instantiation completion.
94 int ExitBuffer;
95
Daniel Dunbar43235712010-07-18 18:54:11 +000096 /// The location where parsing should resume upon instantiation completion.
97 SMLoc ExitLoc;
98
Nico Weber155dccd12014-07-24 17:08:39 +000099 /// The depth of TheCondStack at the start of the instantiation.
100 size_t CondStackDepth;
101
Daniel Dunbar43235712010-07-18 18:54:11 +0000102public:
Rafael Espindola9eef18c2014-08-27 19:49:03 +0000103 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
Daniel Dunbar43235712010-07-18 18:54:11 +0000104};
105
Eli Friedman0f4871d2012-10-22 23:58:19 +0000106struct ParseStatementInfo {
Jim Grosbach4b905842013-09-20 23:08:21 +0000107 /// \brief The parsed operands from the last parsed statement.
David Blaikie960ea3f2014-06-08 16:18:35 +0000108 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000109
Jim Grosbach4b905842013-09-20 23:08:21 +0000110 /// \brief The opcode from the last parsed instruction.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000111 unsigned Opcode = ~0U;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000112
Jim Grosbach4b905842013-09-20 23:08:21 +0000113 /// \brief Was there an error parsing the inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000114 bool ParseError = false;
Chad Rosier149e8e02012-12-12 22:45:52 +0000115
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000116 SmallVectorImpl<AsmRewrite> *AsmRewrites = nullptr;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000117
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000118 ParseStatementInfo() = delete;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000119 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000120 : AsmRewrites(rewrites) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000121};
122
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000123/// \brief The concrete assembly parser instance.
124class AsmParser : public MCAsmParser {
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000125private:
126 AsmLexer Lexer;
127 MCContext &Ctx;
128 MCStreamer &Out;
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000129 const MCAsmInfo &MAI;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000130 SourceMgr &SrcMgr;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000131 SourceMgr::DiagHandlerTy SavedDiagHandler;
132 void *SavedDiagContext;
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000133 std::unique_ptr<MCAsmParserExtension> PlatformParser;
Rafael Espindola82065cb2011-04-11 21:49:50 +0000134
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000135 /// This is the current buffer index we're lexing from as managed by the
136 /// SourceMgr object.
Alp Tokera55b95b2014-07-06 10:33:31 +0000137 unsigned CurBuffer;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000138
139 AsmCond TheCondState;
140 std::vector<AsmCond> TheCondStack;
141
Jim Grosbach4b905842013-09-20 23:08:21 +0000142 /// \brief maps directive names to handler methods in parser
Eli Bendersky17233942013-01-15 22:59:42 +0000143 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000144 /// addDirectiveHandler.
Eli Bendersky17233942013-01-15 22:59:42 +0000145 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000146
Jim Grosbach4b905842013-09-20 23:08:21 +0000147 /// \brief Stack of active macro instantiations.
Daniel Dunbar43235712010-07-18 18:54:11 +0000148 std::vector<MacroInstantiation*> ActiveMacros;
149
Jim Grosbach4b905842013-09-20 23:08:21 +0000150 /// \brief List of bodies of anonymous macros.
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +0000151 std::deque<MCAsmMacro> MacroLikeBodies;
152
Daniel Dunbar828984f2010-07-18 18:38:02 +0000153 /// Boolean tracking whether macro substitution is enabled.
Eli Benderskyc2f6f922013-01-14 18:08:41 +0000154 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000155
Toma Tabacu217116e2015-04-27 10:50:29 +0000156 /// \brief Keeps track of how many .macro's have been instantiated.
157 unsigned NumOfMacroInstantiations;
158
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000159 /// The values from the last parsed cpp hash file line comment if any.
Tim Northoverc0bef992016-04-13 19:46:54 +0000160 struct CppHashInfoTy {
161 StringRef Filename;
Andrew Kaylorca196472016-04-21 20:09:35 +0000162 int64_t LineNumber = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000163 SMLoc Loc;
Andrew Kaylorca196472016-04-21 20:09:35 +0000164 unsigned Buf = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000165 };
166 CppHashInfoTy CppHashInfo;
167
168 /// \brief List of forward directional labels for diagnosis at the end.
169 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
170
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000171 /// When generating dwarf for assembly source files we need to calculate the
172 /// logical line number based on the last parsed cpp hash file line comment
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000173 /// and current line. Since this is slow and messes up the SourceMgr's
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000174 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
175 SMLoc LastQueryIDLoc;
Alp Tokera55b95b2014-07-06 10:33:31 +0000176 unsigned LastQueryBuffer;
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000177 unsigned LastQueryLine;
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000178
Devang Patela173ee52012-01-31 18:14:05 +0000179 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000180 unsigned AssemblerDialect = ~0U;
Devang Patela173ee52012-01-31 18:14:05 +0000181
Jim Grosbach4b905842013-09-20 23:08:21 +0000182 /// \brief is Darwin compatibility enabled?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000183 bool IsDarwin = false;
Preston Gurd05500642012-09-19 20:36:12 +0000184
Jim Grosbach4b905842013-09-20 23:08:21 +0000185 /// \brief Are we parsing ms-style inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000186 bool ParsingInlineAsm = false;
Chad Rosier49963552012-10-13 00:26:04 +0000187
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000188public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000189 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000190 const MCAsmInfo &MAI, unsigned CB);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000191 AsmParser(const AsmParser &) = delete;
192 AsmParser &operator=(const AsmParser &) = delete;
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000193 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000194
Craig Topper59be68f2014-03-08 07:14:16 +0000195 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000196
Craig Topper59be68f2014-03-08 07:14:16 +0000197 void addDirectiveHandler(StringRef Directive,
198 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000199 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000200 }
201
Toma Tabacu11e14a92015-04-21 11:50:52 +0000202 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
203 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
204 }
205
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000206 /// @name MCAsmParser Interface
207 /// {
208
Craig Topper59be68f2014-03-08 07:14:16 +0000209 SourceMgr &getSourceManager() override { return SrcMgr; }
210 MCAsmLexer &getLexer() override { return Lexer; }
211 MCContext &getContext() override { return Ctx; }
212 MCStreamer &getStreamer() override { return Out; }
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000213
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000214 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
215
Craig Topper59be68f2014-03-08 07:14:16 +0000216 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000217 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000218 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000219 else
220 return AssemblerDialect;
221 }
Craig Topper59be68f2014-03-08 07:14:16 +0000222 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000223 AssemblerDialect = i;
224 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000225
Nirav Dave2364748a2016-09-16 18:30:20 +0000226 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
227 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
228 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000229
Craig Topper59be68f2014-03-08 07:14:16 +0000230 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000231
Yunzhong Gao27ea29b2016-09-02 23:15:29 +0000232 void setParsingInlineAsm(bool V) override {
233 ParsingInlineAsm = V;
234 Lexer.setParsingMSInlineAsm(V);
235 }
Craig Topper59be68f2014-03-08 07:14:16 +0000236 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000237
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000238 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000239 unsigned &NumOutputs, unsigned &NumInputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000240 SmallVectorImpl<std::pair<void *,bool>> &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000241 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000242 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000243 const MCInstrInfo *MII, const MCInstPrinter *IP,
244 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000245
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000246 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000247 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
248 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
249 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000250 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
251 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000252 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000253
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000254 /// \brief Parse a floating point expression using the float \p Semantics
255 /// and set \p Res to the value.
256 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
257
Jim Grosbach4b905842013-09-20 23:08:21 +0000258 /// \brief Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000259 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000260 bool parseIdentifier(StringRef &Res) override;
261 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000262
Nirav Davef43cc9f2016-10-10 15:24:54 +0000263 bool checkForValidSection() override;
Nirav Davea645433c2016-07-18 15:24:03 +0000264
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000265 /// }
266
267private:
Michael Zuckerman763e60e2017-05-04 10:37:00 +0000268 bool isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc);
Michael Zuckerman1f1a9122017-05-10 13:08:11 +0000269 void altMacroString(StringRef AltMacroStr, std::string &Res);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000270 bool parseStatement(ParseStatementInfo &Info,
271 MCAsmParserSemaCallback *SI);
Marina Yatsina5f5de9f2016-03-07 18:11:16 +0000272 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
Craig Topper3c76c522015-09-20 23:35:59 +0000273 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000274
Jim Grosbach4b905842013-09-20 23:08:21 +0000275 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000276 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000277 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000278 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000279 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000280 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000281
Eli Benderskya313ae62013-01-16 18:56:50 +0000282 /// \brief Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000283 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000284
285 /// \brief Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000286 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000287
Eli Benderskya313ae62013-01-16 18:56:50 +0000288 /// \brief Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000289 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000290
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000291 /// \brief Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000292 ///
293 /// \param M The macro.
294 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000295 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000296
297 /// \brief Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000298 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000299
David Majnemer91fc4c22014-01-29 18:57:46 +0000300 /// \brief Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000301 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000302
303 /// \brief Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000304 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000305
Jim Grosbach4b905842013-09-20 23:08:21 +0000306 void printMacroInstantiations();
307 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Nirav Dave2364748a2016-09-16 18:30:20 +0000308 SMRange Range = None) const {
309 ArrayRef<SMRange> Ranges(Range);
Chris Lattner72845262011-10-16 05:47:55 +0000310 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000311 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000312 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000313
Jim Grosbach4b905842013-09-20 23:08:21 +0000314 /// \brief Enter the specified file. This returns true on failure.
315 bool enterIncludeFile(const std::string &Filename);
316
317 /// \brief Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000318 /// This returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000319 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
320 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
Daniel Dunbar43235712010-07-18 18:54:11 +0000321
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000322 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000323 /// current token is not set; clients should ensure Lex() is called
324 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000325 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000326 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000327 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000328 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000329
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000330 /// \brief Parse up to the end of statement and a return the contents from the
331 /// current token until the end of the statement; the current token on exit
332 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000333 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000334
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000335 /// \brief Parse until the end of a statement or a comma is encountered,
336 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000337 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000338
Jim Grosbach4b905842013-09-20 23:08:21 +0000339 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +0000340 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000341
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000342 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
343 MCBinaryExpr::Opcode &Kind);
344
Jim Grosbach4b905842013-09-20 23:08:21 +0000345 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
346 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
347 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000348
Jim Grosbach4b905842013-09-20 23:08:21 +0000349 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000350
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000351 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
352 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
353
Eli Bendersky17233942013-01-15 22:59:42 +0000354 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000355 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000356 DK_NO_DIRECTIVE, // Placeholder
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000357 DK_SET,
358 DK_EQU,
359 DK_EQUIV,
360 DK_ASCII,
361 DK_ASCIZ,
362 DK_STRING,
363 DK_BYTE,
364 DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000365 DK_RELOC,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000366 DK_VALUE,
367 DK_2BYTE,
368 DK_LONG,
369 DK_INT,
370 DK_4BYTE,
371 DK_QUAD,
372 DK_8BYTE,
373 DK_OCTA,
374 DK_DC,
375 DK_DC_A,
376 DK_DC_B,
377 DK_DC_D,
378 DK_DC_L,
379 DK_DC_S,
380 DK_DC_W,
381 DK_DC_X,
382 DK_DCB,
383 DK_DCB_B,
384 DK_DCB_D,
385 DK_DCB_L,
386 DK_DCB_S,
387 DK_DCB_W,
388 DK_DCB_X,
389 DK_DS,
390 DK_DS_B,
391 DK_DS_D,
392 DK_DS_L,
393 DK_DS_P,
394 DK_DS_S,
395 DK_DS_W,
396 DK_DS_X,
397 DK_SINGLE,
398 DK_FLOAT,
399 DK_DOUBLE,
400 DK_ALIGN,
401 DK_ALIGN32,
402 DK_BALIGN,
403 DK_BALIGNW,
404 DK_BALIGNL,
405 DK_P2ALIGN,
406 DK_P2ALIGNW,
407 DK_P2ALIGNL,
408 DK_ORG,
409 DK_FILL,
410 DK_ENDR,
411 DK_BUNDLE_ALIGN_MODE,
412 DK_BUNDLE_LOCK,
413 DK_BUNDLE_UNLOCK,
414 DK_ZERO,
415 DK_EXTERN,
416 DK_GLOBL,
417 DK_GLOBAL,
418 DK_LAZY_REFERENCE,
419 DK_NO_DEAD_STRIP,
420 DK_SYMBOL_RESOLVER,
421 DK_PRIVATE_EXTERN,
422 DK_REFERENCE,
423 DK_WEAK_DEFINITION,
424 DK_WEAK_REFERENCE,
425 DK_WEAK_DEF_CAN_BE_HIDDEN,
426 DK_COMM,
427 DK_COMMON,
428 DK_LCOMM,
429 DK_ABORT,
430 DK_INCLUDE,
431 DK_INCBIN,
432 DK_CODE16,
433 DK_CODE16GCC,
434 DK_REPT,
435 DK_IRP,
436 DK_IRPC,
437 DK_IF,
438 DK_IFEQ,
439 DK_IFGE,
440 DK_IFGT,
441 DK_IFLE,
442 DK_IFLT,
443 DK_IFNE,
444 DK_IFB,
445 DK_IFNB,
446 DK_IFC,
447 DK_IFEQS,
448 DK_IFNC,
449 DK_IFNES,
450 DK_IFDEF,
451 DK_IFNDEF,
452 DK_IFNOTDEF,
453 DK_ELSEIF,
454 DK_ELSE,
455 DK_ENDIF,
456 DK_SPACE,
457 DK_SKIP,
458 DK_FILE,
459 DK_LINE,
460 DK_LOC,
461 DK_STABS,
462 DK_CV_FILE,
463 DK_CV_FUNC_ID,
464 DK_CV_INLINE_SITE_ID,
465 DK_CV_LOC,
466 DK_CV_LINETABLE,
467 DK_CV_INLINE_LINETABLE,
468 DK_CV_DEF_RANGE,
469 DK_CV_STRINGTABLE,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000470 DK_CV_FILECHECKSUMS,
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000471 DK_CV_FILECHECKSUM_OFFSET,
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000472 DK_CV_FPO_DATA,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000473 DK_CFI_SECTIONS,
474 DK_CFI_STARTPROC,
475 DK_CFI_ENDPROC,
476 DK_CFI_DEF_CFA,
477 DK_CFI_DEF_CFA_OFFSET,
478 DK_CFI_ADJUST_CFA_OFFSET,
479 DK_CFI_DEF_CFA_REGISTER,
480 DK_CFI_OFFSET,
481 DK_CFI_REL_OFFSET,
482 DK_CFI_PERSONALITY,
483 DK_CFI_LSDA,
484 DK_CFI_REMEMBER_STATE,
485 DK_CFI_RESTORE_STATE,
486 DK_CFI_SAME_VALUE,
487 DK_CFI_RESTORE,
488 DK_CFI_ESCAPE,
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000489 DK_CFI_RETURN_COLUMN,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000490 DK_CFI_SIGNAL_FRAME,
491 DK_CFI_UNDEFINED,
492 DK_CFI_REGISTER,
493 DK_CFI_WINDOW_SAVE,
494 DK_MACROS_ON,
495 DK_MACROS_OFF,
496 DK_ALTMACRO,
497 DK_NOALTMACRO,
498 DK_MACRO,
499 DK_EXITM,
500 DK_ENDM,
501 DK_ENDMACRO,
502 DK_PURGEM,
503 DK_SLEB128,
504 DK_ULEB128,
505 DK_ERR,
506 DK_ERROR,
507 DK_WARNING,
Coby Tayree01e53202017-10-02 14:36:31 +0000508 DK_PRINT,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000509 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000510 };
511
Jim Grosbach4b905842013-09-20 23:08:21 +0000512 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000513 /// directives parsed by this class.
514 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000515
516 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000517 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000518 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Nirav Dave1a9044b2016-10-24 14:35:29 +0000519 bool parseDirectiveValue(StringRef IDVal,
520 unsigned Size); // ".byte", ".long", ...
521 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
522 bool parseDirectiveRealValue(StringRef IDVal,
523 const fltSemantics &); // ".single", ...
Jim Grosbach4b905842013-09-20 23:08:21 +0000524 bool parseDirectiveFill(); // ".fill"
525 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000526 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000527 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
528 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000529 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000530 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000531
Eli Bendersky17233942013-01-15 22:59:42 +0000532 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000533 bool parseDirectiveFile(SMLoc DirectiveLoc);
534 bool parseDirectiveLine();
535 bool parseDirectiveLoc();
536 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000537
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000538 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
539 // ".cv_inline_linetable", ".cv_def_range"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000540 bool parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000541 bool parseDirectiveCVFuncId();
542 bool parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000543 bool parseDirectiveCVLoc();
544 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000545 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000546 bool parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000547 bool parseDirectiveCVStringTable();
548 bool parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000549 bool parseDirectiveCVFileChecksumOffset();
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000550 bool parseDirectiveCVFPOData();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000551
Eli Bendersky17233942013-01-15 22:59:42 +0000552 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000553 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000554 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000555 bool parseDirectiveCFISections();
556 bool parseDirectiveCFIStartProc();
557 bool parseDirectiveCFIEndProc();
558 bool parseDirectiveCFIDefCfaOffset();
559 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
560 bool parseDirectiveCFIAdjustCfaOffset();
561 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
562 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
563 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
564 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
565 bool parseDirectiveCFIRememberState();
566 bool parseDirectiveCFIRestoreState();
567 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
568 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
569 bool parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000570 bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +0000571 bool parseDirectiveCFISignalFrame();
572 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000573
574 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000575 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000576 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000577 bool parseDirectiveEndMacro(StringRef Directive);
578 bool parseDirectiveMacro(SMLoc DirectiveLoc);
579 bool parseDirectiveMacrosOnOff(StringRef Directive);
Michael Zuckerman56704612017-05-01 13:20:12 +0000580 // alternate macro mode directives
581 bool parseDirectiveAltmacro(StringRef Directive);
Eli Benderskyf483ff92012-12-20 19:05:53 +0000582 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000583 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000584 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000585 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000586 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000587 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000588
Eli Bendersky17233942013-01-15 22:59:42 +0000589 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000590 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000591
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000592 // ".dcb"
593 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
594 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
Petr Hosek85b2f672016-09-23 21:53:36 +0000595 // ".ds"
596 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000597
Eli Bendersky17233942013-01-15 22:59:42 +0000598 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000599 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000600
Jim Grosbach4b905842013-09-20 23:08:21 +0000601 /// \brief Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000602 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000603 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000604
Jim Grosbach4b905842013-09-20 23:08:21 +0000605 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000606
Jim Grosbach4b905842013-09-20 23:08:21 +0000607 bool parseDirectiveAbort(); // ".abort"
608 bool parseDirectiveInclude(); // ".include"
609 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000610
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000611 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
612 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000613 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000614 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000615 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000616 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000617 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
618 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000619 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000620 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
621 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
622 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
623 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000624 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000625
Jim Grosbach4b905842013-09-20 23:08:21 +0000626 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000627 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000628
Rafael Espindola34b9c512012-06-03 23:57:14 +0000629 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000630 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
631 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000632 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000633 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000634 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
635 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
636 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000637
Chad Rosierc7f552c2013-02-12 21:33:51 +0000638 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000639 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000640 size_t Len);
641
642 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000643 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000644
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000645 // "end"
646 bool parseDirectiveEnd(SMLoc DirectiveLoc);
647
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000648 // ".err" or ".error"
649 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000650
Nico Weber404012b2014-07-24 16:26:06 +0000651 // ".warning"
652 bool parseDirectiveWarning(SMLoc DirectiveLoc);
653
Coby Tayree01e53202017-10-02 14:36:31 +0000654 // .print <double-quotes-string>
655 bool parseDirectivePrint(SMLoc DirectiveLoc);
656
Eli Bendersky17233942013-01-15 22:59:42 +0000657 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000658};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000659
660} // end anonymous namespace
Daniel Dunbar86033402010-07-12 17:54:38 +0000661
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000662namespace llvm {
663
664extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000665extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000666extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000667
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000668} // end namespace llvm
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000669
Chris Lattnerc35681b2010-01-19 19:46:13 +0000670enum { DEFAULT_ADDRSPACE = 0 };
671
David Blaikie9f380a32015-03-16 18:06:57 +0000672AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000673 const MCAsmInfo &MAI, unsigned CB = 0)
David Blaikie9f380a32015-03-16 18:06:57 +0000674 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000675 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
Nirav Dave2364748a2016-09-16 18:30:20 +0000676 HadError = false;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000677 // Save the old handler.
678 SavedDiagHandler = SrcMgr.getDiagHandler();
679 SavedDiagContext = SrcMgr.getDiagContext();
680 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000681 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000682 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000683
Daniel Dunbarc5011082010-07-12 18:12:02 +0000684 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000685 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
686 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000687 PlatformParser.reset(createCOFFAsmParser());
688 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000689 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000690 PlatformParser.reset(createDarwinAsmParser());
691 IsDarwin = true;
692 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000693 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000694 PlatformParser.reset(createELFAsmParser());
695 break;
Dan Gohman18eafb62017-02-22 01:23:18 +0000696 case MCObjectFileInfo::IsWasm:
697 llvm_unreachable("Wasm parsing not supported yet");
698 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000699 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000700
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000701 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000702 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000703
704 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000705}
706
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000707AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000708 assert((HadError || ActiveMacros.empty()) &&
709 "Unexpected active macro instantiation!");
Sanne Wouda29338752017-02-08 14:48:05 +0000710
711 // Restore the saved diagnostics handler and context for use during
712 // finalization.
713 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000714}
715
Jim Grosbach4b905842013-09-20 23:08:21 +0000716void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000717 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000718 for (std::vector<MacroInstantiation *>::const_reverse_iterator
719 it = ActiveMacros.rbegin(),
720 ie = ActiveMacros.rend();
721 it != ie; ++it)
722 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000723 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000724}
725
Nirav Dave2364748a2016-09-16 18:30:20 +0000726void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
727 printPendingErrors();
728 printMessage(L, SourceMgr::DK_Note, Msg, Range);
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000729 printMacroInstantiations();
730}
731
Nirav Dave2364748a2016-09-16 18:30:20 +0000732bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000733 if(getTargetParser().getTargetOptions().MCNoWarn)
734 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000735 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Nirav Dave2364748a2016-09-16 18:30:20 +0000736 return Error(L, Msg, Range);
737 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000738 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000739 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000740}
741
Nirav Dave2364748a2016-09-16 18:30:20 +0000742bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000743 HadError = true;
Nirav Dave2364748a2016-09-16 18:30:20 +0000744 printMessage(L, SourceMgr::DK_Error, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000745 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000746 return true;
747}
748
Jim Grosbach4b905842013-09-20 23:08:21 +0000749bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000750 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000751 unsigned NewBuf =
752 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
753 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000754 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000755
Sean Callanan7a77eae2010-01-21 00:19:58 +0000756 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000757 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000758 return false;
759}
Daniel Dunbar43235712010-07-18 18:54:11 +0000760
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000761/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000762/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000763/// returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000764bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
765 const MCExpr *Count, SMLoc Loc) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000766 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000767 unsigned NewBuf =
768 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
769 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000770 return true;
771
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000772 // Pick up the bytes from the file and emit them.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000773 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
774 Bytes = Bytes.drop_front(Skip);
775 if (Count) {
776 int64_t Res;
777 if (!Count->evaluateAsAbsolute(Res))
778 return Error(Loc, "expected absolute expression");
779 if (Res < 0)
780 return Warning(Loc, "negative count has no effect");
781 Bytes = Bytes.take_front(Res);
782 }
783 getStreamer().EmitBytes(Bytes);
Kevin Enderby109f25c2011-12-14 21:47:48 +0000784 return false;
785}
786
Alp Tokera55b95b2014-07-06 10:33:31 +0000787void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
788 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000789 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
790 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000791}
792
Sean Callanan7a77eae2010-01-21 00:19:58 +0000793const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000794 if (Lexer.getTok().is(AsmToken::Error))
795 Error(Lexer.getErrLoc(), Lexer.getErr());
796
Nirav Dave53a72f42016-07-11 12:42:14 +0000797 // if it's a end of statement with a comment in it
798 if (getTok().is(AsmToken::EndOfStatement)) {
799 // if this is a line comment output it.
Nirav Dave670109d2017-06-09 14:04:03 +0000800 if (!getTok().getString().empty() && getTok().getString().front() != '\n' &&
Nirav Dave53a72f42016-07-11 12:42:14 +0000801 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
802 Out.addExplicitComment(Twine(getTok().getString()));
803 }
804
Sean Callanan7a77eae2010-01-21 00:19:58 +0000805 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000806
807 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000808 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000809 if (MAI.preserveAsmComments())
810 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000811 tok = &Lexer.Lex();
812 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000813
Sean Callanan7a77eae2010-01-21 00:19:58 +0000814 if (tok->is(AsmToken::Eof)) {
815 // If this is the end of an included file, pop the parent file off the
816 // include stack.
817 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
818 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000819 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000820 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000821 }
822 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000823
Sean Callanan7a77eae2010-01-21 00:19:58 +0000824 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000825}
826
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000827bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000828 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000829 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000830 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000831
Chris Lattner36e02122009-06-21 20:54:55 +0000832 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000833 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000834
835 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000836 AsmCond StartingCondState = TheCondState;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000837 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000838
Kevin Enderby6469fc22011-11-01 22:27:22 +0000839 // If we are generating dwarf for assembly source files save the initial text
840 // section and generate a .file directive.
841 if (getContext().getGenDwarfForAssembly()) {
Eric Christopher445c9522016-10-14 05:47:37 +0000842 MCSection *Sec = getStreamer().getCurrentSectionOnly();
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000843 if (!Sec->getBeginSymbol()) {
844 MCSymbol *SectionStartSym = getContext().createTempSymbol();
845 getStreamer().EmitLabel(SectionStartSym);
846 Sec->setBeginSymbol(SectionStartSym);
847 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000848 bool InsertResult = getContext().addGenDwarfSection(Sec);
849 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000850 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000851 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
852 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000853 }
854
Chris Lattner73f36112009-07-02 21:53:43 +0000855 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000856 while (Lexer.isNot(AsmToken::Eof)) {
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000857 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000858 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000859 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000860
Nirav Dave2364748a2016-09-16 18:30:20 +0000861 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
862 // for printing ErrMsg via Lex() only if no (presumably better) parser error
863 // exists.
864 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
Nirav Dave1180e6892016-06-02 17:15:05 +0000865 Lex();
866 }
867
Nirav Dave2364748a2016-09-16 18:30:20 +0000868 // parseStatement returned true so may need to emit an error.
869 printPendingErrors();
870
871 // Skipping to the next line if needed.
872 if (!getLexer().isAtStartOfStatement())
873 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000874 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000875
Nirav Dave2364748a2016-09-16 18:30:20 +0000876 // All errors should have been emitted.
877 assert(!hasPendingError() && "unexpected error from parseStatement");
878
Oliver Stannard21718282016-07-26 14:19:47 +0000879 getTargetParser().flushPendingInstructions(getStreamer());
880
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000881 if (TheCondState.TheCond != StartingCondState.TheCond ||
882 TheCondState.Ignore != StartingCondState.Ignore)
Nirav Dave2364748a2016-09-16 18:30:20 +0000883 printError(getTok().getLoc(), "unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000884 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000885 const auto &LineTables = getContext().getMCDwarfLineTables();
886 if (!LineTables.empty()) {
887 unsigned Index = 0;
888 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
889 if (File.Name.empty() && Index != 0)
Nirav Dave2364748a2016-09-16 18:30:20 +0000890 printError(getTok().getLoc(), "unassigned file number: " +
891 Twine(Index) +
892 " for .file directives");
David Blaikie8bf66c42014-04-01 07:35:52 +0000893 ++Index;
894 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000895 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000896
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000897 // Check to see that all assembler local symbols were actually defined.
898 // Targets that don't do subsections via symbols may not want this, though,
899 // so conservatively exclude them. Only do this if we're finalizing, though,
900 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000901 if (!NoFinalize) {
902 if (MAI.hasSubsectionsViaSymbols()) {
903 for (const auto &TableEntry : getContext().getSymbols()) {
904 MCSymbol *Sym = TableEntry.getValue();
905 // Variable symbols may not be marked as defined, so check those
906 // explicitly. If we know it's a variable, we have a definition for
907 // the purposes of this check.
908 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
909 // FIXME: We would really like to refer back to where the symbol was
910 // first referenced for a source location. We need to add something
911 // to track that. Currently, we just point to the end of the file.
Nirav Dave2364748a2016-09-16 18:30:20 +0000912 printError(getTok().getLoc(), "assembler local symbol '" +
913 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000914 }
915 }
916
917 // Temporary symbols like the ones for directional jumps don't go in the
918 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000919 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
920 if (std::get<2>(LocSym)->isUndefined()) {
921 // Reset the state of any "# line file" directives we've seen to the
922 // context as it was at the diagnostic site.
923 CppHashInfo = std::get<1>(LocSym);
Nirav Dave2364748a2016-09-16 18:30:20 +0000924 printError(std::get<0>(LocSym), "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000925 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000926 }
927 }
928
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000929 // Finalize the output stream if there are no errors and if the client wants
930 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000931 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000932 Out.Finish();
933
Oliver Stannard07b43d32015-11-17 09:58:07 +0000934 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000935}
936
Nirav Davef43cc9f2016-10-10 15:24:54 +0000937bool AsmParser::checkForValidSection() {
Eric Christopher445c9522016-10-14 05:47:37 +0000938 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000939 Out.InitSections(false);
Nirav Davef43cc9f2016-10-10 15:24:54 +0000940 return Error(getTok().getLoc(),
941 "expected section directive before assembly directive");
Daniel Dunbare5444a82010-09-09 22:42:59 +0000942 }
Nirav Davef43cc9f2016-10-10 15:24:54 +0000943 return false;
Daniel Dunbare5444a82010-09-09 22:42:59 +0000944}
945
Jim Grosbach4b905842013-09-20 23:08:21 +0000946/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000947void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000948 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000949 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000950
Chris Lattnere5074c42009-06-22 01:29:09 +0000951 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000952 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000953 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000954}
955
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000956StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000957 const char *Start = getTok().getLoc().getPointer();
958
Jim Grosbach4b905842013-09-20 23:08:21 +0000959 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000960 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000961
962 const char *End = getTok().getLoc().getPointer();
963 return StringRef(Start, End - Start);
964}
Chris Lattner78db3622009-06-22 05:51:26 +0000965
Jim Grosbach4b905842013-09-20 23:08:21 +0000966StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000967 const char *Start = getTok().getLoc().getPointer();
968
969 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000970 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000971 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000972
973 const char *End = getTok().getLoc().getPointer();
974 return StringRef(Start, End - Start);
975}
976
Jim Grosbach4b905842013-09-20 23:08:21 +0000977/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000978/// NOTE: This assumes the leading '(' has already been consumed.
979///
980/// parenexpr ::= expr)
981///
Jim Grosbach4b905842013-09-20 23:08:21 +0000982bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
983 if (parseExpression(Res))
984 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000985 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +0000986 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000987 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000988 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +0000989 return false;
990}
Chris Lattner78db3622009-06-22 05:51:26 +0000991
Jim Grosbach4b905842013-09-20 23:08:21 +0000992/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000993/// NOTE: This assumes the leading '[' has already been consumed.
994///
995/// bracketexpr ::= expr]
996///
Jim Grosbach4b905842013-09-20 23:08:21 +0000997bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
998 if (parseExpression(Res))
999 return true;
Nirav Davea645433c2016-07-18 15:24:03 +00001000 EndLoc = getTok().getEndLoc();
1001 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
1002 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001003 return false;
1004}
1005
Jim Grosbach4b905842013-09-20 23:08:21 +00001006/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001007/// primaryexpr ::= (parenexpr
1008/// primaryexpr ::= symbol
1009/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +00001010/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +00001011/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +00001012bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001013 SMLoc FirstTokenLoc = getLexer().getLoc();
1014 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
1015 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +00001016 default:
1017 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +00001018 // If we have an error assume that we've already handled it.
1019 case AsmToken::Error:
1020 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001021 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001022 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001023 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001024 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001025 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001026 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +00001027 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +00001028 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00001029 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +00001030 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +00001031 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001032 if (parseIdentifier(Identifier)) {
Nirav Daved0463322016-10-12 13:58:07 +00001033 // We may have failed but $ may be a valid token.
1034 if (getTok().is(AsmToken::Dollar)) {
David Majnemer0c58bc62013-09-25 10:47:21 +00001035 if (Lexer.getMAI().getDollarIsPC()) {
Nirav Daved0463322016-10-12 13:58:07 +00001036 Lex();
David Majnemer0c58bc62013-09-25 10:47:21 +00001037 // This is a '$' reference, which references the current PC. Emit a
1038 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001039 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +00001040 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001041 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +00001042 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +00001043 EndLoc = FirstTokenLoc;
1044 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +00001045 }
1046 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +00001047 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001048 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001049 // Parse symbol variant
1050 std::pair<StringRef, StringRef> Split;
1051 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +00001052 if (FirstTokenKind == AsmToken::String) {
1053 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +00001054 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +00001055 SMLoc AtLoc = getLexer().getLoc();
1056 StringRef VName;
1057 if (parseIdentifier(VName))
1058 return Error(AtLoc, "expected symbol variant after '@'");
1059
1060 Split = std::make_pair(Identifier, VName);
1061 }
1062 } else {
1063 Split = Identifier.split('@');
1064 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001065 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +00001066 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +00001067 StringRef VName;
1068 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +00001069 // eat ')'.
1070 if (parseToken(AsmToken::RParen,
1071 "unexpected token in variant, expected ')'"))
1072 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +00001073 Split = std::make_pair(Identifier, VName);
1074 }
Daniel Dunbar24764322010-08-24 19:13:42 +00001075
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001076 EndLoc = SMLoc::getFromPointer(Identifier.end());
1077
Daniel Dunbard20cda02009-10-16 01:34:54 +00001078 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +00001079 StringRef SymbolName = Identifier;
Weiming Zhaocf26d562016-12-01 18:00:36 +00001080 if (SymbolName.empty())
1081 return true;
1082
Hans Wennborgce69d772013-10-18 20:46:28 +00001083 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +00001084
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001085 // Lookup the symbol variant if used.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001086 if (!Split.second.empty()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001087 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +00001088 if (Variant != MCSymbolRefExpr::VK_Invalid) {
1089 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +00001090 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +00001091 Variant = MCSymbolRefExpr::VK_None;
1092 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +00001093 return Error(SMLoc::getFromPointer(Split.second.begin()),
1094 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001095 }
1096 }
Daniel Dunbar55992562010-03-15 23:51:06 +00001097
Jim Grosbach6f482002015-05-18 18:43:14 +00001098 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +00001099
Daniel Dunbard20cda02009-10-16 01:34:54 +00001100 // If this is an absolute variable reference, substitute it now to preserve
1101 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +00001102 if (Sym->isVariable() &&
1103 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +00001104 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +00001105 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +00001106
Vedant Kumar86dbd922015-08-31 17:44:53 +00001107 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +00001108 return false;
1109 }
1110
1111 // Otherwise create a symbol ref.
Chad Rosier9245e122017-01-19 20:06:32 +00001112 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
Chris Lattner78db3622009-06-22 05:51:26 +00001113 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001114 }
David Woodhousef42a6662014-02-01 16:20:54 +00001115 case AsmToken::BigNum:
1116 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001117 case AsmToken::Integer: {
1118 SMLoc Loc = getTok().getLoc();
1119 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001120 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001121 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001122 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001123 // Look for 'b' or 'f' following an Integer as a directional label
1124 if (Lexer.getKind() == AsmToken::Identifier) {
1125 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001126 // Lookup the symbol variant if used.
1127 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1128 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1129 if (Split.first.size() != IDVal.size()) {
1130 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001131 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001132 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001133 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001134 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001135 if (IDVal == "f" || IDVal == "b") {
1136 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001137 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001138 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001139 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001140 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001141 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001142 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001143 Lex(); // Eat identifier.
1144 }
1145 }
Chris Lattner78db3622009-06-22 05:51:26 +00001146 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001147 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001148 case AsmToken::Real: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001149 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001150 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001151 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001152 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001153 Lex(); // Eat token.
1154 return false;
1155 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001156 case AsmToken::Dot: {
1157 // This is a '.' reference, which references the current PC. Emit a
1158 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001159 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001160 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001161 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001162 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001163 Lex(); // Eat identifier.
1164 return false;
1165 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001166 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001167 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001168 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001169 case AsmToken::LBrac:
1170 if (!PlatformParser->HasBracketExpressions())
1171 return TokError("brackets expression not supported on this target");
1172 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001173 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001174 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001175 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001176 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001177 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001178 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001179 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001180 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001181 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001182 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001183 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001184 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001185 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001186 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001187 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001188 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001189 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001190 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001191 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001192 // MIPS unary expression operators. The lexer won't generate these tokens if
1193 // MCAsmInfo::HasMipsExpressions is false for the target.
1194 case AsmToken::PercentCall16:
1195 case AsmToken::PercentCall_Hi:
1196 case AsmToken::PercentCall_Lo:
1197 case AsmToken::PercentDtprel_Hi:
1198 case AsmToken::PercentDtprel_Lo:
1199 case AsmToken::PercentGot:
1200 case AsmToken::PercentGot_Disp:
1201 case AsmToken::PercentGot_Hi:
1202 case AsmToken::PercentGot_Lo:
1203 case AsmToken::PercentGot_Ofst:
1204 case AsmToken::PercentGot_Page:
1205 case AsmToken::PercentGottprel:
1206 case AsmToken::PercentGp_Rel:
1207 case AsmToken::PercentHi:
1208 case AsmToken::PercentHigher:
1209 case AsmToken::PercentHighest:
1210 case AsmToken::PercentLo:
1211 case AsmToken::PercentNeg:
1212 case AsmToken::PercentPcrel_Hi:
1213 case AsmToken::PercentPcrel_Lo:
1214 case AsmToken::PercentTlsgd:
1215 case AsmToken::PercentTlsldm:
1216 case AsmToken::PercentTprel_Hi:
1217 case AsmToken::PercentTprel_Lo:
1218 Lex(); // Eat the operator.
1219 if (Lexer.isNot(AsmToken::LParen))
1220 return TokError("expected '(' after operator");
1221 Lex(); // Eat the operator.
1222 if (parseExpression(Res, EndLoc))
1223 return true;
1224 if (Lexer.isNot(AsmToken::RParen))
1225 return TokError("expected ')'");
1226 Lex(); // Eat the operator.
1227 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1228 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001229 }
1230}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001231
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001232bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001233 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001234 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001235}
1236
Daniel Dunbar55f16672010-09-17 02:47:07 +00001237const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001238AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001239 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001240 // Ask the target implementation about this expression first.
1241 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1242 if (NewE)
1243 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001244 // Recurse over the given expression, rebuilding it to apply the given variant
1245 // if there is exactly one symbol.
1246 switch (E->getKind()) {
1247 case MCExpr::Target:
1248 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001249 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001250
1251 case MCExpr::SymbolRef: {
1252 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1253
1254 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001255 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1256 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001257 return E;
1258 }
1259
Jim Grosbach13760bd2015-05-30 01:25:56 +00001260 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001261 }
1262
1263 case MCExpr::Unary: {
1264 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001265 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001266 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001267 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001268 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001269 }
1270
1271 case MCExpr::Binary: {
1272 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001273 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1274 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001275
1276 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001277 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001278
Jim Grosbach4b905842013-09-20 23:08:21 +00001279 if (!LHS)
1280 LHS = BE->getLHS();
1281 if (!RHS)
1282 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001283
Jim Grosbach13760bd2015-05-30 01:25:56 +00001284 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001285 }
1286 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001287
Craig Toppera2886c22012-02-07 05:05:23 +00001288 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001289}
1290
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001291/// This function checks if the next token is <string> type or arithmetic.
1292/// string that begin with character '<' must end with character '>'.
1293/// otherwise it is arithmetics.
1294/// If the function returns a 'true' value,
1295/// the End argument will be filled with the last location pointed to the '>'
1296/// character.
1297
1298/// There is a gap between the AltMacro's documentation and the single quote implementation.
1299/// GCC does not fully support this feature and so we will not support it.
1300/// TODO: Adding single quote as a string.
1301bool AsmParser::isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc) {
1302 assert((StrLoc.getPointer() != NULL) &&
1303 "Argument to the function cannot be a NULL value");
1304 const char *CharPtr = StrLoc.getPointer();
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001305 while ((*CharPtr != '>') && (*CharPtr != '\n') && (*CharPtr != '\r') &&
1306 (*CharPtr != '\0')) {
1307 if (*CharPtr == '!')
1308 CharPtr++;
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001309 CharPtr++;
1310 }
1311 if (*CharPtr == '>') {
1312 EndLoc = StrLoc.getFromPointer(CharPtr + 1);
1313 return true;
1314 }
1315 return false;
1316}
1317
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001318/// \brief creating a string without the escape characters '!'.
1319void AsmParser::altMacroString(StringRef AltMacroStr,std::string &Res) {
Michael Zuckermanff298792017-05-10 14:00:57 +00001320 for (size_t Pos = 0; Pos < AltMacroStr.size(); Pos++) {
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001321 if (AltMacroStr[Pos] == '!')
1322 Pos++;
1323 Res += AltMacroStr[Pos];
1324 }
1325}
1326
Jim Grosbach4b905842013-09-20 23:08:21 +00001327/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001328///
Jim Grosbachbd164242011-08-20 16:24:13 +00001329/// expr ::= expr &&,|| expr -> lowest.
1330/// expr ::= expr |,^,&,! expr
1331/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1332/// expr ::= expr <<,>> expr
1333/// expr ::= expr +,- expr
1334/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001335/// expr ::= primaryexpr
1336///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001337bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001338 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001339 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001340 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001341 return true;
1342
Daniel Dunbar55f16672010-09-17 02:47:07 +00001343 // As a special case, we support 'a op b @ modifier' by rewriting the
1344 // expression to include the modifier. This is inefficient, but in general we
1345 // expect users to use 'a@modifier op b'.
1346 if (Lexer.getKind() == AsmToken::At) {
1347 Lex();
1348
1349 if (Lexer.isNot(AsmToken::Identifier))
1350 return TokError("unexpected symbol modifier following '@'");
1351
1352 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001353 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001354 if (Variant == MCSymbolRefExpr::VK_Invalid)
1355 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1356
Jim Grosbach4b905842013-09-20 23:08:21 +00001357 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001358 if (!ModifiedRes) {
1359 return TokError("invalid modifier '" + getTok().getIdentifier() +
1360 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001361 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001362
Daniel Dunbar55f16672010-09-17 02:47:07 +00001363 Res = ModifiedRes;
1364 Lex();
1365 }
1366
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001367 // Try to constant fold it up front, if possible.
1368 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001369 if (Res->evaluateAsAbsolute(Value))
1370 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001371
1372 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001373}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001374
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001375bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001376 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001377 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001378}
1379
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001380bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1381 SMLoc &EndLoc) {
1382 if (parseParenExpr(Res, EndLoc))
1383 return true;
1384
1385 for (; ParenDepth > 0; --ParenDepth) {
1386 if (parseBinOpRHS(1, Res, EndLoc))
1387 return true;
1388
1389 // We don't Lex() the last RParen.
1390 // This is the same behavior as parseParenExpression().
1391 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001392 EndLoc = getTok().getEndLoc();
1393 if (parseToken(AsmToken::RParen,
1394 "expected ')' in parentheses expression"))
1395 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001396 }
1397 }
1398 return false;
1399}
1400
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001401bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001402 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001403
Daniel Dunbar75630b32009-06-30 02:10:03 +00001404 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001405 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001406 return true;
1407
Jim Grosbach13760bd2015-05-30 01:25:56 +00001408 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001409 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001410
1411 return false;
1412}
1413
David Majnemer0993e0b2015-10-26 03:15:34 +00001414static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1415 MCBinaryExpr::Opcode &Kind,
1416 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001417 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001418 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001419 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001420
Jim Grosbach4b905842013-09-20 23:08:21 +00001421 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001422 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001423 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001424 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001425 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001426 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001427 return 1;
1428
Jim Grosbach4b905842013-09-20 23:08:21 +00001429 // Low Precedence: |, &, ^
1430 //
1431 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001432 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001433 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001434 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001435 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001436 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001437 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001438 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001439 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001440 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001441
Jim Grosbach4b905842013-09-20 23:08:21 +00001442 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001443 case AsmToken::EqualEqual:
1444 Kind = MCBinaryExpr::EQ;
1445 return 3;
1446 case AsmToken::ExclaimEqual:
1447 case AsmToken::LessGreater:
1448 Kind = MCBinaryExpr::NE;
1449 return 3;
1450 case AsmToken::Less:
1451 Kind = MCBinaryExpr::LT;
1452 return 3;
1453 case AsmToken::LessEqual:
1454 Kind = MCBinaryExpr::LTE;
1455 return 3;
1456 case AsmToken::Greater:
1457 Kind = MCBinaryExpr::GT;
1458 return 3;
1459 case AsmToken::GreaterEqual:
1460 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001461 return 3;
1462
Jim Grosbach4b905842013-09-20 23:08:21 +00001463 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001464 case AsmToken::LessLess:
1465 Kind = MCBinaryExpr::Shl;
1466 return 4;
1467 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001468 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001469 return 4;
1470
Jim Grosbach4b905842013-09-20 23:08:21 +00001471 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001472 case AsmToken::Plus:
1473 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001474 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001475 case AsmToken::Minus:
1476 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001477 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001478
Jim Grosbach4b905842013-09-20 23:08:21 +00001479 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001480 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001481 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001482 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001483 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001484 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001485 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001486 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001487 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001488 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001489 }
1490}
1491
David Majnemer0993e0b2015-10-26 03:15:34 +00001492static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1493 MCBinaryExpr::Opcode &Kind,
1494 bool ShouldUseLogicalShr) {
1495 switch (K) {
1496 default:
1497 return 0; // not a binop.
1498
1499 // Lowest Precedence: &&, ||
1500 case AsmToken::AmpAmp:
1501 Kind = MCBinaryExpr::LAnd;
1502 return 2;
1503 case AsmToken::PipePipe:
1504 Kind = MCBinaryExpr::LOr;
1505 return 1;
1506
1507 // Low Precedence: ==, !=, <>, <, <=, >, >=
1508 case AsmToken::EqualEqual:
1509 Kind = MCBinaryExpr::EQ;
1510 return 3;
1511 case AsmToken::ExclaimEqual:
1512 case AsmToken::LessGreater:
1513 Kind = MCBinaryExpr::NE;
1514 return 3;
1515 case AsmToken::Less:
1516 Kind = MCBinaryExpr::LT;
1517 return 3;
1518 case AsmToken::LessEqual:
1519 Kind = MCBinaryExpr::LTE;
1520 return 3;
1521 case AsmToken::Greater:
1522 Kind = MCBinaryExpr::GT;
1523 return 3;
1524 case AsmToken::GreaterEqual:
1525 Kind = MCBinaryExpr::GTE;
1526 return 3;
1527
1528 // Low Intermediate Precedence: +, -
1529 case AsmToken::Plus:
1530 Kind = MCBinaryExpr::Add;
1531 return 4;
1532 case AsmToken::Minus:
1533 Kind = MCBinaryExpr::Sub;
1534 return 4;
1535
1536 // High Intermediate Precedence: |, &, ^
1537 //
1538 // FIXME: gas seems to support '!' as an infix operator?
1539 case AsmToken::Pipe:
1540 Kind = MCBinaryExpr::Or;
1541 return 5;
1542 case AsmToken::Caret:
1543 Kind = MCBinaryExpr::Xor;
1544 return 5;
1545 case AsmToken::Amp:
1546 Kind = MCBinaryExpr::And;
1547 return 5;
1548
1549 // Highest Precedence: *, /, %, <<, >>
1550 case AsmToken::Star:
1551 Kind = MCBinaryExpr::Mul;
1552 return 6;
1553 case AsmToken::Slash:
1554 Kind = MCBinaryExpr::Div;
1555 return 6;
1556 case AsmToken::Percent:
1557 Kind = MCBinaryExpr::Mod;
1558 return 6;
1559 case AsmToken::LessLess:
1560 Kind = MCBinaryExpr::Shl;
1561 return 6;
1562 case AsmToken::GreaterGreater:
1563 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1564 return 6;
1565 }
1566}
1567
1568unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1569 MCBinaryExpr::Opcode &Kind) {
1570 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1571 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1572 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1573}
1574
Jim Grosbach4b905842013-09-20 23:08:21 +00001575/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001576/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001577bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001578 SMLoc &EndLoc) {
Chad Rosier9245e122017-01-19 20:06:32 +00001579 SMLoc StartLoc = Lexer.getLoc();
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001580 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001581 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001582 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001583
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001584 // If the next token is lower precedence than we are allowed to eat, return
1585 // successfully with what we ate already.
1586 if (TokPrec < Precedence)
1587 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001588
Sean Callanan686ed8d2010-01-19 20:22:31 +00001589 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001590
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001591 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001592 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001593 if (parsePrimaryExpr(RHS, EndLoc))
1594 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001595
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001596 // If BinOp binds less tightly with RHS than the operator after RHS, let
1597 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001598 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001599 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001600 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1601 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001602
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001603 // Merge LHS and RHS according to operator.
Chad Rosier9245e122017-01-19 20:06:32 +00001604 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001605 }
1606}
1607
Chris Lattner36e02122009-06-21 20:54:55 +00001608/// ParseStatement:
1609/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001610/// ::= Label* Directive ...Operands... EndOfStatement
1611/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001612bool AsmParser::parseStatement(ParseStatementInfo &Info,
1613 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001614 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001615 // Eat initial spaces and comments
1616 while (Lexer.is(AsmToken::Space))
1617 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001618 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001619 // if this is a line comment we can drop it safely
Nirav Dave670109d2017-06-09 14:04:03 +00001620 if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
Nirav Davefd910412016-06-17 16:06:17 +00001621 getTok().getString().front() == '\n')
1622 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001623 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001624 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001625 }
Nirav Davefd910412016-06-17 16:06:17 +00001626 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001627 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001628 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001629 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001630 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001631 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001632 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001633 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001634 if (Lexer.is(AsmToken::Integer)) {
1635 LocalLabelVal = getTok().getIntVal();
1636 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001637 if (!TheCondState.Ignore) {
1638 Lex(); // always eat a token
1639 return Error(IDLoc, "unexpected token at start of statement");
1640 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001641 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001642 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001643 IDVal = getTok().getString();
1644 Lex(); // Consume the integer token to be used as an identifier token.
1645 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001646 if (!TheCondState.Ignore) {
1647 Lex(); // always eat a token
1648 return Error(IDLoc, "unexpected token at start of statement");
1649 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001650 }
1651 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001652 } else if (Lexer.is(AsmToken::Dot)) {
1653 // Treat '.' as a valid identifier in this context.
1654 Lex();
1655 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001656 } else if (Lexer.is(AsmToken::LCurly)) {
1657 // Treat '{' as a valid identifier in this context.
1658 Lex();
1659 IDVal = "{";
1660
1661 } else if (Lexer.is(AsmToken::RCurly)) {
1662 // Treat '}' as a valid identifier in this context.
1663 Lex();
1664 IDVal = "}";
Yonghong Song06ff6552017-09-12 17:55:23 +00001665 } else if (Lexer.is(AsmToken::Star) &&
1666 getTargetParser().starIsStartOfStatement()) {
1667 // Accept '*' as a valid start of statement.
1668 Lex();
1669 IDVal = "*";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001670 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001671 if (!TheCondState.Ignore) {
1672 Lex(); // always eat a token
1673 return Error(IDLoc, "unexpected token at start of statement");
1674 }
Chris Lattner926885c2010-04-17 18:14:27 +00001675 IDVal = "";
1676 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001677
Chris Lattner926885c2010-04-17 18:14:27 +00001678 // Handle conditional assembly here before checking for skipping. We
1679 // have to do this so that .endif isn't skipped in a ".if 0" block for
1680 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001681 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001682 DirectiveKindMap.find(IDVal);
1683 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1684 ? DK_NO_DIRECTIVE
1685 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001686 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001687 default:
1688 break;
1689 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001690 case DK_IFEQ:
1691 case DK_IFGE:
1692 case DK_IFGT:
1693 case DK_IFLE:
1694 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001695 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001696 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001697 case DK_IFB:
1698 return parseDirectiveIfb(IDLoc, true);
1699 case DK_IFNB:
1700 return parseDirectiveIfb(IDLoc, false);
1701 case DK_IFC:
1702 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001703 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001704 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001705 case DK_IFNC:
1706 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001707 case DK_IFNES:
1708 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001709 case DK_IFDEF:
1710 return parseDirectiveIfdef(IDLoc, true);
1711 case DK_IFNDEF:
1712 case DK_IFNOTDEF:
1713 return parseDirectiveIfdef(IDLoc, false);
1714 case DK_ELSEIF:
1715 return parseDirectiveElseIf(IDLoc);
1716 case DK_ELSE:
1717 return parseDirectiveElse(IDLoc);
1718 case DK_ENDIF:
1719 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001720 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001721
Eli Bendersky88024712013-01-16 19:32:36 +00001722 // Ignore the statement if in the middle of inactive conditional
1723 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001724 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001725 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001726 return false;
1727 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001728
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001729 // FIXME: Recurse on local labels?
1730
1731 // See what kind of statement we have.
1732 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001733 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001734 if (!getTargetParser().isLabel(ID))
1735 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001736 if (checkForValidSection())
1737 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001738
Chris Lattner36e02122009-06-21 20:54:55 +00001739 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001740 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001741
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001742 // Diagnose attempt to use '.' as a label.
1743 if (IDVal == ".")
1744 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1745
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001746 // Diagnose attempt to use a variable as a label.
1747 //
1748 // FIXME: Diagnostics. Note the location of the definition as a label.
1749 // FIXME: This doesn't diagnose assignment to a symbol which has been
1750 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001751 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001752 if (LocalLabelVal == -1) {
1753 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001754 StringRef RewrittenLabel =
1755 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001756 assert(!RewrittenLabel.empty() &&
Nico Weber67e715f2015-06-19 23:43:47 +00001757 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001758 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1759 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001760 IDVal = RewrittenLabel;
1761 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001762 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001763 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001764 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
Nirav Dave9263ae32016-08-02 19:17:54 +00001765 // End of Labels should be treated as end of line for lexing
1766 // purposes but that information is not available to the Lexer who
1767 // does not understand Labels. This may cause us to see a Hash
1768 // here instead of a preprocessor line comment.
1769 if (getTok().is(AsmToken::Hash)) {
1770 StringRef CommentStr = parseStringToEndOfStatement();
1771 Lexer.Lex();
1772 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1773 }
1774
Nirav Dave8ea792d2016-07-13 14:03:12 +00001775 // Consume any end of statement token, if present, to avoid spurious
1776 // AddBlankLine calls().
1777 if (getTok().is(AsmToken::EndOfStatement)) {
1778 Lex();
1779 }
1780
Daniel Dunbare73b2672009-08-26 22:13:22 +00001781 // Emit the label.
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00001782 if (!getTargetParser().isParsingInlineAsm())
Rafael Espindolabe991572017-02-10 15:13:12 +00001783 Out.EmitLabel(Sym, IDLoc);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001784
Kevin Enderbye7739d42011-12-09 18:09:40 +00001785 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001786 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001787 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001788 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1789 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001790
Tim Northover1744d0a2013-10-25 12:49:50 +00001791 getTargetParser().onLabelParsed(Sym);
1792
Eli Friedman0f4871d2012-10-22 23:58:19 +00001793 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001794 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001795
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001796 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001797 if (!getTargetParser().equalIsAsmAssignment())
1798 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001799 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001800 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001801
Jim Grosbach4b905842013-09-20 23:08:21 +00001802 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001803
1804 default: // Normal instruction or directive.
1805 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001806 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001807
1808 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001809 if (areMacrosEnabled())
Rafael Espindola22c38a02018-02-14 16:34:27 +00001810 if (const MCAsmMacro *M = getContext().lookupMacro(IDVal)) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001811 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001812 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001813
Michael J. Spencer530ce852010-10-09 11:00:50 +00001814 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001815
Eli Bendersky17233942013-01-15 22:59:42 +00001816 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001817 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001818 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001819 //
Eli Bendersky17233942013-01-15 22:59:42 +00001820 // 1. The target-specific assembly parser. Some directives are target
1821 // specific or may potentially behave differently on certain targets.
1822 // 2. Asm parser extensions. For example, platform-specific parsers
1823 // (like the ELF parser) register themselves as extensions.
1824 // 3. The generic directive parser implemented by this class. These are
1825 // all the directives that behave in a target and platform independent
1826 // manner, or at least have a default behavior that's shared between
1827 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001828
Oliver Stannard21718282016-07-26 14:19:47 +00001829 getTargetParser().flushPendingInstructions(getStreamer());
1830
Nirav Dave2364748a2016-09-16 18:30:20 +00001831 SMLoc StartTokLoc = getTok().getLoc();
1832 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1833
1834 if (hasPendingError())
1835 return true;
1836 // Currently the return value should be true if we are
1837 // uninterested but as this is at odds with the standard parsing
1838 // convention (return true = error) we have instances of a parsed
1839 // directive that fails returning true as an error. Catch these
1840 // cases as best as possible errors here.
1841 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1842 return true;
1843 // Return if we did some parsing or believe we succeeded.
1844 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001845 return false;
1846
Alp Tokercb402912014-01-24 17:20:08 +00001847 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001848 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001849 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1850 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001851 if (Handler.first)
1852 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1853
1854 // Finally, if no one else is interested in this directive, it must be
1855 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001856 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001857 default:
1858 break;
1859 case DK_SET:
1860 case DK_EQU:
1861 return parseDirectiveSet(IDVal, true);
1862 case DK_EQUIV:
1863 return parseDirectiveSet(IDVal, false);
1864 case DK_ASCII:
1865 return parseDirectiveAscii(IDVal, false);
1866 case DK_ASCIZ:
1867 case DK_STRING:
1868 return parseDirectiveAscii(IDVal, true);
1869 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001870 case DK_DC_B:
1871 return parseDirectiveValue(IDVal, 1);
1872 case DK_DC:
1873 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001874 case DK_SHORT:
1875 case DK_VALUE:
1876 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001877 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001878 case DK_LONG:
1879 case DK_INT:
1880 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001881 case DK_DC_L:
1882 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001883 case DK_QUAD:
1884 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001885 return parseDirectiveValue(IDVal, 8);
1886 case DK_DC_A:
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001887 return parseDirectiveValue(
1888 IDVal, getContext().getAsmInfo()->getCodePointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001889 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001890 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001891 case DK_SINGLE:
1892 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001893 case DK_DC_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001894 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
Jim Grosbach4b905842013-09-20 23:08:21 +00001895 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001896 case DK_DC_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001897 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
Jim Grosbach4b905842013-09-20 23:08:21 +00001898 case DK_ALIGN: {
1899 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1900 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1901 }
1902 case DK_ALIGN32: {
1903 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1904 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1905 }
1906 case DK_BALIGN:
1907 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1908 case DK_BALIGNW:
1909 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1910 case DK_BALIGNL:
1911 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1912 case DK_P2ALIGN:
1913 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1914 case DK_P2ALIGNW:
1915 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1916 case DK_P2ALIGNL:
1917 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1918 case DK_ORG:
1919 return parseDirectiveOrg();
1920 case DK_FILL:
1921 return parseDirectiveFill();
1922 case DK_ZERO:
1923 return parseDirectiveZero();
1924 case DK_EXTERN:
1925 eatToEndOfStatement(); // .extern is the default, ignore it.
1926 return false;
1927 case DK_GLOBL:
1928 case DK_GLOBAL:
1929 return parseDirectiveSymbolAttribute(MCSA_Global);
1930 case DK_LAZY_REFERENCE:
1931 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1932 case DK_NO_DEAD_STRIP:
1933 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1934 case DK_SYMBOL_RESOLVER:
1935 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1936 case DK_PRIVATE_EXTERN:
1937 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1938 case DK_REFERENCE:
1939 return parseDirectiveSymbolAttribute(MCSA_Reference);
1940 case DK_WEAK_DEFINITION:
1941 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1942 case DK_WEAK_REFERENCE:
1943 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1944 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1945 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1946 case DK_COMM:
1947 case DK_COMMON:
1948 return parseDirectiveComm(/*IsLocal=*/false);
1949 case DK_LCOMM:
1950 return parseDirectiveComm(/*IsLocal=*/true);
1951 case DK_ABORT:
1952 return parseDirectiveAbort();
1953 case DK_INCLUDE:
1954 return parseDirectiveInclude();
1955 case DK_INCBIN:
1956 return parseDirectiveIncbin();
1957 case DK_CODE16:
1958 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001959 return TokError(Twine(IDVal) +
1960 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001961 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001962 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001963 case DK_IRP:
1964 return parseDirectiveIrp(IDLoc);
1965 case DK_IRPC:
1966 return parseDirectiveIrpc(IDLoc);
1967 case DK_ENDR:
1968 return parseDirectiveEndr(IDLoc);
1969 case DK_BUNDLE_ALIGN_MODE:
1970 return parseDirectiveBundleAlignMode();
1971 case DK_BUNDLE_LOCK:
1972 return parseDirectiveBundleLock();
1973 case DK_BUNDLE_UNLOCK:
1974 return parseDirectiveBundleUnlock();
1975 case DK_SLEB128:
1976 return parseDirectiveLEB128(true);
1977 case DK_ULEB128:
1978 return parseDirectiveLEB128(false);
1979 case DK_SPACE:
1980 case DK_SKIP:
1981 return parseDirectiveSpace(IDVal);
1982 case DK_FILE:
1983 return parseDirectiveFile(IDLoc);
1984 case DK_LINE:
1985 return parseDirectiveLine();
1986 case DK_LOC:
1987 return parseDirectiveLoc();
1988 case DK_STABS:
1989 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001990 case DK_CV_FILE:
1991 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001992 case DK_CV_FUNC_ID:
1993 return parseDirectiveCVFuncId();
1994 case DK_CV_INLINE_SITE_ID:
1995 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001996 case DK_CV_LOC:
1997 return parseDirectiveCVLoc();
1998 case DK_CV_LINETABLE:
1999 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00002000 case DK_CV_INLINE_LINETABLE:
2001 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00002002 case DK_CV_DEF_RANGE:
2003 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002004 case DK_CV_STRINGTABLE:
2005 return parseDirectiveCVStringTable();
2006 case DK_CV_FILECHECKSUMS:
2007 return parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00002008 case DK_CV_FILECHECKSUM_OFFSET:
2009 return parseDirectiveCVFileChecksumOffset();
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00002010 case DK_CV_FPO_DATA:
2011 return parseDirectiveCVFPOData();
Jim Grosbach4b905842013-09-20 23:08:21 +00002012 case DK_CFI_SECTIONS:
2013 return parseDirectiveCFISections();
2014 case DK_CFI_STARTPROC:
2015 return parseDirectiveCFIStartProc();
2016 case DK_CFI_ENDPROC:
2017 return parseDirectiveCFIEndProc();
2018 case DK_CFI_DEF_CFA:
2019 return parseDirectiveCFIDefCfa(IDLoc);
2020 case DK_CFI_DEF_CFA_OFFSET:
2021 return parseDirectiveCFIDefCfaOffset();
2022 case DK_CFI_ADJUST_CFA_OFFSET:
2023 return parseDirectiveCFIAdjustCfaOffset();
2024 case DK_CFI_DEF_CFA_REGISTER:
2025 return parseDirectiveCFIDefCfaRegister(IDLoc);
2026 case DK_CFI_OFFSET:
2027 return parseDirectiveCFIOffset(IDLoc);
2028 case DK_CFI_REL_OFFSET:
2029 return parseDirectiveCFIRelOffset(IDLoc);
2030 case DK_CFI_PERSONALITY:
2031 return parseDirectiveCFIPersonalityOrLsda(true);
2032 case DK_CFI_LSDA:
2033 return parseDirectiveCFIPersonalityOrLsda(false);
2034 case DK_CFI_REMEMBER_STATE:
2035 return parseDirectiveCFIRememberState();
2036 case DK_CFI_RESTORE_STATE:
2037 return parseDirectiveCFIRestoreState();
2038 case DK_CFI_SAME_VALUE:
2039 return parseDirectiveCFISameValue(IDLoc);
2040 case DK_CFI_RESTORE:
2041 return parseDirectiveCFIRestore(IDLoc);
2042 case DK_CFI_ESCAPE:
2043 return parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00002044 case DK_CFI_RETURN_COLUMN:
2045 return parseDirectiveCFIReturnColumn(IDLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +00002046 case DK_CFI_SIGNAL_FRAME:
2047 return parseDirectiveCFISignalFrame();
2048 case DK_CFI_UNDEFINED:
2049 return parseDirectiveCFIUndefined(IDLoc);
2050 case DK_CFI_REGISTER:
2051 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00002052 case DK_CFI_WINDOW_SAVE:
2053 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00002054 case DK_MACROS_ON:
2055 case DK_MACROS_OFF:
2056 return parseDirectiveMacrosOnOff(IDVal);
2057 case DK_MACRO:
2058 return parseDirectiveMacro(IDLoc);
Michael Zuckerman56704612017-05-01 13:20:12 +00002059 case DK_ALTMACRO:
2060 case DK_NOALTMACRO:
2061 return parseDirectiveAltmacro(IDVal);
Nico Weber155dccd12014-07-24 17:08:39 +00002062 case DK_EXITM:
2063 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00002064 case DK_ENDM:
2065 case DK_ENDMACRO:
2066 return parseDirectiveEndMacro(IDVal);
2067 case DK_PURGEM:
2068 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00002069 case DK_END:
2070 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00002071 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00002072 return parseDirectiveError(IDLoc, false);
2073 case DK_ERROR:
2074 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00002075 case DK_WARNING:
2076 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002077 case DK_RELOC:
2078 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002079 case DK_DCB:
2080 case DK_DCB_W:
2081 return parseDirectiveDCB(IDVal, 2);
2082 case DK_DCB_B:
2083 return parseDirectiveDCB(IDVal, 1);
2084 case DK_DCB_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002085 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002086 case DK_DCB_L:
2087 return parseDirectiveDCB(IDVal, 4);
2088 case DK_DCB_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002089 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
Petr Hosek731bb9c2016-08-23 21:34:53 +00002090 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002091 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00002092 return TokError(Twine(IDVal) +
2093 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00002094 case DK_DS:
2095 case DK_DS_W:
2096 return parseDirectiveDS(IDVal, 2);
2097 case DK_DS_B:
2098 return parseDirectiveDS(IDVal, 1);
2099 case DK_DS_D:
2100 return parseDirectiveDS(IDVal, 8);
2101 case DK_DS_L:
2102 case DK_DS_S:
2103 return parseDirectiveDS(IDVal, 4);
2104 case DK_DS_P:
2105 case DK_DS_X:
2106 return parseDirectiveDS(IDVal, 12);
Coby Tayree01e53202017-10-02 14:36:31 +00002107 case DK_PRINT:
2108 return parseDirectivePrint(IDLoc);
Eli Friedman20b02642010-07-19 04:17:25 +00002109 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002110
Jim Grosbach758e0cc2012-05-01 18:38:27 +00002111 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00002112 }
Chris Lattner36e02122009-06-21 20:54:55 +00002113
Chad Rosierc7f552c2013-02-12 21:33:51 +00002114 // __asm _emit or __asm __emit
2115 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
2116 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002117 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00002118
2119 // __asm align
2120 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002121 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00002122
Coby Tayree3847be92017-04-04 17:57:23 +00002123 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
Michael Zuckerman02ecd432015-12-13 17:07:23 +00002124 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00002125 if (checkForValidSection())
2126 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00002127
Chris Lattner7cbfa442010-05-19 23:34:33 +00002128 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00002129 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00002130 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00002131 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
2132 Info.ParsedOperands);
2133 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00002134
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002135 // Dump the parsed representation, if requested.
2136 if (getShowParsedOperands()) {
2137 SmallString<256> Str;
2138 raw_svector_ostream OS(Str);
2139 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002140 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002141 if (i != 0)
2142 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002143 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002144 }
2145 OS << "]";
2146
Jim Grosbach4b905842013-09-20 23:08:21 +00002147 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002148 }
2149
Nirav Dave2364748a2016-09-16 18:30:20 +00002150 // Fail even if ParseInstruction erroneously returns false.
2151 if (hasPendingError() || ParseHadError)
2152 return true;
2153
Oliver Stannard8b273082014-06-19 15:52:37 +00002154 // If we are generating dwarf for the current section then generate a .loc
2155 // directive for the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002156 if (!ParseHadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002157 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002158 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002159 unsigned Line;
2160 if (ActiveMacros.empty())
2161 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2162 else
Frederic Riss16238d92015-06-25 21:57:33 +00002163 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2164 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002165
Eli Bendersky88024712013-01-16 19:32:36 +00002166 // If we previously parsed a cpp hash file line comment then make sure the
2167 // current Dwarf File is for the CppHashFilename if not then emit the
2168 // Dwarf File table for it and adjust the line number for the .loc.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00002169 if (!CppHashInfo.Filename.empty()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002170 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002171 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002172 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002173
Jim Grosbach4b905842013-09-20 23:08:21 +00002174 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
2175 // cache with the different Loc from the call above we save the last
2176 // info we queried here with SrcMgr.FindLineNumber().
2177 unsigned CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002178 if (LastQueryIDLoc == CppHashInfo.Loc &&
2179 LastQueryBuffer == CppHashInfo.Buf)
Jim Grosbach4b905842013-09-20 23:08:21 +00002180 CppHashLocLineNo = LastQueryLine;
2181 else {
Tim Northoverc0bef992016-04-13 19:46:54 +00002182 CppHashLocLineNo =
2183 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002184 LastQueryLine = CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002185 LastQueryIDLoc = CppHashInfo.Loc;
2186 LastQueryBuffer = CppHashInfo.Buf;
Jim Grosbach4b905842013-09-20 23:08:21 +00002187 }
Tim Northoverc0bef992016-04-13 19:46:54 +00002188 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002189 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002190
Jim Grosbach4b905842013-09-20 23:08:21 +00002191 getStreamer().EmitDwarfLocDirective(
2192 getContext().getGenDwarfFileNumber(), Line, 0,
2193 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2194 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002195 }
2196
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002197 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002198 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002199 uint64_t ErrorInfo;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00002200 if (getTargetParser().MatchAndEmitInstruction(
2201 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2202 getTargetParser().isParsingInlineAsm()))
Nirav Dave2364748a2016-09-16 18:30:20 +00002203 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002204 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002205 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002206}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002207
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002208// Parse and erase curly braces marking block start/end
2209bool
2210AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2211 // Identify curly brace marking block start/end
2212 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2213 return false;
2214
2215 SMLoc StartLoc = Lexer.getLoc();
2216 Lex(); // Eat the brace
2217 if (Lexer.is(AsmToken::EndOfStatement))
2218 Lex(); // Eat EndOfStatement following the brace
2219
2220 // Erase the block start/end brace from the output asm string
2221 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2222 StartLoc.getPointer());
2223 return true;
2224}
2225
Jim Grosbach4b905842013-09-20 23:08:21 +00002226/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002227/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002228bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002229 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002230 // Lexer only ever emits HashDirective if it fully formed if it's
2231 // done the checking already so this is an internal error.
2232 assert(getTok().is(AsmToken::Integer) &&
2233 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002234 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002235 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002236 assert(getTok().is(AsmToken::String) &&
2237 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002238 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002239 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002240
Kevin Enderby72553612011-09-13 23:45:18 +00002241 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002242 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002243
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002244 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002245 CppHashInfo.Loc = L;
2246 CppHashInfo.Filename = Filename;
2247 CppHashInfo.LineNumber = LineNumber;
2248 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002249 return false;
2250}
2251
Jim Grosbach4b905842013-09-20 23:08:21 +00002252/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002253/// for the Filename and LineNo if any in the diagnostic.
2254void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002255 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002256 raw_ostream &OS = errs();
2257
2258 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002259 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002260 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2261 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002262 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002263
Jim Grosbach4b905842013-09-20 23:08:21 +00002264 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002265 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002266 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2267 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2268 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002269 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2270 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002271 }
2272
Eric Christophera7c32732012-12-18 00:30:54 +00002273 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002274 // manager changed or buffer changed (like in a nested include) then just
2275 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002276 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002277 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002278 if (Parser->SavedDiagHandler)
2279 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2280 else
Craig Topper353eda42014-04-24 06:44:33 +00002281 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002282 return;
2283 }
2284
Eric Christophera7c32732012-12-18 00:30:54 +00002285 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002286 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2287 // for the diagnostic.
2288 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002289
2290 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2291 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002292 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002293 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002294 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002295
Jim Grosbach4b905842013-09-20 23:08:21 +00002296 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2297 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002298 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002299
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002300 if (Parser->SavedDiagHandler)
2301 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2302 else
Craig Topper353eda42014-04-24 06:44:33 +00002303 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002304}
2305
Rafael Espindola2c064482012-08-21 18:29:30 +00002306// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2307// difference being that that function accepts '@' as part of identifiers and
2308// we can't do that. AsmLexer.cpp should probably be changed to handle
2309// '@' as a special case when needed.
2310static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002311 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2312 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002313}
2314
Rafael Espindola34b9c512012-06-03 23:57:14 +00002315bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002316 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002317 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002318 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002319 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002320 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002321 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002322 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002323
Preston Gurd05500642012-09-19 20:36:12 +00002324 // A macro without parameters is handled differently on Darwin:
2325 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002326 while (!Body.empty()) {
2327 // Scan for the next substitution.
2328 std::size_t End = Body.size(), Pos = 0;
2329 for (; Pos != End; ++Pos) {
2330 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002331 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002332 // This macro has no parameters, look for $0, $1, etc.
2333 if (Body[Pos] != '$' || Pos + 1 == End)
2334 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002335
Rafael Espindola1134ab232011-06-05 02:43:45 +00002336 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002337 if (Next == '$' || Next == 'n' ||
2338 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002339 break;
2340 } else {
2341 // This macro has parameters, look for \foo, \bar, etc.
2342 if (Body[Pos] == '\\' && Pos + 1 != End)
2343 break;
2344 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002345 }
2346
2347 // Add the prefix.
2348 OS << Body.slice(0, Pos);
2349
2350 // Check if we reached the end.
2351 if (Pos == End)
2352 break;
2353
Benjamin Kramer513e7442014-02-20 13:36:32 +00002354 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002355 switch (Body[Pos + 1]) {
2356 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002357 case '$':
2358 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002359 break;
2360
Jim Grosbach4b905842013-09-20 23:08:21 +00002361 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002362 case 'n':
2363 OS << A.size();
2364 break;
2365
Jim Grosbach4b905842013-09-20 23:08:21 +00002366 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002367 default: {
2368 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002369 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002370 if (Index >= A.size())
2371 break;
2372
2373 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002374 for (const AsmToken &Token : A[Index])
2375 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002376 break;
2377 }
2378 }
2379 Pos += 2;
2380 } else {
2381 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002382
2383 // Check for the \@ pseudo-variable.
2384 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002385 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002386 else
2387 while (isIdentifierChar(Body[I]) && I + 1 != End)
2388 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002389
Jim Grosbach4b905842013-09-20 23:08:21 +00002390 const char *Begin = Body.data() + Pos + 1;
2391 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002392 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002393
Toma Tabacu217116e2015-04-27 10:50:29 +00002394 if (Argument == "@") {
2395 OS << NumOfMacroInstantiations;
2396 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002397 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002398 for (; Index < NParameters; ++Index)
2399 if (Parameters[Index].Name == Argument)
2400 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002401
Toma Tabacu217116e2015-04-27 10:50:29 +00002402 if (Index == NParameters) {
2403 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2404 Pos += 3;
2405 else {
2406 OS << '\\' << Argument;
2407 Pos = I;
2408 }
2409 } else {
2410 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002411 for (const AsmToken &Token : A[Index])
Michael Zuckerman56704612017-05-01 13:20:12 +00002412 // For altmacro mode, you can write '%expr'.
2413 // The prefix '%' evaluates the expression 'expr'
2414 // and uses the result as a string (e.g. replace %(1+2) with the string "3").
2415 // Here, we identify the integer token which is the result of the
2416 // absolute expression evaluation and replace it with its string representation.
2417 if ((Lexer.IsaAltMacroMode()) &&
2418 (*(Token.getString().begin()) == '%') && Token.is(AsmToken::Integer))
2419 // Emit an integer value to the buffer.
2420 OS << Token.getIntVal();
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002421 // Only Token that was validated as a string and begins with '<'
2422 // is considered altMacroString!!!
2423 else if ((Lexer.IsaAltMacroMode()) &&
2424 (*(Token.getString().begin()) == '<') &&
2425 Token.is(AsmToken::String)) {
2426 std::string Res;
2427 altMacroString(Token.getStringContents(), Res);
2428 OS << Res;
2429 }
Toma Tabacu217116e2015-04-27 10:50:29 +00002430 // We expect no quotes around the string's contents when
2431 // parsing for varargs.
Michael Zuckerman56704612017-05-01 13:20:12 +00002432 else if (Token.isNot(AsmToken::String) || VarargParameter)
Craig Topper84008482015-10-10 05:38:14 +00002433 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002434 else
Craig Topper84008482015-10-10 05:38:14 +00002435 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002436
2437 Pos += 1 + Argument.size();
2438 }
Preston Gurd05500642012-09-19 20:36:12 +00002439 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002440 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002441 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002442 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002443 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002444
Rafael Espindola1134ab232011-06-05 02:43:45 +00002445 return false;
2446}
Daniel Dunbar43235712010-07-18 18:54:11 +00002447
Nico Weber2a8f9222014-07-24 16:29:04 +00002448MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002449 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002450 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002451 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002452
Jim Grosbach4b905842013-09-20 23:08:21 +00002453static bool isOperator(AsmToken::TokenKind kind) {
2454 switch (kind) {
2455 default:
2456 return false;
2457 case AsmToken::Plus:
2458 case AsmToken::Minus:
2459 case AsmToken::Tilde:
2460 case AsmToken::Slash:
2461 case AsmToken::Star:
2462 case AsmToken::Dot:
2463 case AsmToken::Equal:
2464 case AsmToken::EqualEqual:
2465 case AsmToken::Pipe:
2466 case AsmToken::PipePipe:
2467 case AsmToken::Caret:
2468 case AsmToken::Amp:
2469 case AsmToken::AmpAmp:
2470 case AsmToken::Exclaim:
2471 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002472 case AsmToken::Less:
2473 case AsmToken::LessEqual:
2474 case AsmToken::LessLess:
2475 case AsmToken::LessGreater:
2476 case AsmToken::Greater:
2477 case AsmToken::GreaterEqual:
2478 case AsmToken::GreaterGreater:
2479 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002480 }
2481}
2482
David Majnemer16252452014-01-29 00:07:39 +00002483namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002484
David Majnemer16252452014-01-29 00:07:39 +00002485class AsmLexerSkipSpaceRAII {
2486public:
2487 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2488 Lexer.setSkipSpace(SkipSpace);
2489 }
2490
2491 ~AsmLexerSkipSpaceRAII() {
2492 Lexer.setSkipSpace(true);
2493 }
2494
2495private:
2496 AsmLexer &Lexer;
2497};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002498
2499} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002500
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002501bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2502
2503 if (Vararg) {
2504 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2505 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002506 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002507 }
2508 return false;
2509 }
2510
Rafael Espindola768b41c2012-06-15 14:02:34 +00002511 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002512
David Majnemer16252452014-01-29 00:07:39 +00002513 // Darwin doesn't use spaces to delmit arguments.
2514 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002515
Scott Egertona1fa68a2016-02-11 13:48:49 +00002516 bool SpaceEaten;
2517
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002518 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002519 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002520 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002521 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002522
Scott Egertona1fa68a2016-02-11 13:48:49 +00002523 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002524
Scott Egertona1fa68a2016-02-11 13:48:49 +00002525 if (Lexer.is(AsmToken::Comma))
2526 break;
2527
2528 if (Lexer.is(AsmToken::Space)) {
2529 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002530 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002531 }
Preston Gurd05500642012-09-19 20:36:12 +00002532
2533 // Spaces can delimit parameters, but could also be part an expression.
2534 // If the token after a space is an operator, add the token and the next
2535 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002536 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002537 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002538 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002539 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002540
Scott Egertona1fa68a2016-02-11 13:48:49 +00002541 // Whitespace after an operator can be ignored.
2542 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002543 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002544
2545 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002546 }
2547 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002548 if (SpaceEaten)
2549 break;
Preston Gurd05500642012-09-19 20:36:12 +00002550 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002551
Jim Grosbach4b905842013-09-20 23:08:21 +00002552 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002553 // to be able to fill in the remaining default parameter values
2554 if (Lexer.is(AsmToken::EndOfStatement))
2555 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002556
2557 // Adjust the current parentheses level.
2558 if (Lexer.is(AsmToken::LParen))
2559 ++ParenLevel;
2560 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2561 --ParenLevel;
2562
2563 // Append the token to the current argument list.
2564 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002565 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002566 }
Preston Gurd05500642012-09-19 20:36:12 +00002567
Rafael Espindola768b41c2012-06-15 14:02:34 +00002568 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002569 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002570 return false;
2571}
2572
2573// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002574bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002575 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002576 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002577 bool NamedParametersFound = false;
2578 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002579
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002580 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002581 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002582
Rafael Espindola768b41c2012-06-15 14:02:34 +00002583 // Parse two kinds of macro invocations:
2584 // - macros defined without any parameters accept an arbitrary number of them
2585 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002586 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002587 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2588 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002589 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002590 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002591
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002592 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002593 if (parseIdentifier(FA.Name))
2594 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002595
Nirav Dave2364748a2016-09-16 18:30:20 +00002596 if (Lexer.isNot(AsmToken::Equal))
2597 return TokError("expected '=' after formal parameter identifier");
2598
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002599 Lex();
2600
2601 NamedParametersFound = true;
2602 }
Michael Zuckerman56704612017-05-01 13:20:12 +00002603 bool Vararg = HasVararg && Parameter == (NParameters - 1);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002604
Nirav Dave2364748a2016-09-16 18:30:20 +00002605 if (NamedParametersFound && FA.Name.empty())
2606 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002607
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002608 SMLoc StrLoc = Lexer.getLoc();
2609 SMLoc EndLoc;
Michael Zuckerman56704612017-05-01 13:20:12 +00002610 if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Percent)) {
Michael Zuckerman56704612017-05-01 13:20:12 +00002611 const MCExpr *AbsoluteExp;
2612 int64_t Value;
2613 /// Eat '%'
2614 Lex();
2615 if (parseExpression(AbsoluteExp, EndLoc))
2616 return false;
2617 if (!AbsoluteExp->evaluateAsAbsolute(Value))
2618 return Error(StrLoc, "expected absolute expression");
2619 const char *StrChar = StrLoc.getPointer();
2620 const char *EndChar = EndLoc.getPointer();
2621 AsmToken newToken(AsmToken::Integer, StringRef(StrChar , EndChar - StrChar), Value);
2622 FA.Value.push_back(newToken);
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002623 } else if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Less) &&
2624 isAltmacroString(StrLoc, EndLoc)) {
2625 const char *StrChar = StrLoc.getPointer();
2626 const char *EndChar = EndLoc.getPointer();
2627 jumpToLoc(EndLoc, CurBuffer);
2628 /// Eat from '<' to '>'
2629 Lex();
2630 AsmToken newToken(AsmToken::String, StringRef(StrChar, EndChar - StrChar));
2631 FA.Value.push_back(newToken);
2632 } else if(parseMacroArgument(FA.Value, Vararg))
Michael Zuckerman56704612017-05-01 13:20:12 +00002633 return true;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002634
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002635 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002636 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002637 unsigned FAI = 0;
2638 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002639 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002640 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002641
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002642 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002643 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002644 return Error(IDLoc, "parameter named '" + FA.Name +
2645 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002646 }
2647 PI = FAI;
2648 }
2649
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002650 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002651 if (A.size() <= PI)
2652 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002653 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002654
2655 if (FALocs.size() <= PI)
2656 FALocs.resize(PI + 1);
2657
2658 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002659 }
Jim Grosbach206661622012-07-30 22:44:17 +00002660
Preston Gurd242ed3152012-09-19 20:29:04 +00002661 // At the end of the statement, fill in remaining arguments that have
2662 // default values. If there aren't any, then the next argument is
2663 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002664 if (Lexer.is(AsmToken::EndOfStatement)) {
2665 bool Failure = false;
2666 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2667 if (A[FAI].empty()) {
2668 if (M->Parameters[FAI].Required) {
2669 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2670 "missing value for required parameter "
2671 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2672 Failure = true;
2673 }
2674
2675 if (!M->Parameters[FAI].Value.empty())
2676 A[FAI] = M->Parameters[FAI].Value;
2677 }
2678 }
2679 return Failure;
2680 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002681
2682 if (Lexer.is(AsmToken::Comma))
2683 Lex();
2684 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002685
2686 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002687}
2688
Jim Grosbach4b905842013-09-20 23:08:21 +00002689bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002690 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2691 // eliminate this, although we should protect against infinite loops.
2692 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2693 if (ActiveMacros.size() == MaxNestingDepth) {
2694 std::ostringstream MaxNestingDepthError;
2695 MaxNestingDepthError << "macros cannot be nested more than "
2696 << MaxNestingDepth << " levels deep."
2697 << " Use -asm-macro-max-nesting-depth to increase "
2698 "this limit.";
2699 return TokError(MaxNestingDepthError.str());
2700 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002701
Eli Bendersky38274122013-01-14 23:22:36 +00002702 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002703 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002704 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002705
Rafael Espindola1134ab232011-06-05 02:43:45 +00002706 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2707 // to hold the macro body with substitutions.
2708 SmallString<256> Buf;
2709 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002710 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002711
Toma Tabacu217116e2015-04-27 10:50:29 +00002712 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002713 return true;
2714
Eli Bendersky38274122013-01-14 23:22:36 +00002715 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002716 // instantiation.
2717 OS << ".endmacro\n";
2718
Rafael Espindola3560ff22014-08-27 20:03:13 +00002719 std::unique_ptr<MemoryBuffer> Instantiation =
2720 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002721
Daniel Dunbar43235712010-07-18 18:54:11 +00002722 // Create the macro instantiation object and add to the current macro
2723 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002724 MacroInstantiation *MI = new MacroInstantiation(
2725 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002726 ActiveMacros.push_back(MI);
2727
Toma Tabacu217116e2015-04-27 10:50:29 +00002728 ++NumOfMacroInstantiations;
2729
Daniel Dunbar43235712010-07-18 18:54:11 +00002730 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002731 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002732 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002733 Lex();
2734
2735 return false;
2736}
2737
Jim Grosbach4b905842013-09-20 23:08:21 +00002738void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002739 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002740 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002741 Lex();
2742
2743 // Pop the instantiation entry.
2744 delete ActiveMacros.back();
2745 ActiveMacros.pop_back();
2746}
2747
Jim Grosbach4b905842013-09-20 23:08:21 +00002748bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002749 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002750 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002751 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002752 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2753 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002754 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002755
Pete Cooper80d21cb2015-06-22 19:35:57 +00002756 if (!Sym) {
2757 // In the case where we parse an expression starting with a '.', we will
2758 // not generate an error, nor will we create a symbol. In this case we
2759 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002760 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002761 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002762
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002763 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002764 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002765 if (NoDeadStrip)
2766 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2767
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002768 return false;
2769}
2770
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002771/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002772/// ::= identifier
2773/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002774bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002775 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002776 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2777 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002778 // handle this as a context dependent token, instead we detect adjacent tokens
2779 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002780 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2781 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002782
Hans Wennborgce69d772013-10-18 20:46:28 +00002783 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002784
2785 AsmToken Buf[1];
2786 Lexer.peekTokens(Buf, false);
2787
2788 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002789 return true;
2790
Hans Wennborgce69d772013-10-18 20:46:28 +00002791 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002792 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002793 return true;
2794
Nirav Daved0463322016-10-12 13:58:07 +00002795 // eat $ or @
2796 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002797 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002798 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002799 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002800 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002801 return false;
2802 }
2803
Jim Grosbach4b905842013-09-20 23:08:21 +00002804 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002805 return true;
2806
Sean Callanan936b0d32010-01-19 21:44:56 +00002807 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002808
Sean Callanan686ed8d2010-01-19 20:22:31 +00002809 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002810
2811 return false;
2812}
2813
Jim Grosbach4b905842013-09-20 23:08:21 +00002814/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002815/// ::= .equ identifier ',' expression
2816/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002817/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002818bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002819 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002820 if (check(parseIdentifier(Name), "expected identifier") ||
2821 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2822 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2823 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002824}
2825
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002826bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002827 if (check(getTok().isNot(AsmToken::String), "expected string"))
2828 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002829
2830 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002831 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002832 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2833 if (Str[i] != '\\') {
2834 Data += Str[i];
2835 continue;
2836 }
2837
2838 // Recognize escaped characters. Note that this escape semantics currently
2839 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2840 ++i;
2841 if (i == e)
2842 return TokError("unexpected backslash at end of string");
2843
2844 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002845 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002846 // Consume up to three octal characters.
2847 unsigned Value = Str[i] - '0';
2848
Jim Grosbach4b905842013-09-20 23:08:21 +00002849 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002850 ++i;
2851 Value = Value * 8 + (Str[i] - '0');
2852
Jim Grosbach4b905842013-09-20 23:08:21 +00002853 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002854 ++i;
2855 Value = Value * 8 + (Str[i] - '0');
2856 }
2857 }
2858
2859 if (Value > 255)
2860 return TokError("invalid octal escape sequence (out of range)");
2861
Jim Grosbach4b905842013-09-20 23:08:21 +00002862 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002863 continue;
2864 }
2865
2866 // Otherwise recognize individual escapes.
2867 switch (Str[i]) {
2868 default:
2869 // Just reject invalid escape sequences for now.
2870 return TokError("invalid escape sequence (unrecognized character)");
2871
2872 case 'b': Data += '\b'; break;
2873 case 'f': Data += '\f'; break;
2874 case 'n': Data += '\n'; break;
2875 case 'r': Data += '\r'; break;
2876 case 't': Data += '\t'; break;
2877 case '"': Data += '"'; break;
2878 case '\\': Data += '\\'; break;
2879 }
2880 }
2881
Nirav Davea645433c2016-07-18 15:24:03 +00002882 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002883 return false;
2884}
2885
Jim Grosbach4b905842013-09-20 23:08:21 +00002886/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002887/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002888bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002889 auto parseOp = [&]() -> bool {
2890 std::string Data;
2891 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002892 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002893 getStreamer().EmitBytes(Data);
2894 if (ZeroTerminated)
2895 getStreamer().EmitBytes(StringRef("\0", 1));
2896 return false;
2897 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002898
Nirav Dave1a9044b2016-10-24 14:35:29 +00002899 if (parseMany(parseOp))
2900 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002901 return false;
2902}
2903
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002904/// parseDirectiveReloc
2905/// ::= .reloc expression , identifier [ , expression ]
2906bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2907 const MCExpr *Offset;
2908 const MCExpr *Expr = nullptr;
2909
2910 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00002911 int64_t OffsetValue;
2912 // We can only deal with constant expressions at the moment.
2913
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002914 if (parseExpression(Offset))
2915 return true;
2916
Nirav Davea645433c2016-07-18 15:24:03 +00002917 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2918 "expression is not a constant value") ||
2919 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2920 parseToken(AsmToken::Comma, "expected comma") ||
2921 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2922 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002923
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002924 SMLoc NameLoc = Lexer.getTok().getLoc();
2925 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002926 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002927
2928 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002929 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002930 SMLoc ExprLoc = Lexer.getLoc();
2931 if (parseExpression(Expr))
2932 return true;
2933
2934 MCValue Value;
2935 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2936 return Error(ExprLoc, "expression must be relocatable");
2937 }
2938
Nirav Davea645433c2016-07-18 15:24:03 +00002939 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002940 "unexpected token in .reloc directive"))
2941 return true;
2942
2943 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2944 return Error(NameLoc, "unknown relocation name");
2945
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002946 return false;
2947}
2948
Jim Grosbach4b905842013-09-20 23:08:21 +00002949/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002950/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002951bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2952 auto parseOp = [&]() -> bool {
2953 const MCExpr *Value;
2954 SMLoc ExprLoc = getLexer().getLoc();
2955 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002956 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002957 // Special case constant expressions to match code generator.
2958 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2959 assert(Size <= 8 && "Invalid size");
2960 uint64_t IntValue = MCE->getValue();
2961 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2962 return Error(ExprLoc, "out of range literal value");
2963 getStreamer().EmitIntValue(IntValue, Size);
2964 } else
2965 getStreamer().EmitValue(Value, Size, ExprLoc);
2966 return false;
2967 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002968
Nirav Dave1a9044b2016-10-24 14:35:29 +00002969 if (parseMany(parseOp))
2970 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002971 return false;
2972}
2973
David Woodhoused6de0d92014-02-01 16:20:59 +00002974/// ParseDirectiveOctaValue
2975/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002976
2977bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
2978 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00002979 if (checkForValidSection())
2980 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002981 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
2982 return TokError("unknown token in expression");
2983 SMLoc ExprLoc = getTok().getLoc();
2984 APInt IntValue = getTok().getAPIntVal();
2985 uint64_t hi, lo;
2986 Lex();
2987 if (!IntValue.isIntN(128))
2988 return Error(ExprLoc, "out of range literal value");
2989 if (!IntValue.isIntN(64)) {
2990 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2991 lo = IntValue.getLoBits(64).getZExtValue();
2992 } else {
2993 hi = 0;
2994 lo = IntValue.getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002995 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00002996 if (MAI.isLittleEndian()) {
2997 getStreamer().EmitIntValue(lo, 8);
2998 getStreamer().EmitIntValue(hi, 8);
2999 } else {
3000 getStreamer().EmitIntValue(hi, 8);
3001 getStreamer().EmitIntValue(lo, 8);
3002 }
3003 return false;
3004 };
David Woodhoused6de0d92014-02-01 16:20:59 +00003005
Nirav Dave1a9044b2016-10-24 14:35:29 +00003006 if (parseMany(parseOp))
3007 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00003008 return false;
3009}
3010
Petr Hosek4cb08ce2016-09-23 19:25:15 +00003011bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
3012 // We don't truly support arithmetic on floating point expressions, so we
3013 // have to manually parse unary prefixes.
3014 bool IsNeg = false;
3015 if (getLexer().is(AsmToken::Minus)) {
3016 Lexer.Lex();
3017 IsNeg = true;
3018 } else if (getLexer().is(AsmToken::Plus))
3019 Lexer.Lex();
3020
3021 if (Lexer.is(AsmToken::Error))
3022 return TokError(Lexer.getErr());
3023 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
3024 Lexer.isNot(AsmToken::Identifier))
3025 return TokError("unexpected token in directive");
3026
3027 // Convert to an APFloat.
3028 APFloat Value(Semantics);
3029 StringRef IDVal = getTok().getString();
3030 if (getLexer().is(AsmToken::Identifier)) {
3031 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
3032 Value = APFloat::getInf(Semantics);
3033 else if (!IDVal.compare_lower("nan"))
3034 Value = APFloat::getNaN(Semantics, false, ~0);
3035 else
3036 return TokError("invalid floating point literal");
3037 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
3038 APFloat::opInvalidOp)
3039 return TokError("invalid floating point literal");
3040 if (IsNeg)
3041 Value.changeSign();
3042
3043 // Consume the numeric token.
3044 Lex();
3045
3046 Res = Value.bitcastToAPInt();
3047
3048 return false;
3049}
3050
Jim Grosbach4b905842013-09-20 23:08:21 +00003051/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00003052/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003053bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
3054 const fltSemantics &Semantics) {
3055 auto parseOp = [&]() -> bool {
3056 APInt AsInt;
3057 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00003058 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003059 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
3060 AsInt.getBitWidth() / 8);
3061 return false;
3062 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00003063
Nirav Dave1a9044b2016-10-24 14:35:29 +00003064 if (parseMany(parseOp))
3065 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00003066 return false;
3067}
3068
Jim Grosbach4b905842013-09-20 23:08:21 +00003069/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00003070/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003071bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003072 SMLoc NumBytesLoc = Lexer.getLoc();
3073 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003074 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00003075 return true;
3076
Rafael Espindolab91bac62010-10-05 19:42:57 +00003077 int64_t Val = 0;
3078 if (getLexer().is(AsmToken::Comma)) {
3079 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003080 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00003081 return true;
3082 }
3083
Nirav Davea645433c2016-07-18 15:24:03 +00003084 if (parseToken(AsmToken::EndOfStatement,
3085 "unexpected token in '.zero' directive"))
3086 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00003087 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00003088
3089 return false;
3090}
3091
Jim Grosbach4b905842013-09-20 23:08:21 +00003092/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00003093/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003094bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003095 SMLoc NumValuesLoc = Lexer.getLoc();
3096 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003097 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00003098 return true;
3099
Roman Divackye33098f2013-09-24 17:44:41 +00003100 int64_t FillSize = 1;
3101 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00003102
David Majnemer522d3db2014-02-01 07:19:38 +00003103 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003104
Nirav Dave1a9044b2016-10-24 14:35:29 +00003105 if (parseOptionalToken(AsmToken::Comma)) {
3106 SizeLoc = getTok().getLoc();
3107 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00003108 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003109 if (parseOptionalToken(AsmToken::Comma)) {
3110 ExprLoc = getTok().getLoc();
3111 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00003112 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00003113 }
3114 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003115 if (parseToken(AsmToken::EndOfStatement,
3116 "unexpected token in '.fill' directive"))
3117 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003118
David Majnemer522d3db2014-02-01 07:19:38 +00003119 if (FillSize < 0) {
3120 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00003121 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00003122 }
3123 if (FillSize > 8) {
3124 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
3125 FillSize = 8;
3126 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00003127
David Majnemer522d3db2014-02-01 07:19:38 +00003128 if (!isUInt<32>(FillExpr) && FillSize > 4)
3129 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
3130
Petr Hosek67a94a72016-05-28 05:57:48 +00003131 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00003132
3133 return false;
3134}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003135
Jim Grosbach4b905842013-09-20 23:08:21 +00003136/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003137/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003138bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00003139 const MCExpr *Offset;
Oliver Stannard268f42f2016-12-14 10:43:58 +00003140 SMLoc OffsetLoc = Lexer.getLoc();
Nirav Davef43cc9f2016-10-10 15:24:54 +00003141 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003142 return true;
3143
3144 // Parse optional fill expression.
3145 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003146 if (parseOptionalToken(AsmToken::Comma))
3147 if (parseAbsoluteExpression(FillExpr))
3148 return addErrorSuffix(" in '.org' directive");
3149 if (parseToken(AsmToken::EndOfStatement))
3150 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00003151
Oliver Stannard268f42f2016-12-14 10:43:58 +00003152 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003153 return false;
3154}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003155
Jim Grosbach4b905842013-09-20 23:08:21 +00003156/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003157/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00003158bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003159 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003160 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003161 SMLoc MaxBytesLoc;
3162 bool HasFillExpr = false;
3163 int64_t FillExpr = 0;
3164 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003165
3166 auto parseAlign = [&]() -> bool {
Coby Tayreed483a102017-08-02 17:36:10 +00003167 if (parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00003168 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003169 if (parseOptionalToken(AsmToken::Comma)) {
3170 // The fill expression can be omitted while specifying a maximum number of
3171 // alignment bytes, e.g:
3172 // .align 3,,4
3173 if (getTok().isNot(AsmToken::Comma)) {
3174 HasFillExpr = true;
3175 if (parseAbsoluteExpression(FillExpr))
3176 return true;
3177 }
3178 if (parseOptionalToken(AsmToken::Comma))
3179 if (parseTokenLoc(MaxBytesLoc) ||
3180 parseAbsoluteExpression(MaxBytesToFill))
3181 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003182 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003183 return parseToken(AsmToken::EndOfStatement);
3184 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003185
Coby Tayreed483a102017-08-02 17:36:10 +00003186 if (checkForValidSection())
3187 return addErrorSuffix(" in directive");
3188 // Ignore empty '.p2align' directives for GNU-as compatibility
3189 if (IsPow2 && (ValueSize == 1) && getTok().is(AsmToken::EndOfStatement)) {
3190 Warning(AlignmentLoc, "p2align directive with no operand(s) is ignored");
3191 return parseToken(AsmToken::EndOfStatement);
3192 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003193 if (parseAlign())
3194 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003195
Nirav Dave2364748a2016-09-16 18:30:20 +00003196 // Always emit an alignment here even if we thrown an error.
3197 bool ReturnVal = false;
3198
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003199 // Compute alignment in bytes.
3200 if (IsPow2) {
3201 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003202 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003203 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003204 Alignment = 31;
3205 }
3206
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003207 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003208 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003209 // Reject alignments that aren't either a power of two or zero,
3210 // for gas compatibility. Alignment of zero is silently rounded
3211 // up to one.
3212 if (Alignment == 0)
3213 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003214 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003215 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003216 }
3217
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003218 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003219 if (MaxBytesLoc.isValid()) {
3220 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003221 ReturnVal |= Error(MaxBytesLoc,
3222 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003223 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003224 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003225 }
3226
3227 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003228 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003229 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003230 MaxBytesToFill = 0;
3231 }
3232 }
3233
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003234 // Check whether we should use optimal code alignment for this .align
3235 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003236 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003237 assert(Section && "must have section to emit alignment");
3238 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003239 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3240 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003241 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003242 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003243 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003244 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3245 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003246 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003247
Nirav Dave2364748a2016-09-16 18:30:20 +00003248 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003249}
3250
Jim Grosbach4b905842013-09-20 23:08:21 +00003251/// parseDirectiveFile
Paul Robinson29f5f982018-01-09 23:31:48 +00003252/// ::= .file filename
3253/// ::= .file number [directory] filename [md5 checksum]
Jim Grosbach4b905842013-09-20 23:08:21 +00003254bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003255 // FIXME: I'm not sure what this is.
3256 int64_t FileNumber = -1;
3257 SMLoc FileNumberLoc = getLexer().getLoc();
3258 if (getLexer().is(AsmToken::Integer)) {
3259 FileNumber = getTok().getIntVal();
3260 Lex();
3261
3262 if (FileNumber < 1)
3263 return TokError("file number less than one");
3264 }
3265
Nirav Davea645433c2016-07-18 15:24:03 +00003266 std::string Path = getTok().getString();
Eli Bendersky17233942013-01-15 22:59:42 +00003267
3268 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003269 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003270 if (check(getTok().isNot(AsmToken::String),
3271 "unexpected token in '.file' directive") ||
3272 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003273 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003274
3275 StringRef Directory;
3276 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003277 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003278 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003279 if (check(FileNumber == -1,
3280 "explicit path specified, but no file number") ||
3281 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003282 return true;
3283 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003284 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003285 } else {
3286 Filename = Path;
3287 }
3288
Paul Robinson29f5f982018-01-09 23:31:48 +00003289 std::string Checksum;
3290 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3291 StringRef Keyword;
3292 if (check(getTok().isNot(AsmToken::Identifier),
3293 "unexpected token in '.file' directive") ||
3294 parseIdentifier(Keyword) ||
3295 check(Keyword != "md5", "unexpected token in '.file' directive"))
3296 return true;
3297 if (getLexer().is(AsmToken::String) &&
3298 check(FileNumber == -1, "MD5 checksum specified, but no file number"))
3299 return true;
3300 if (check(getTok().isNot(AsmToken::String),
3301 "unexpected token in '.file' directive") ||
3302 parseEscapedString(Checksum) ||
3303 check(Checksum.size() != 32, "invalid MD5 checksum specified") ||
3304 parseToken(AsmToken::EndOfStatement,
3305 "unexpected token in '.file' directive"))
3306 return true;
3307 }
Eli Bendersky17233942013-01-15 22:59:42 +00003308
3309 if (FileNumber == -1)
3310 getStreamer().EmitFileDirective(Filename);
3311 else {
Paul Robinson29f5f982018-01-09 23:31:48 +00003312 MD5::MD5Result *CKMem = nullptr;
3313 if (!Checksum.empty()) {
3314 Checksum = fromHex(Checksum);
3315 if (check(Checksum.size() != 16, "invalid MD5 checksum specified"))
3316 return true;
3317 CKMem = (MD5::MD5Result *)Ctx.allocate(sizeof(MD5::MD5Result), 1);
3318 memcpy(&CKMem->Bytes, Checksum.data(), 16);
3319 }
David Blaikie22748082016-05-26 00:22:26 +00003320 // If there is -g option as well as debug info from directive file,
3321 // we turn off -g option, directly use the existing debug info instead.
David Blaikiedc3f01e2015-03-09 01:57:13 +00003322 if (getContext().getGenDwarfForAssembly())
David Blaikie22748082016-05-26 00:22:26 +00003323 getContext().setGenDwarfForAssembly(false);
Paul Robinson29f5f982018-01-09 23:31:48 +00003324 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory,
3325 Filename, CKMem) == 0)
Nirav Dave2364748a2016-09-16 18:30:20 +00003326 return Error(FileNumberLoc, "file number already allocated");
Eli Bendersky17233942013-01-15 22:59:42 +00003327 }
3328
3329 return false;
3330}
3331
Jim Grosbach4b905842013-09-20 23:08:21 +00003332/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003333/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003334bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003335 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003336 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003337 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3338 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003339 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003340 // FIXME: Do something with the .line.
3341 }
Nirav Davea645433c2016-07-18 15:24:03 +00003342 if (parseToken(AsmToken::EndOfStatement,
3343 "unexpected token in '.line' directive"))
3344 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003345
3346 return false;
3347}
3348
Jim Grosbach4b905842013-09-20 23:08:21 +00003349/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003350/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3351/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3352/// The first number is a file number, must have been previously assigned with
3353/// a .file directive, the second number is the line number and optionally the
3354/// third number is a column position (zero if not specified). The remaining
3355/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003356bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003357 int64_t FileNumber = 0, LineNumber = 0;
3358 SMLoc Loc = getTok().getLoc();
3359 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3360 check(FileNumber < 1, Loc,
3361 "file number less than one in '.loc' directive") ||
3362 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3363 "unassigned file number in '.loc' directive"))
3364 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003365
Nirav Davea645433c2016-07-18 15:24:03 +00003366 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003367 if (getLexer().is(AsmToken::Integer)) {
3368 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003369 if (LineNumber < 0)
3370 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003371 Lex();
3372 }
3373
3374 int64_t ColumnPos = 0;
3375 if (getLexer().is(AsmToken::Integer)) {
3376 ColumnPos = getTok().getIntVal();
3377 if (ColumnPos < 0)
3378 return TokError("column position less than zero in '.loc' directive");
3379 Lex();
3380 }
3381
3382 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3383 unsigned Isa = 0;
3384 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003385
Nirav Dave1a9044b2016-10-24 14:35:29 +00003386 auto parseLocOp = [&]() -> bool {
3387 StringRef Name;
3388 SMLoc Loc = getTok().getLoc();
3389 if (parseIdentifier(Name))
3390 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003391
Nirav Dave1a9044b2016-10-24 14:35:29 +00003392 if (Name == "basic_block")
3393 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3394 else if (Name == "prologue_end")
3395 Flags |= DWARF2_FLAG_PROLOGUE_END;
3396 else if (Name == "epilogue_begin")
3397 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3398 else if (Name == "is_stmt") {
3399 Loc = getTok().getLoc();
3400 const MCExpr *Value;
3401 if (parseExpression(Value))
3402 return true;
3403 // The expression must be the constant 0 or 1.
3404 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3405 int Value = MCE->getValue();
3406 if (Value == 0)
3407 Flags &= ~DWARF2_FLAG_IS_STMT;
3408 else if (Value == 1)
3409 Flags |= DWARF2_FLAG_IS_STMT;
3410 else
3411 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003412 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003413 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003414 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003415 } else if (Name == "isa") {
3416 Loc = getTok().getLoc();
3417 const MCExpr *Value;
3418 if (parseExpression(Value))
3419 return true;
3420 // The expression must be a constant greater or equal to 0.
3421 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3422 int Value = MCE->getValue();
3423 if (Value < 0)
3424 return Error(Loc, "isa number less than zero");
3425 Isa = Value;
3426 } else {
3427 return Error(Loc, "isa number not a constant value");
3428 }
3429 } else if (Name == "discriminator") {
3430 if (parseAbsoluteExpression(Discriminator))
3431 return true;
3432 } else {
3433 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003434 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003435 return false;
3436 };
3437
Nirav Davee2369aa2016-10-26 17:28:58 +00003438 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003439 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003440
3441 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3442 Isa, Discriminator, StringRef());
3443
3444 return false;
3445}
3446
Jim Grosbach4b905842013-09-20 23:08:21 +00003447/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003448/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003449bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003450 return TokError("unsupported directive '.stabs'");
3451}
3452
Reid Kleckner2214ed82016-01-29 00:49:42 +00003453/// parseDirectiveCVFile
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003454/// ::= .cv_file number filename [checksum] [checksumkind]
Reid Kleckner2214ed82016-01-29 00:49:42 +00003455bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003456 SMLoc FileNumberLoc = getTok().getLoc();
3457 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003458 std::string Filename;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003459 std::string Checksum;
3460 int64_t ChecksumKind = 0;
Nirav Davea645433c2016-07-18 15:24:03 +00003461
3462 if (parseIntToken(FileNumber,
3463 "expected file number in '.cv_file' directive") ||
3464 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3465 check(getTok().isNot(AsmToken::String),
3466 "unexpected token in '.cv_file' directive") ||
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003467 parseEscapedString(Filename))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003468 return true;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003469 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3470 if (check(getTok().isNot(AsmToken::String),
3471 "unexpected token in '.cv_file' directive") ||
3472 parseEscapedString(Checksum) ||
3473 parseIntToken(ChecksumKind,
3474 "expected checksum kind in '.cv_file' directive") ||
3475 parseToken(AsmToken::EndOfStatement,
3476 "unexpected token in '.cv_file' directive"))
3477 return true;
3478 }
Nirav Dave1ab71992016-07-18 19:35:21 +00003479
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003480 Checksum = fromHex(Checksum);
3481 void *CKMem = Ctx.allocate(Checksum.size(), 1);
3482 memcpy(CKMem, Checksum.data(), Checksum.size());
3483 ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem),
3484 Checksum.size());
3485
3486 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename, ChecksumAsBytes,
3487 static_cast<uint8_t>(ChecksumKind)))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003488 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003489
3490 return false;
3491}
3492
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003493bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3494 StringRef DirectiveName) {
3495 SMLoc Loc;
3496 return parseTokenLoc(Loc) ||
3497 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3498 "' directive") ||
3499 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3500 "expected function id within range [0, UINT_MAX)");
3501}
3502
3503bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3504 SMLoc Loc;
3505 return parseTokenLoc(Loc) ||
3506 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3507 "' directive") ||
3508 check(FileNumber < 1, Loc, "file number less than one in '" +
3509 DirectiveName + "' directive") ||
3510 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3511 "unassigned file number in '" + DirectiveName + "' directive");
3512}
3513
3514/// parseDirectiveCVFuncId
3515/// ::= .cv_func_id FunctionId
3516///
3517/// Introduces a function ID that can be used with .cv_loc.
3518bool AsmParser::parseDirectiveCVFuncId() {
3519 SMLoc FunctionIdLoc = getTok().getLoc();
3520 int64_t FunctionId;
3521
3522 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3523 parseToken(AsmToken::EndOfStatement,
3524 "unexpected token in '.cv_func_id' directive"))
3525 return true;
3526
3527 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003528 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003529
3530 return false;
3531}
3532
3533/// parseDirectiveCVInlineSiteId
3534/// ::= .cv_inline_site_id FunctionId
3535/// "within" IAFunc
3536/// "inlined_at" IAFile IALine [IACol]
3537///
3538/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3539/// at" source location information for use in the line table of the caller,
3540/// whether the caller is a real function or another inlined call site.
3541bool AsmParser::parseDirectiveCVInlineSiteId() {
3542 SMLoc FunctionIdLoc = getTok().getLoc();
3543 int64_t FunctionId;
3544 int64_t IAFunc;
3545 int64_t IAFile;
3546 int64_t IALine;
3547 int64_t IACol = 0;
3548
3549 // FunctionId
3550 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3551 return true;
3552
3553 // "within"
3554 if (check((getLexer().isNot(AsmToken::Identifier) ||
3555 getTok().getIdentifier() != "within"),
3556 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3557 return true;
3558 Lex();
3559
3560 // IAFunc
3561 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3562 return true;
3563
3564 // "inlined_at"
3565 if (check((getLexer().isNot(AsmToken::Identifier) ||
3566 getTok().getIdentifier() != "inlined_at"),
3567 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3568 "directive") )
3569 return true;
3570 Lex();
3571
3572 // IAFile IALine
3573 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3574 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3575 return true;
3576
3577 // [IACol]
3578 if (getLexer().is(AsmToken::Integer)) {
3579 IACol = getTok().getIntVal();
3580 Lex();
3581 }
3582
3583 if (parseToken(AsmToken::EndOfStatement,
3584 "unexpected token in '.cv_inline_site_id' directive"))
3585 return true;
3586
3587 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3588 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003589 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003590
3591 return false;
3592}
3593
Reid Kleckner2214ed82016-01-29 00:49:42 +00003594/// parseDirectiveCVLoc
3595/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3596/// [is_stmt VALUE]
3597/// The first number is a file number, must have been previously assigned with
3598/// a .file directive, the second number is the line number and optionally the
3599/// third number is a column position (zero if not specified). The remaining
3600/// optional items are .loc sub-directives.
3601bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003602 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003603 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003604 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3605 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003606 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003607
3608 int64_t LineNumber = 0;
3609 if (getLexer().is(AsmToken::Integer)) {
3610 LineNumber = getTok().getIntVal();
3611 if (LineNumber < 0)
3612 return TokError("line number less than zero in '.cv_loc' directive");
3613 Lex();
3614 }
3615
3616 int64_t ColumnPos = 0;
3617 if (getLexer().is(AsmToken::Integer)) {
3618 ColumnPos = getTok().getIntVal();
3619 if (ColumnPos < 0)
3620 return TokError("column position less than zero in '.cv_loc' directive");
3621 Lex();
3622 }
3623
3624 bool PrologueEnd = false;
3625 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003626
3627 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003628 StringRef Name;
3629 SMLoc Loc = getTok().getLoc();
3630 if (parseIdentifier(Name))
3631 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003632 if (Name == "prologue_end")
3633 PrologueEnd = true;
3634 else if (Name == "is_stmt") {
3635 Loc = getTok().getLoc();
3636 const MCExpr *Value;
3637 if (parseExpression(Value))
3638 return true;
3639 // The expression must be the constant 0 or 1.
3640 IsStmt = ~0ULL;
3641 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3642 IsStmt = MCE->getValue();
3643
3644 if (IsStmt > 1)
3645 return Error(Loc, "is_stmt value not 0 or 1");
3646 } else {
3647 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3648 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003649 return false;
3650 };
3651
3652 if (parseMany(parseOp, false /*hasComma*/))
3653 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003654
3655 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003656 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3657 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003658 return false;
3659}
3660
3661/// parseDirectiveCVLinetable
3662/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3663bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003664 int64_t FunctionId;
3665 StringRef FnStartName, FnEndName;
3666 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003667 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003668 parseToken(AsmToken::Comma,
3669 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003670 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3671 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003672 parseToken(AsmToken::Comma,
3673 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003674 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3675 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003676 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003677
3678 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3679 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3680
3681 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3682 return false;
3683}
3684
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003685/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003686/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003687bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003688 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3689 StringRef FnStartName, FnEndName;
3690 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003691 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003692 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003693 parseIntToken(
3694 SourceFileId,
3695 "expected SourceField in '.cv_inline_linetable' directive") ||
3696 check(SourceFileId <= 0, Loc,
3697 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003698 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003699 parseIntToken(
3700 SourceLineNum,
3701 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3702 check(SourceLineNum < 0, Loc,
3703 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003704 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3705 "expected identifier in directive") ||
3706 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3707 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003708 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003709
Nirav Davea645433c2016-07-18 15:24:03 +00003710 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3711 return true;
3712
3713 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3714 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003715 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3716 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003717 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003718 return false;
3719}
3720
David Majnemer408b5e62016-02-05 01:55:49 +00003721/// parseDirectiveCVDefRange
3722/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3723bool AsmParser::parseDirectiveCVDefRange() {
3724 SMLoc Loc;
3725 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3726 while (getLexer().is(AsmToken::Identifier)) {
3727 Loc = getLexer().getLoc();
3728 StringRef GapStartName;
3729 if (parseIdentifier(GapStartName))
3730 return Error(Loc, "expected identifier in directive");
3731 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3732
3733 Loc = getLexer().getLoc();
3734 StringRef GapEndName;
3735 if (parseIdentifier(GapEndName))
3736 return Error(Loc, "expected identifier in directive");
3737 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3738
3739 Ranges.push_back({GapStartSym, GapEndSym});
3740 }
3741
David Majnemer408b5e62016-02-05 01:55:49 +00003742 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003743 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3744 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003745 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003746
3747 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3748 return false;
3749}
3750
Reid Kleckner2214ed82016-01-29 00:49:42 +00003751/// parseDirectiveCVStringTable
3752/// ::= .cv_stringtable
3753bool AsmParser::parseDirectiveCVStringTable() {
3754 getStreamer().EmitCVStringTableDirective();
3755 return false;
3756}
3757
3758/// parseDirectiveCVFileChecksums
3759/// ::= .cv_filechecksums
3760bool AsmParser::parseDirectiveCVFileChecksums() {
3761 getStreamer().EmitCVFileChecksumsDirective();
3762 return false;
3763}
3764
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003765/// parseDirectiveCVFileChecksumOffset
3766/// ::= .cv_filechecksumoffset fileno
3767bool AsmParser::parseDirectiveCVFileChecksumOffset() {
3768 int64_t FileNo;
3769 if (parseIntToken(FileNo, "expected identifier in directive"))
3770 return true;
3771 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3772 return true;
3773 getStreamer().EmitCVFileChecksumOffsetDirective(FileNo);
3774 return false;
3775}
3776
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00003777/// parseDirectiveCVFPOData
3778/// ::= .cv_fpo_data procsym
3779bool AsmParser::parseDirectiveCVFPOData() {
3780 SMLoc DirLoc = getLexer().getLoc();
3781 StringRef ProcName;
3782 if (parseIdentifier(ProcName))
3783 return TokError("expected symbol name");
3784 if (parseEOL("unexpected tokens"))
3785 return addErrorSuffix(" in '.cv_fpo_data' directive");
3786 MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName);
3787 getStreamer().EmitCVFPOData(ProcSym, DirLoc);
3788 return false;
3789}
3790
Jim Grosbach4b905842013-09-20 23:08:21 +00003791/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003792/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003793bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003794 StringRef Name;
3795 bool EH = false;
3796 bool Debug = false;
3797
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003798 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003799 return TokError("Expected an identifier");
3800
3801 if (Name == ".eh_frame")
3802 EH = true;
3803 else if (Name == ".debug_frame")
3804 Debug = true;
3805
3806 if (getLexer().is(AsmToken::Comma)) {
3807 Lex();
3808
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003809 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003810 return TokError("Expected an identifier");
3811
3812 if (Name == ".eh_frame")
3813 EH = true;
3814 else if (Name == ".debug_frame")
3815 Debug = true;
3816 }
3817
3818 getStreamer().EmitCFISections(EH, Debug);
3819 return false;
3820}
3821
Jim Grosbach4b905842013-09-20 23:08:21 +00003822/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003823/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003824bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003825 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003826 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3827 if (check(parseIdentifier(Simple) || Simple != "simple",
3828 "unexpected token") ||
3829 parseToken(AsmToken::EndOfStatement))
3830 return addErrorSuffix(" in '.cfi_startproc' directive");
3831 }
Nirav Davea645433c2016-07-18 15:24:03 +00003832
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003833 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003834 return false;
3835}
3836
Jim Grosbach4b905842013-09-20 23:08:21 +00003837/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003838/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003839bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003840 getStreamer().EmitCFIEndProc();
3841 return false;
3842}
3843
Jim Grosbach4b905842013-09-20 23:08:21 +00003844/// \brief parse register name or number.
3845bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003846 SMLoc DirectiveLoc) {
3847 unsigned RegNo;
3848
3849 if (getLexer().isNot(AsmToken::Integer)) {
3850 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3851 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003852 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003853 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003854 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003855
3856 return false;
3857}
3858
Jim Grosbach4b905842013-09-20 23:08:21 +00003859/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003860/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003861bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003862 int64_t Register = 0, Offset = 0;
3863 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3864 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3865 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003866 return true;
3867
3868 getStreamer().EmitCFIDefCfa(Register, Offset);
3869 return false;
3870}
3871
Jim Grosbach4b905842013-09-20 23:08:21 +00003872/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003873/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003874bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003875 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003876 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003877 return true;
3878
3879 getStreamer().EmitCFIDefCfaOffset(Offset);
3880 return false;
3881}
3882
Jim Grosbach4b905842013-09-20 23:08:21 +00003883/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003884/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003885bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003886 int64_t Register1 = 0, Register2 = 0;
3887 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3888 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3889 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003890 return true;
3891
3892 getStreamer().EmitCFIRegister(Register1, Register2);
3893 return false;
3894}
3895
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003896/// parseDirectiveCFIWindowSave
3897/// ::= .cfi_window_save
3898bool AsmParser::parseDirectiveCFIWindowSave() {
3899 getStreamer().EmitCFIWindowSave();
3900 return false;
3901}
3902
Jim Grosbach4b905842013-09-20 23:08:21 +00003903/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003904/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003905bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003906 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003907 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003908 return true;
3909
3910 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3911 return false;
3912}
3913
Jim Grosbach4b905842013-09-20 23:08:21 +00003914/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003915/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003916bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003917 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003918 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003919 return true;
3920
3921 getStreamer().EmitCFIDefCfaRegister(Register);
3922 return false;
3923}
3924
Jim Grosbach4b905842013-09-20 23:08:21 +00003925/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003926/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003927bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003928 int64_t Register = 0;
3929 int64_t Offset = 0;
3930
Nirav Davea645433c2016-07-18 15:24:03 +00003931 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3932 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3933 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003934 return true;
3935
3936 getStreamer().EmitCFIOffset(Register, Offset);
3937 return false;
3938}
3939
Jim Grosbach4b905842013-09-20 23:08:21 +00003940/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003941/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003942bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003943 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003944
Nirav Davea645433c2016-07-18 15:24:03 +00003945 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3946 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3947 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003948 return true;
3949
3950 getStreamer().EmitCFIRelOffset(Register, Offset);
3951 return false;
3952}
3953
3954static bool isValidEncoding(int64_t Encoding) {
3955 if (Encoding & ~0xff)
3956 return false;
3957
3958 if (Encoding == dwarf::DW_EH_PE_omit)
3959 return true;
3960
3961 const unsigned Format = Encoding & 0xf;
3962 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3963 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3964 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3965 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3966 return false;
3967
3968 const unsigned Application = Encoding & 0x70;
3969 if (Application != dwarf::DW_EH_PE_absptr &&
3970 Application != dwarf::DW_EH_PE_pcrel)
3971 return false;
3972
3973 return true;
3974}
3975
Jim Grosbach4b905842013-09-20 23:08:21 +00003976/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003977/// IsPersonality true for cfi_personality, false for cfi_lsda
3978/// ::= .cfi_personality encoding, [symbol_name]
3979/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003980bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003981 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003982 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003983 return true;
3984 if (Encoding == dwarf::DW_EH_PE_omit)
3985 return false;
3986
Eli Bendersky17233942013-01-15 22:59:42 +00003987 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00003988 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
3989 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3990 check(parseIdentifier(Name), "expected identifier in directive"))
3991 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003992
Jim Grosbach6f482002015-05-18 18:43:14 +00003993 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003994
3995 if (IsPersonality)
3996 getStreamer().EmitCFIPersonality(Sym, Encoding);
3997 else
3998 getStreamer().EmitCFILsda(Sym, Encoding);
3999 return false;
4000}
4001
Jim Grosbach4b905842013-09-20 23:08:21 +00004002/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00004003/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004004bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004005 getStreamer().EmitCFIRememberState();
4006 return false;
4007}
4008
Jim Grosbach4b905842013-09-20 23:08:21 +00004009/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00004010/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004011bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004012 getStreamer().EmitCFIRestoreState();
4013 return false;
4014}
4015
Jim Grosbach4b905842013-09-20 23:08:21 +00004016/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00004017/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00004018bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004019 int64_t Register = 0;
4020
Jim Grosbach4b905842013-09-20 23:08:21 +00004021 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004022 return true;
4023
4024 getStreamer().EmitCFISameValue(Register);
4025 return false;
4026}
4027
Jim Grosbach4b905842013-09-20 23:08:21 +00004028/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00004029/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00004030bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004031 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00004032 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004033 return true;
4034
4035 getStreamer().EmitCFIRestore(Register);
4036 return false;
4037}
4038
Jim Grosbach4b905842013-09-20 23:08:21 +00004039/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00004040/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004041bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00004042 std::string Values;
4043 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004044 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004045 return true;
4046
4047 Values.push_back((uint8_t)CurrValue);
4048
4049 while (getLexer().is(AsmToken::Comma)) {
4050 Lex();
4051
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004052 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004053 return true;
4054
4055 Values.push_back((uint8_t)CurrValue);
4056 }
4057
4058 getStreamer().EmitCFIEscape(Values);
4059 return false;
4060}
4061
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00004062/// parseDirectiveCFIReturnColumn
4063/// ::= .cfi_return_column register
4064bool AsmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc) {
4065 int64_t Register = 0;
4066 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4067 return true;
4068 getStreamer().EmitCFIReturnColumn(Register);
4069 return false;
4070}
4071
Jim Grosbach4b905842013-09-20 23:08:21 +00004072/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00004073/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00004074bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00004075 if (parseToken(AsmToken::EndOfStatement,
4076 "unexpected token in '.cfi_signal_frame'"))
4077 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004078
4079 getStreamer().EmitCFISignalFrame();
4080 return false;
4081}
4082
Jim Grosbach4b905842013-09-20 23:08:21 +00004083/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00004084/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00004085bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004086 int64_t Register = 0;
4087
Jim Grosbach4b905842013-09-20 23:08:21 +00004088 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004089 return true;
4090
4091 getStreamer().EmitCFIUndefined(Register);
4092 return false;
4093}
4094
Michael Zuckerman56704612017-05-01 13:20:12 +00004095/// parseDirectiveAltmacro
4096/// ::= .altmacro
4097/// ::= .noaltmacro
4098bool AsmParser::parseDirectiveAltmacro(StringRef Directive) {
4099 if (getLexer().isNot(AsmToken::EndOfStatement))
4100 return TokError("unexpected token in '" + Directive + "' directive");
4101 if (Directive == ".altmacro")
4102 getLexer().SetAltMacroMode(true);
4103 else
4104 getLexer().SetAltMacroMode(false);
4105 return false;
4106}
4107
Jim Grosbach4b905842013-09-20 23:08:21 +00004108/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00004109/// ::= .macros_on
4110/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00004111bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004112 if (parseToken(AsmToken::EndOfStatement,
4113 "unexpected token in '" + Directive + "' directive"))
4114 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004115
Jim Grosbach4b905842013-09-20 23:08:21 +00004116 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00004117 return false;
4118}
4119
Jim Grosbach4b905842013-09-20 23:08:21 +00004120/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004121/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00004122bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004123 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004124 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00004125 return TokError("expected identifier in '.macro' directive");
4126
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004127 if (getLexer().is(AsmToken::Comma))
4128 Lex();
4129
Eli Bendersky17233942013-01-15 22:59:42 +00004130 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00004131 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004132
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00004133 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004134 return Error(Lexer.getLoc(),
4135 "Vararg parameter '" + Parameters.back().Name +
4136 "' should be last one in the list of parameters.");
4137
David Majnemer91fc4c22014-01-29 18:57:46 +00004138 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004139 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00004140 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004141
Coby Tayreebedaae02017-04-08 20:29:03 +00004142 // Emit an error if two (or more) named parameters share the same name
4143 for (const MCAsmMacroParameter& CurrParam : Parameters)
4144 if (CurrParam.Name.equals(Parameter.Name))
4145 return TokError("macro '" + Name + "' has multiple parameters"
4146 " named '" + Parameter.Name + "'");
4147
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004148 if (Lexer.is(AsmToken::Colon)) {
4149 Lex(); // consume ':'
4150
4151 SMLoc QualLoc;
4152 StringRef Qualifier;
4153
4154 QualLoc = Lexer.getLoc();
4155 if (parseIdentifier(Qualifier))
4156 return Error(QualLoc, "missing parameter qualifier for "
4157 "'" + Parameter.Name + "' in macro '" + Name + "'");
4158
4159 if (Qualifier == "req")
4160 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00004161 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004162 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004163 else
4164 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
4165 "for '" + Parameter.Name + "' in macro '" + Name + "'");
4166 }
4167
David Majnemer91fc4c22014-01-29 18:57:46 +00004168 if (getLexer().is(AsmToken::Equal)) {
4169 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004170
4171 SMLoc ParamLoc;
4172
4173 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004174 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00004175 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004176
4177 if (Parameter.Required)
4178 Warning(ParamLoc, "pointless default value for required parameter "
4179 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00004180 }
David Majnemer91fc4c22014-01-29 18:57:46 +00004181
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00004182 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00004183
4184 if (getLexer().is(AsmToken::Comma))
4185 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004186 }
4187
Nirav Dave1180e6892016-06-02 17:15:05 +00004188 // Eat just the end of statement.
4189 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004190
Nirav Dave1180e6892016-06-02 17:15:05 +00004191 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00004192 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004193 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00004194 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004195 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00004196 // Ignore Lexing errors in macros.
4197 while (Lexer.is(AsmToken::Error)) {
4198 Lexer.Lex();
4199 }
4200
Eli Bendersky17233942013-01-15 22:59:42 +00004201 // Check whether we have reached the end of the file.
4202 if (getLexer().is(AsmToken::Eof))
4203 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
4204
4205 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004206 if (getLexer().is(AsmToken::Identifier)) {
4207 if (getTok().getIdentifier() == ".endm" ||
4208 getTok().getIdentifier() == ".endmacro") {
4209 if (MacroDepth == 0) { // Outermost macro.
4210 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00004211 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004212 if (getLexer().isNot(AsmToken::EndOfStatement))
4213 return TokError("unexpected token in '" + EndToken.getIdentifier() +
4214 "' directive");
4215 break;
4216 } else {
4217 // Otherwise we just found the end of an inner macro.
4218 --MacroDepth;
4219 }
4220 } else if (getTok().getIdentifier() == ".macro") {
4221 // We allow nested macros. Those aren't instantiated until the outermost
4222 // macro is expanded so just ignore them for now.
4223 ++MacroDepth;
4224 }
Eli Bendersky17233942013-01-15 22:59:42 +00004225 }
4226
4227 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004228 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00004229 }
4230
Rafael Espindola22c38a02018-02-14 16:34:27 +00004231 if (getContext().lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00004232 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
4233 }
4234
4235 const char *BodyStart = StartToken.getLoc().getPointer();
4236 const char *BodyEnd = EndToken.getLoc().getPointer();
4237 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00004238 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Rafael Espindola22c38a02018-02-14 16:34:27 +00004239 getContext().defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00004240 return false;
4241}
4242
Jim Grosbach4b905842013-09-20 23:08:21 +00004243/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00004244///
4245/// With the support added for named parameters there may be code out there that
4246/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00004247/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00004248/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00004249/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00004250/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4251/// warning that the positional parameter found in body which have no effect.
4252/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00004253/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00004254/// intended or change the macro to use the named parameters. It is possible
4255/// this warning will trigger when the none of the named parameters are used
4256/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00004257void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00004258 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004259 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00004260 // If this macro is not defined with named parameters the warning we are
4261 // checking for here doesn't apply.
4262 unsigned NParameters = Parameters.size();
4263 if (NParameters == 0)
4264 return;
4265
4266 bool NamedParametersFound = false;
4267 bool PositionalParametersFound = false;
4268
4269 // Look at the body of the macro for use of both the named parameters and what
4270 // are likely to be positional parameters. This is what expandMacro() is
4271 // doing when it finds the parameters in the body.
4272 while (!Body.empty()) {
4273 // Scan for the next possible parameter.
4274 std::size_t End = Body.size(), Pos = 0;
4275 for (; Pos != End; ++Pos) {
4276 // Check for a substitution or escape.
4277 // This macro is defined with parameters, look for \foo, \bar, etc.
4278 if (Body[Pos] == '\\' && Pos + 1 != End)
4279 break;
4280
4281 // This macro should have parameters, but look for $0, $1, ..., $n too.
4282 if (Body[Pos] != '$' || Pos + 1 == End)
4283 continue;
4284 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004285 if (Next == '$' || Next == 'n' ||
4286 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004287 break;
4288 }
4289
4290 // Check if we reached the end.
4291 if (Pos == End)
4292 break;
4293
4294 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004295 switch (Body[Pos + 1]) {
4296 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004297 case '$':
4298 break;
4299
Jim Grosbach4b905842013-09-20 23:08:21 +00004300 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004301 case 'n':
4302 PositionalParametersFound = true;
4303 break;
4304
Jim Grosbach4b905842013-09-20 23:08:21 +00004305 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004306 default: {
4307 PositionalParametersFound = true;
4308 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004309 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004310 }
4311 Pos += 2;
4312 } else {
4313 unsigned I = Pos + 1;
4314 while (isIdentifierChar(Body[I]) && I + 1 != End)
4315 ++I;
4316
Jim Grosbach4b905842013-09-20 23:08:21 +00004317 const char *Begin = Body.data() + Pos + 1;
4318 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004319 unsigned Index = 0;
4320 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004321 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004322 break;
4323
4324 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004325 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4326 Pos += 3;
4327 else {
4328 Pos = I;
4329 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004330 } else {
4331 NamedParametersFound = true;
4332 Pos += 1 + Argument.size();
4333 }
4334 }
4335 // Update the scan point.
4336 Body = Body.substr(Pos);
4337 }
4338
4339 if (!NamedParametersFound && PositionalParametersFound)
4340 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4341 "used in macro body, possible positional parameter "
4342 "found in body which will have no effect");
4343}
4344
Nico Weber155dccd12014-07-24 17:08:39 +00004345/// parseDirectiveExitMacro
4346/// ::= .exitm
4347bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004348 if (parseToken(AsmToken::EndOfStatement,
4349 "unexpected token in '" + Directive + "' directive"))
4350 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004351
4352 if (!isInsideMacroInstantiation())
4353 return TokError("unexpected '" + Directive + "' in file, "
4354 "no current macro definition");
4355
4356 // Exit all conditionals that are active in the current macro.
4357 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4358 TheCondState = TheCondStack.back();
4359 TheCondStack.pop_back();
4360 }
4361
4362 handleMacroExit();
4363 return false;
4364}
4365
Jim Grosbach4b905842013-09-20 23:08:21 +00004366/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004367/// ::= .endm
4368/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004369bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004370 if (getLexer().isNot(AsmToken::EndOfStatement))
4371 return TokError("unexpected token in '" + Directive + "' directive");
4372
4373 // If we are inside a macro instantiation, terminate the current
4374 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004375 if (isInsideMacroInstantiation()) {
4376 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004377 return false;
4378 }
4379
4380 // Otherwise, this .endmacro is a stray entry in the file; well formed
4381 // .endmacro directives are handled during the macro definition parsing.
4382 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004383 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004384}
4385
Jim Grosbach4b905842013-09-20 23:08:21 +00004386/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004387/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004388bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004389 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004390 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004391 if (parseTokenLoc(Loc) ||
4392 check(parseIdentifier(Name), Loc,
4393 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004394 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004395 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004396 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004397
Rafael Espindola22c38a02018-02-14 16:34:27 +00004398 if (!getContext().lookupMacro(Name))
Nirav Dave1ab71992016-07-18 19:35:21 +00004399 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4400
Rafael Espindola22c38a02018-02-14 16:34:27 +00004401 getContext().undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004402 return false;
4403}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004404
Jim Grosbach4b905842013-09-20 23:08:21 +00004405/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004406/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004407bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004408 // Expect a single argument: an expression that evaluates to a constant
4409 // in the inclusive range 0-30.
4410 SMLoc ExprLoc = getLexer().getLoc();
4411 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004412 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004413 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4414 "in '.bundle_align_mode' "
4415 "directive") ||
4416 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4417 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004418 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004419
4420 // Because of AlignSizePow2's verified range we can safely truncate it to
4421 // unsigned.
4422 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4423 return false;
4424}
4425
Jim Grosbach4b905842013-09-20 23:08:21 +00004426/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004427/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004428bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004429 if (checkForValidSection())
4430 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004431 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004432
Nirav Dave1a9044b2016-10-24 14:35:29 +00004433 StringRef Option;
4434 SMLoc Loc = getTok().getLoc();
4435 const char *kInvalidOptionError =
4436 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004437
Nirav Dave1a9044b2016-10-24 14:35:29 +00004438 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004439 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4440 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004441 parseToken(AsmToken::EndOfStatement,
4442 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004443 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004444 AlignToEnd = true;
4445 }
4446
Eli Bendersky802b6282013-01-07 21:51:08 +00004447 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004448 return false;
4449}
4450
Jim Grosbach4b905842013-09-20 23:08:21 +00004451/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004452/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004453bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004454 if (checkForValidSection() ||
4455 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004456 "unexpected token in '.bundle_unlock' directive"))
4457 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004458
4459 getStreamer().EmitBundleUnlock();
4460 return false;
4461}
4462
Jim Grosbach4b905842013-09-20 23:08:21 +00004463/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004464/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004465bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Petr Hosek67a94a72016-05-28 05:57:48 +00004466 SMLoc NumBytesLoc = Lexer.getLoc();
4467 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004468 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004469 return true;
4470
4471 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004472 if (parseOptionalToken(AsmToken::Comma))
4473 if (parseAbsoluteExpression(FillExpr))
4474 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4475 if (parseToken(AsmToken::EndOfStatement))
4476 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004477
Eli Bendersky17233942013-01-15 22:59:42 +00004478 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004479 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004480
4481 return false;
4482}
4483
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004484/// parseDirectiveDCB
4485/// ::= .dcb.{b, l, w} expression, expression
4486bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004487 SMLoc NumValuesLoc = Lexer.getLoc();
4488 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004489 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004490 return true;
4491
4492 if (NumValues < 0) {
4493 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4494 return false;
4495 }
4496
4497 if (parseToken(AsmToken::Comma,
4498 "unexpected token in '" + Twine(IDVal) + "' directive"))
4499 return true;
4500
4501 const MCExpr *Value;
4502 SMLoc ExprLoc = getLexer().getLoc();
4503 if (parseExpression(Value))
4504 return true;
4505
4506 // Special case constant expressions to match code generator.
4507 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4508 assert(Size <= 8 && "Invalid size");
4509 uint64_t IntValue = MCE->getValue();
4510 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4511 return Error(ExprLoc, "literal value out of range for directive");
4512 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4513 getStreamer().EmitIntValue(IntValue, Size);
4514 } else {
4515 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4516 getStreamer().EmitValue(Value, Size, ExprLoc);
4517 }
4518
4519 if (parseToken(AsmToken::EndOfStatement,
4520 "unexpected token in '" + Twine(IDVal) + "' directive"))
4521 return true;
4522
4523 return false;
4524}
4525
4526/// parseDirectiveRealDCB
4527/// ::= .dcb.{d, s} expression, expression
4528bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004529 SMLoc NumValuesLoc = Lexer.getLoc();
4530 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004531 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004532 return true;
4533
4534 if (NumValues < 0) {
4535 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4536 return false;
4537 }
4538
4539 if (parseToken(AsmToken::Comma,
4540 "unexpected token in '" + Twine(IDVal) + "' directive"))
4541 return true;
4542
4543 APInt AsInt;
4544 if (parseRealValue(Semantics, AsInt))
4545 return true;
4546
4547 if (parseToken(AsmToken::EndOfStatement,
4548 "unexpected token in '" + Twine(IDVal) + "' directive"))
4549 return true;
4550
4551 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4552 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4553 AsInt.getBitWidth() / 8);
4554
4555 return false;
4556}
4557
Petr Hosek85b2f672016-09-23 21:53:36 +00004558/// parseDirectiveDS
4559/// ::= .ds.{b, d, l, p, s, w, x} expression
4560bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004561 SMLoc NumValuesLoc = Lexer.getLoc();
4562 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004563 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004564 return true;
4565
4566 if (NumValues < 0) {
4567 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4568 return false;
4569 }
4570
4571 if (parseToken(AsmToken::EndOfStatement,
4572 "unexpected token in '" + Twine(IDVal) + "' directive"))
4573 return true;
4574
4575 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4576 getStreamer().emitFill(Size, 0);
4577
4578 return false;
4579}
4580
Jim Grosbach4b905842013-09-20 23:08:21 +00004581/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004582/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004583bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004584 if (checkForValidSection())
4585 return true;
4586
Nirav Dave1a9044b2016-10-24 14:35:29 +00004587 auto parseOp = [&]() -> bool {
4588 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004589 if (parseExpression(Value))
4590 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004591 if (Signed)
4592 getStreamer().EmitSLEB128Value(Value);
4593 else
4594 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004595 return false;
4596 };
Eli Bendersky17233942013-01-15 22:59:42 +00004597
Nirav Dave1a9044b2016-10-24 14:35:29 +00004598 if (parseMany(parseOp))
4599 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004600
4601 return false;
4602}
4603
Jim Grosbach4b905842013-09-20 23:08:21 +00004604/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004605/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004606bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004607 auto parseOp = [&]() -> bool {
4608 StringRef Name;
4609 SMLoc Loc = getTok().getLoc();
4610 if (parseIdentifier(Name))
4611 return Error(Loc, "expected identifier");
4612 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004613
Nirav Dave1a9044b2016-10-24 14:35:29 +00004614 // Assembler local symbols don't make any sense here. Complain loudly.
4615 if (Sym->isTemporary())
4616 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004617
Nirav Dave1a9044b2016-10-24 14:35:29 +00004618 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4619 return Error(Loc, "unable to emit symbol attribute");
4620 return false;
4621 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004622
Nirav Dave1a9044b2016-10-24 14:35:29 +00004623 if (parseMany(parseOp))
4624 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004625 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004626}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004627
Jim Grosbach4b905842013-09-20 23:08:21 +00004628/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004629/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004630bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004631 if (checkForValidSection())
4632 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004633
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004634 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004635 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004636 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004637 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004638
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004639 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004640 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004641
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004642 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004643 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004644 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004645
4646 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004647 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004648 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004649 return true;
4650
4651 int64_t Pow2Alignment = 0;
4652 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004653 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004654 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004655 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004656 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004657 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004658
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004659 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4660 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004661 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4662
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004663 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004664 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4665 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004666 if (!isPowerOf2_64(Pow2Alignment))
4667 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4668 Pow2Alignment = Log2_64(Pow2Alignment);
4669 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004670 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004671
Nirav Dave1a9044b2016-10-24 14:35:29 +00004672 if (parseToken(AsmToken::EndOfStatement,
4673 "unexpected token in '.comm' or '.lcomm' directive"))
4674 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004675
Chris Lattner28ad7542009-07-09 17:25:12 +00004676 // NOTE: a size of zero for a .comm should create a undefined symbol
4677 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004678 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004679 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004680 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004681
Eric Christopherbc818852010-05-14 01:38:54 +00004682 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004683 // may internally end up wanting an alignment in bytes.
4684 // FIXME: Diagnose overflow.
4685 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004686 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004687 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004688
Rafael Espindola13a79bb2017-02-02 21:26:06 +00004689 Sym->redefineIfPossible();
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004690 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004691 return Error(IDLoc, "invalid symbol redefinition");
4692
Chris Lattner28ad7542009-07-09 17:25:12 +00004693 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004694 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004695 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004696 return false;
4697 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004698
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004699 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004700 return false;
4701}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004702
Jim Grosbach4b905842013-09-20 23:08:21 +00004703/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004704/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004705bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004706 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004707 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004708
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004709 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004710 if (parseToken(AsmToken::EndOfStatement,
4711 "unexpected token in '.abort' directive"))
4712 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004713
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004714 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004715 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004716 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004717 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004718 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004719
4720 return false;
4721}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004722
Jim Grosbach4b905842013-09-20 23:08:21 +00004723/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004724/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004725bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004726 // Allow the strings to have escaped octal character sequence.
4727 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004728 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004729
Nirav Davea645433c2016-07-18 15:24:03 +00004730 if (check(getTok().isNot(AsmToken::String),
4731 "expected string in '.include' directive") ||
4732 parseEscapedString(Filename) ||
4733 check(getTok().isNot(AsmToken::EndOfStatement),
4734 "unexpected token in '.include' directive") ||
4735 // Attempt to switch the lexer to the included file before consuming the
4736 // end of statement to avoid losing it when we switch.
4737 check(enterIncludeFile(Filename), IncludeLoc,
4738 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004739 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004740
4741 return false;
4742}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004743
Jim Grosbach4b905842013-09-20 23:08:21 +00004744/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004745/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004746bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004747 // Allow the strings to have escaped octal character sequence.
4748 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004749 SMLoc IncbinLoc = getTok().getLoc();
4750 if (check(getTok().isNot(AsmToken::String),
4751 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00004752 parseEscapedString(Filename))
4753 return true;
4754
4755 int64_t Skip = 0;
4756 const MCExpr *Count = nullptr;
4757 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004758 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00004759 // The skip expression can be omitted while specifying the count, e.g:
4760 // .incbin "filename",,4
4761 if (getTok().isNot(AsmToken::Comma)) {
4762 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4763 return true;
4764 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00004765 if (parseOptionalToken(AsmToken::Comma)) {
4766 CountLoc = getTok().getLoc();
4767 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00004768 return true;
4769 }
4770 }
4771
4772 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004773 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004774 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004775
Petr Hosek2f4ac442016-09-23 00:41:06 +00004776 if (check(Skip < 0, SkipLoc, "skip is negative"))
4777 return true;
4778
Nirav Dave1ab71992016-07-18 19:35:21 +00004779 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00004780 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00004781 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004782 return false;
4783}
4784
Jim Grosbach4b905842013-09-20 23:08:21 +00004785/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004786/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4787bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004788 TheCondStack.push_back(TheCondState);
4789 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004790 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004791 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004792 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004793 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004794 if (parseAbsoluteExpression(ExprValue) ||
4795 parseToken(AsmToken::EndOfStatement,
4796 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004797 return true;
4798
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004799 switch (DirKind) {
4800 default:
4801 llvm_unreachable("unsupported directive");
4802 case DK_IF:
4803 case DK_IFNE:
4804 break;
4805 case DK_IFEQ:
4806 ExprValue = ExprValue == 0;
4807 break;
4808 case DK_IFGE:
4809 ExprValue = ExprValue >= 0;
4810 break;
4811 case DK_IFGT:
4812 ExprValue = ExprValue > 0;
4813 break;
4814 case DK_IFLE:
4815 ExprValue = ExprValue <= 0;
4816 break;
4817 case DK_IFLT:
4818 ExprValue = ExprValue < 0;
4819 break;
4820 }
4821
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004822 TheCondState.CondMet = ExprValue;
4823 TheCondState.Ignore = !TheCondState.CondMet;
4824 }
4825
4826 return false;
4827}
4828
Jim Grosbach4b905842013-09-20 23:08:21 +00004829/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004830/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004831bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004832 TheCondStack.push_back(TheCondState);
4833 TheCondState.TheCond = AsmCond::IfCond;
4834
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004835 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004836 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004837 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004838 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004839
Nirav Davea645433c2016-07-18 15:24:03 +00004840 if (parseToken(AsmToken::EndOfStatement,
4841 "unexpected token in '.ifb' directive"))
4842 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004843
4844 TheCondState.CondMet = ExpectBlank == Str.empty();
4845 TheCondState.Ignore = !TheCondState.CondMet;
4846 }
4847
4848 return false;
4849}
4850
Jim Grosbach4b905842013-09-20 23:08:21 +00004851/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004852/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004853/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004854bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004855 TheCondStack.push_back(TheCondState);
4856 TheCondState.TheCond = AsmCond::IfCond;
4857
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004858 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004859 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004860 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004861 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004862
Nirav Davea645433c2016-07-18 15:24:03 +00004863 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4864 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004865
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004866 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004867
Nirav Davea645433c2016-07-18 15:24:03 +00004868 if (parseToken(AsmToken::EndOfStatement,
4869 "unexpected token in '.ifc' directive"))
4870 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004871
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004872 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004873 TheCondState.Ignore = !TheCondState.CondMet;
4874 }
4875
4876 return false;
4877}
4878
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004879/// parseDirectiveIfeqs
4880/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004881bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004882 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004883 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004884 return TokError("expected string parameter for '.ifeqs' directive");
4885 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004886 }
4887
4888 StringRef String1 = getTok().getStringContents();
4889 Lex();
4890
4891 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004892 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004893 return TokError(
4894 "expected comma after first string for '.ifeqs' directive");
4895 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004896 }
4897
4898 Lex();
4899
4900 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004901 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004902 return TokError("expected string parameter for '.ifeqs' directive");
4903 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004904 }
4905
4906 StringRef String2 = getTok().getStringContents();
4907 Lex();
4908
4909 TheCondStack.push_back(TheCondState);
4910 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004911 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004912 TheCondState.Ignore = !TheCondState.CondMet;
4913
4914 return false;
4915}
4916
Jim Grosbach4b905842013-09-20 23:08:21 +00004917/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004918/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004919bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004920 StringRef Name;
4921 TheCondStack.push_back(TheCondState);
4922 TheCondState.TheCond = AsmCond::IfCond;
4923
4924 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004925 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004926 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00004927 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4928 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4929 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004930
Jim Grosbach6f482002015-05-18 18:43:14 +00004931 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004932
4933 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004934 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004935 else
Craig Topper353eda42014-04-24 06:44:33 +00004936 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004937 TheCondState.Ignore = !TheCondState.CondMet;
4938 }
4939
4940 return false;
4941}
4942
Jim Grosbach4b905842013-09-20 23:08:21 +00004943/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004944/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004945bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004946 if (TheCondState.TheCond != AsmCond::IfCond &&
4947 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004948 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
4949 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004950 TheCondState.TheCond = AsmCond::ElseIfCond;
4951
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004952 bool LastIgnoreState = false;
4953 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004954 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004955 if (LastIgnoreState || TheCondState.CondMet) {
4956 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004957 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004958 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004959 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004960 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004961 return true;
4962
Nirav Dave1a9044b2016-10-24 14:35:29 +00004963 if (parseToken(AsmToken::EndOfStatement,
4964 "unexpected token in '.elseif' directive"))
4965 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004966
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004967 TheCondState.CondMet = ExprValue;
4968 TheCondState.Ignore = !TheCondState.CondMet;
4969 }
4970
4971 return false;
4972}
4973
Jim Grosbach4b905842013-09-20 23:08:21 +00004974/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004975/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004976bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004977 if (parseToken(AsmToken::EndOfStatement,
4978 "unexpected token in '.else' directive"))
4979 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004980
4981 if (TheCondState.TheCond != AsmCond::IfCond &&
4982 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004983 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
4984 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004985 TheCondState.TheCond = AsmCond::ElseCond;
4986 bool LastIgnoreState = false;
4987 if (!TheCondStack.empty())
4988 LastIgnoreState = TheCondStack.back().Ignore;
4989 if (LastIgnoreState || TheCondState.CondMet)
4990 TheCondState.Ignore = true;
4991 else
4992 TheCondState.Ignore = false;
4993
4994 return false;
4995}
4996
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004997/// parseDirectiveEnd
4998/// ::= .end
4999bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005000 if (parseToken(AsmToken::EndOfStatement,
5001 "unexpected token in '.end' directive"))
5002 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005003
5004 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00005005 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005006
5007 return false;
5008}
5009
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005010/// parseDirectiveError
5011/// ::= .err
5012/// ::= .error [string]
5013bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
5014 if (!TheCondStack.empty()) {
5015 if (TheCondStack.back().Ignore) {
5016 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005017 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005018 }
5019 }
5020
5021 if (!WithMessage)
5022 return Error(L, ".err encountered");
5023
5024 StringRef Message = ".error directive invoked in source file";
5025 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005026 if (Lexer.isNot(AsmToken::String))
5027 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005028
5029 Message = getTok().getStringContents();
5030 Lex();
5031 }
5032
Nirav Dave2364748a2016-09-16 18:30:20 +00005033 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005034}
5035
Nico Weber404012b2014-07-24 16:26:06 +00005036/// parseDirectiveWarning
5037/// ::= .warning [string]
5038bool AsmParser::parseDirectiveWarning(SMLoc L) {
5039 if (!TheCondStack.empty()) {
5040 if (TheCondStack.back().Ignore) {
5041 eatToEndOfStatement();
5042 return false;
5043 }
5044 }
5045
5046 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00005047
5048 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005049 if (Lexer.isNot(AsmToken::String))
5050 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00005051
5052 Message = getTok().getStringContents();
5053 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00005054 if (parseToken(AsmToken::EndOfStatement,
5055 "expected end of statement in '.warning' directive"))
5056 return true;
Nico Weber404012b2014-07-24 16:26:06 +00005057 }
5058
Nirav Dave2364748a2016-09-16 18:30:20 +00005059 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00005060}
5061
Jim Grosbach4b905842013-09-20 23:08:21 +00005062/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005063/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00005064bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005065 if (parseToken(AsmToken::EndOfStatement,
5066 "unexpected token in '.endif' directive"))
5067 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005068
Jim Grosbach4b905842013-09-20 23:08:21 +00005069 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00005070 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
5071 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005072 if (!TheCondStack.empty()) {
5073 TheCondState = TheCondStack.back();
5074 TheCondStack.pop_back();
5075 }
5076
5077 return false;
5078}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00005079
Eli Bendersky17233942013-01-15 22:59:42 +00005080void AsmParser::initializeDirectiveKindMap() {
5081 DirectiveKindMap[".set"] = DK_SET;
5082 DirectiveKindMap[".equ"] = DK_EQU;
5083 DirectiveKindMap[".equiv"] = DK_EQUIV;
5084 DirectiveKindMap[".ascii"] = DK_ASCII;
5085 DirectiveKindMap[".asciz"] = DK_ASCIZ;
5086 DirectiveKindMap[".string"] = DK_STRING;
5087 DirectiveKindMap[".byte"] = DK_BYTE;
5088 DirectiveKindMap[".short"] = DK_SHORT;
5089 DirectiveKindMap[".value"] = DK_VALUE;
5090 DirectiveKindMap[".2byte"] = DK_2BYTE;
5091 DirectiveKindMap[".long"] = DK_LONG;
5092 DirectiveKindMap[".int"] = DK_INT;
5093 DirectiveKindMap[".4byte"] = DK_4BYTE;
5094 DirectiveKindMap[".quad"] = DK_QUAD;
5095 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00005096 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00005097 DirectiveKindMap[".single"] = DK_SINGLE;
5098 DirectiveKindMap[".float"] = DK_FLOAT;
5099 DirectiveKindMap[".double"] = DK_DOUBLE;
5100 DirectiveKindMap[".align"] = DK_ALIGN;
5101 DirectiveKindMap[".align32"] = DK_ALIGN32;
5102 DirectiveKindMap[".balign"] = DK_BALIGN;
5103 DirectiveKindMap[".balignw"] = DK_BALIGNW;
5104 DirectiveKindMap[".balignl"] = DK_BALIGNL;
5105 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
5106 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
5107 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
5108 DirectiveKindMap[".org"] = DK_ORG;
5109 DirectiveKindMap[".fill"] = DK_FILL;
5110 DirectiveKindMap[".zero"] = DK_ZERO;
5111 DirectiveKindMap[".extern"] = DK_EXTERN;
5112 DirectiveKindMap[".globl"] = DK_GLOBL;
5113 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00005114 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
5115 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
5116 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
5117 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
5118 DirectiveKindMap[".reference"] = DK_REFERENCE;
5119 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
5120 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
5121 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
5122 DirectiveKindMap[".comm"] = DK_COMM;
5123 DirectiveKindMap[".common"] = DK_COMMON;
5124 DirectiveKindMap[".lcomm"] = DK_LCOMM;
5125 DirectiveKindMap[".abort"] = DK_ABORT;
5126 DirectiveKindMap[".include"] = DK_INCLUDE;
5127 DirectiveKindMap[".incbin"] = DK_INCBIN;
5128 DirectiveKindMap[".code16"] = DK_CODE16;
5129 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
5130 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005131 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00005132 DirectiveKindMap[".irp"] = DK_IRP;
5133 DirectiveKindMap[".irpc"] = DK_IRPC;
5134 DirectiveKindMap[".endr"] = DK_ENDR;
5135 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
5136 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
5137 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
5138 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00005139 DirectiveKindMap[".ifeq"] = DK_IFEQ;
5140 DirectiveKindMap[".ifge"] = DK_IFGE;
5141 DirectiveKindMap[".ifgt"] = DK_IFGT;
5142 DirectiveKindMap[".ifle"] = DK_IFLE;
5143 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00005144 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00005145 DirectiveKindMap[".ifb"] = DK_IFB;
5146 DirectiveKindMap[".ifnb"] = DK_IFNB;
5147 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005148 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00005149 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00005150 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00005151 DirectiveKindMap[".ifdef"] = DK_IFDEF;
5152 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
5153 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
5154 DirectiveKindMap[".elseif"] = DK_ELSEIF;
5155 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005156 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00005157 DirectiveKindMap[".endif"] = DK_ENDIF;
5158 DirectiveKindMap[".skip"] = DK_SKIP;
5159 DirectiveKindMap[".space"] = DK_SPACE;
5160 DirectiveKindMap[".file"] = DK_FILE;
5161 DirectiveKindMap[".line"] = DK_LINE;
5162 DirectiveKindMap[".loc"] = DK_LOC;
5163 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005164 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005165 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005166 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
5167 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00005168 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005169 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00005170 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005171 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
5172 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00005173 DirectiveKindMap[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET;
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00005174 DirectiveKindMap[".cv_fpo_data"] = DK_CV_FPO_DATA;
Eli Bendersky17233942013-01-15 22:59:42 +00005175 DirectiveKindMap[".sleb128"] = DK_SLEB128;
5176 DirectiveKindMap[".uleb128"] = DK_ULEB128;
5177 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
5178 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
5179 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
5180 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
5181 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
5182 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
5183 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
5184 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
5185 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
5186 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
5187 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
5188 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
5189 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
5190 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
5191 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
5192 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00005193 DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN;
Eli Bendersky17233942013-01-15 22:59:42 +00005194 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
5195 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
5196 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00005197 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00005198 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
5199 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
5200 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00005201 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00005202 DirectiveKindMap[".endm"] = DK_ENDM;
5203 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
5204 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005205 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005206 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00005207 DirectiveKindMap[".warning"] = DK_WARNING;
Michael Zuckerman56704612017-05-01 13:20:12 +00005208 DirectiveKindMap[".altmacro"] = DK_ALTMACRO;
5209 DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00005210 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00005211 DirectiveKindMap[".dc"] = DK_DC;
5212 DirectiveKindMap[".dc.a"] = DK_DC_A;
5213 DirectiveKindMap[".dc.b"] = DK_DC_B;
5214 DirectiveKindMap[".dc.d"] = DK_DC_D;
5215 DirectiveKindMap[".dc.l"] = DK_DC_L;
5216 DirectiveKindMap[".dc.s"] = DK_DC_S;
5217 DirectiveKindMap[".dc.w"] = DK_DC_W;
5218 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00005219 DirectiveKindMap[".dcb"] = DK_DCB;
5220 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
5221 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
5222 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
5223 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
5224 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
5225 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00005226 DirectiveKindMap[".ds"] = DK_DS;
5227 DirectiveKindMap[".ds.b"] = DK_DS_B;
5228 DirectiveKindMap[".ds.d"] = DK_DS_D;
5229 DirectiveKindMap[".ds.l"] = DK_DS_L;
5230 DirectiveKindMap[".ds.p"] = DK_DS_P;
5231 DirectiveKindMap[".ds.s"] = DK_DS_S;
5232 DirectiveKindMap[".ds.w"] = DK_DS_W;
5233 DirectiveKindMap[".ds.x"] = DK_DS_X;
Coby Tayree01e53202017-10-02 14:36:31 +00005234 DirectiveKindMap[".print"] = DK_PRINT;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00005235}
5236
Jim Grosbach4b905842013-09-20 23:08:21 +00005237MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005238 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005239
Rafael Espindola34b9c512012-06-03 23:57:14 +00005240 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005241 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005242 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00005243 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005244 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00005245 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005246 }
5247
Rafael Espindola34b9c512012-06-03 23:57:14 +00005248 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00005249 (getTok().getIdentifier() == ".rept" ||
5250 getTok().getIdentifier() == ".irp" ||
5251 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005252 ++NestLevel;
5253 }
5254
5255 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00005256 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005257 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005258 EndToken = getTok();
5259 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005260 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005261 printError(getTok().getLoc(),
5262 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00005263 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005264 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005265 break;
5266 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005267 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005268 }
5269
Rafael Espindola34b9c512012-06-03 23:57:14 +00005270 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005271 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005272 }
5273
5274 const char *BodyStart = StartToken.getLoc().getPointer();
5275 const char *BodyEnd = EndToken.getLoc().getPointer();
5276 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5277
Rafael Espindola34b9c512012-06-03 23:57:14 +00005278 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005279 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00005280 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005281}
5282
Jim Grosbach4b905842013-09-20 23:08:21 +00005283void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005284 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005285 OS << ".endr\n";
5286
Rafael Espindola3560ff22014-08-27 20:03:13 +00005287 std::unique_ptr<MemoryBuffer> Instantiation =
5288 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005289
Rafael Espindola34b9c512012-06-03 23:57:14 +00005290 // Create the macro instantiation object and add to the current macro
5291 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005292 MacroInstantiation *MI = new MacroInstantiation(
5293 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005294 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005295
Rafael Espindola34b9c512012-06-03 23:57:14 +00005296 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005297 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005298 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005299 Lex();
5300}
5301
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005302/// parseDirectiveRept
5303/// ::= .rep | .rept count
5304bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005305 const MCExpr *CountExpr;
5306 SMLoc CountLoc = getTok().getLoc();
5307 if (parseExpression(CountExpr))
5308 return true;
5309
Rafael Espindola34b9c512012-06-03 23:57:14 +00005310 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00005311 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005312 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5313 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005314
Nirav Davea645433c2016-07-18 15:24:03 +00005315 if (check(Count < 0, CountLoc, "Count is negative") ||
5316 parseToken(AsmToken::EndOfStatement,
5317 "unexpected token in '" + Dir + "' directive"))
5318 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005319
5320 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005321 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005322 if (!M)
5323 return true;
5324
5325 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5326 // to hold the macro body with substitutions.
5327 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005328 raw_svector_ostream OS(Buf);
5329 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005330 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5331 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005332 return true;
5333 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005334 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005335
5336 return false;
5337}
5338
Jim Grosbach4b905842013-09-20 23:08:21 +00005339/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005340/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005341bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005342 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005343 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005344 if (check(parseIdentifier(Parameter.Name),
5345 "expected identifier in '.irp' directive") ||
5346 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5347 parseMacroArguments(nullptr, A) ||
5348 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005349 return true;
5350
Rafael Espindola768b41c2012-06-15 14:02:34 +00005351 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005352 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005353 if (!M)
5354 return true;
5355
5356 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5357 // to hold the macro body with substitutions.
5358 SmallString<256> Buf;
5359 raw_svector_ostream OS(Buf);
5360
Craig Topper84008482015-10-10 05:38:14 +00005361 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005362 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5363 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005364 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005365 return true;
5366 }
5367
Jim Grosbach4b905842013-09-20 23:08:21 +00005368 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005369
5370 return false;
5371}
5372
Jim Grosbach4b905842013-09-20 23:08:21 +00005373/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005374/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005375bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005376 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005377 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005378
5379 if (check(parseIdentifier(Parameter.Name),
5380 "expected identifier in '.irpc' directive") ||
5381 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5382 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005383 return true;
5384
5385 if (A.size() != 1 || A.front().size() != 1)
5386 return TokError("unexpected token in '.irpc' directive");
5387
5388 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005389 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5390 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005391
5392 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005393 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005394 if (!M)
5395 return true;
5396
5397 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5398 // to hold the macro body with substitutions.
5399 SmallString<256> Buf;
5400 raw_svector_ostream OS(Buf);
5401
5402 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005403 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005404 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005405 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005406
Toma Tabacu217116e2015-04-27 10:50:29 +00005407 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5408 // This is undocumented, but GAS seems to support it.
5409 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005410 return true;
5411 }
5412
Jim Grosbach4b905842013-09-20 23:08:21 +00005413 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005414
5415 return false;
5416}
5417
Jim Grosbach4b905842013-09-20 23:08:21 +00005418bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005419 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005420 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005421
5422 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005423 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005424 assert(getLexer().is(AsmToken::EndOfStatement));
5425
Jim Grosbach4b905842013-09-20 23:08:21 +00005426 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005427 return false;
5428}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005429
Jim Grosbach4b905842013-09-20 23:08:21 +00005430bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005431 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005432 const MCExpr *Value;
5433 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005434 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005435 return true;
5436 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5437 if (!MCE)
5438 return Error(ExprLoc, "unexpected expression in _emit");
5439 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005440 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005441 return Error(ExprLoc, "literal value out of range for directive");
5442
Craig Topper7d5b2312015-10-10 05:25:02 +00005443 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005444 return false;
5445}
5446
Jim Grosbach4b905842013-09-20 23:08:21 +00005447bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005448 const MCExpr *Value;
5449 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005450 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005451 return true;
5452 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5453 if (!MCE)
5454 return Error(ExprLoc, "unexpected expression in align");
5455 uint64_t IntValue = MCE->getValue();
5456 if (!isPowerOf2_64(IntValue))
5457 return Error(ExprLoc, "literal value not a power of two greater then zero");
5458
Craig Topper7d5b2312015-10-10 05:25:02 +00005459 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005460 return false;
5461}
5462
Coby Tayree01e53202017-10-02 14:36:31 +00005463bool AsmParser::parseDirectivePrint(SMLoc DirectiveLoc) {
5464 const AsmToken StrTok = getTok();
5465 Lex();
5466 if (StrTok.isNot(AsmToken::String) || StrTok.getString().front() != '"')
5467 return Error(DirectiveLoc, "expected double quoted string after .print");
5468 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5469 return true;
5470 llvm::outs() << StrTok.getStringContents() << '\n';
5471 return false;
5472}
5473
Chad Rosierf43fcf52013-02-13 21:27:17 +00005474// We are comparing pointers, but the pointers are relative to a single string.
5475// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005476static int rewritesSort(const AsmRewrite *AsmRewriteA,
5477 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005478 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5479 return -1;
5480 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5481 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005482
Chad Rosierfce4fab2013-04-08 17:43:47 +00005483 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5484 // rewrite to the same location. Make sure the SizeDirective rewrite is
5485 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5486 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005487 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5488 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005489 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005490
Jim Grosbach4b905842013-09-20 23:08:21 +00005491 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5492 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005493 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005494 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005495}
5496
Jim Grosbach4b905842013-09-20 23:08:21 +00005497bool AsmParser::parseMSInlineAsm(
5498 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00005499 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
Jim Grosbach4b905842013-09-20 23:08:21 +00005500 SmallVectorImpl<std::string> &Constraints,
5501 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5502 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005503 SmallVector<void *, 4> InputDecls;
5504 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005505 SmallVector<bool, 4> InputDeclsAddressOf;
5506 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005507 SmallVector<std::string, 4> InputConstraints;
5508 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005509 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005510
Benjamin Kramer1a136112013-02-15 20:37:21 +00005511 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005512
5513 // Prime the lexer.
5514 Lex();
5515
5516 // While we have input, parse each statement.
5517 unsigned InputIdx = 0;
5518 unsigned OutputIdx = 0;
5519 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005520 // Parse curly braces marking block start/end
5521 if (parseCurlyBlockScope(AsmStrRewrites))
5522 continue;
5523
Eli Friedman0f4871d2012-10-22 23:58:19 +00005524 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005525 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005526
Nirav Dave2364748a2016-09-16 18:30:20 +00005527 if (StatementErr || Info.ParseError) {
5528 // Emit pending errors if any exist.
5529 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005530 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005531 }
5532
5533 // No pending error should exist here.
5534 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005535
Benjamin Kramer1a136112013-02-15 20:37:21 +00005536 if (Info.Opcode == ~0U)
5537 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005538
Benjamin Kramer1a136112013-02-15 20:37:21 +00005539 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005540
Benjamin Kramer1a136112013-02-15 20:37:21 +00005541 // Build the list of clobbers, outputs and inputs.
5542 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005543 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005544
Benjamin Kramer1a136112013-02-15 20:37:21 +00005545 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005546 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005547 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005548
Benjamin Kramer1a136112013-02-15 20:37:21 +00005549 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005550 if (Operand.isReg() && !Operand.needAddressOf() &&
5551 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005552 unsigned NumDefs = Desc.getNumDefs();
5553 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005554 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5555 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005556 continue;
5557 }
5558
5559 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005560 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005561 if (SymName.empty())
5562 continue;
5563
David Blaikie960ea3f2014-06-08 16:18:35 +00005564 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005565 if (!OpDecl)
5566 continue;
5567
5568 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005569 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005570 if (isOutput) {
5571 ++InputIdx;
5572 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005573 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005574 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005575 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005576 } else {
5577 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005578 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5579 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005580 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005581 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005582 }
Reid Kleckneree088972013-12-10 18:27:32 +00005583
5584 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005585 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5586 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005587 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005588 }
5589
5590 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005591 NumOutputs = OutputDecls.size();
5592 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005593
5594 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005595 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5596 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5597 ClobberRegs.end());
5598 Clobbers.assign(ClobberRegs.size(), std::string());
5599 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5600 raw_string_ostream OS(Clobbers[I]);
5601 IP->printRegName(OS, ClobberRegs[I]);
5602 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005603
5604 // Merge the various outputs and inputs. Output are expected first.
5605 if (NumOutputs || NumInputs) {
5606 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005607 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005608 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005609 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005610 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005611 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005612 }
5613 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005614 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005615 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005616 }
5617 }
5618
5619 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005620 std::string AsmStringIR;
5621 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005622 StringRef ASMString =
5623 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5624 const char *AsmStart = ASMString.begin();
5625 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005626 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005627 for (const AsmRewrite &AR : AsmStrRewrites) {
5628 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005629
David Majnemer8114c1a2014-06-23 02:17:16 +00005630 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005631 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005632
Chad Rosier120eefd2013-03-19 17:32:17 +00005633 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005634 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005635 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005636
Chad Rosier37e755c2012-10-23 17:43:43 +00005637 // Skip the original expression.
5638 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005639 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005640 continue;
5641 }
5642
Chad Rosierff10ed12013-04-12 16:26:42 +00005643 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005644 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005645 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005646 default:
5647 break;
Coby Tayreed8912892017-08-24 08:46:25 +00005648 case AOK_IntelExpr:
5649 assert(AR.IntelExp.isValid() && "cannot write invalid intel expression");
5650 if (AR.IntelExp.NeedBracs)
5651 OS << "[";
5652 if (AR.IntelExp.hasBaseReg())
5653 OS << AR.IntelExp.BaseReg;
5654 if (AR.IntelExp.hasIndexReg())
5655 OS << (AR.IntelExp.hasBaseReg() ? " + " : "")
5656 << AR.IntelExp.IndexReg;
5657 if (AR.IntelExp.Scale > 1)
5658 OS << " * $$" << AR.IntelExp.Scale;
5659 if (AR.IntelExp.Imm || !AR.IntelExp.hasRegs())
5660 OS << (AR.IntelExp.hasRegs() ? " + $$" : "$$") << AR.IntelExp.Imm;
5661 if (AR.IntelExp.NeedBracs)
5662 OS << "]";
Chad Rosier8bce6642012-10-18 15:49:34 +00005663 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005664 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005665 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005666 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005667 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005668 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005669 break;
5670 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005671 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005672 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005673 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005674 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005675 default: break;
5676 case 8: OS << "byte ptr "; break;
5677 case 16: OS << "word ptr "; break;
5678 case 32: OS << "dword ptr "; break;
5679 case 64: OS << "qword ptr "; break;
5680 case 80: OS << "xword ptr "; break;
5681 case 128: OS << "xmmword ptr "; break;
5682 case 256: OS << "ymmword ptr "; break;
5683 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005684 break;
5685 case AOK_Emit:
5686 OS << ".byte";
5687 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005688 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005689 // MS alignment directives are measured in bytes. If the native assembler
5690 // measures alignment in bytes, we can pass it straight through.
5691 OS << ".align";
5692 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5693 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005694
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005695 // Alignment is in log2 form, so print that instead and skip the original
5696 // immediate.
5697 unsigned Val = AR.Val;
5698 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005699 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005700 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5701 break;
5702 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005703 case AOK_EVEN:
5704 OS << ".even";
5705 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005706 case AOK_EndOfStatement:
5707 OS << "\n\t";
5708 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005709 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005710
Chad Rosier8bce6642012-10-18 15:49:34 +00005711 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005712 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005713 }
5714
5715 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005716 if (AsmStart != AsmEnd)
5717 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005718
5719 AsmString = OS.str();
5720 return false;
5721}
5722
Pete Cooper80d21cb2015-06-22 19:35:57 +00005723namespace llvm {
5724namespace MCParserUtils {
5725
5726/// Returns whether the given symbol is used anywhere in the given expression,
5727/// or subexpressions.
5728static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5729 switch (Value->getKind()) {
5730 case MCExpr::Binary: {
5731 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5732 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5733 isSymbolUsedInExpression(Sym, BE->getRHS());
5734 }
5735 case MCExpr::Target:
5736 case MCExpr::Constant:
5737 return false;
5738 case MCExpr::SymbolRef: {
5739 const MCSymbol &S =
5740 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5741 if (S.isVariable())
5742 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5743 return &S == Sym;
5744 }
5745 case MCExpr::Unary:
5746 return isSymbolUsedInExpression(
5747 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5748 }
5749
5750 llvm_unreachable("Unknown expr kind!");
5751}
5752
5753bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5754 MCAsmParser &Parser, MCSymbol *&Sym,
5755 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005756
5757 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005758 SMLoc EqualLoc = Parser.getTok().getLoc();
Pete Cooper80d21cb2015-06-22 19:35:57 +00005759
5760 if (Parser.parseExpression(Value)) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00005761 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005762 }
5763
5764 // Note: we don't count b as used in "a = b". This is to allow
5765 // a = b
5766 // b = c
5767
Nirav Dave1a9044b2016-10-24 14:35:29 +00005768 if (Parser.parseToken(AsmToken::EndOfStatement))
5769 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00005770
5771 // Validate that the LHS is allowed to be a variable (either it has not been
5772 // used as a symbol, or it is an absolute symbol).
5773 Sym = Parser.getContext().lookupSymbol(Name);
5774 if (Sym) {
5775 // Diagnose assignment to a label.
5776 //
5777 // FIXME: Diagnostics. Note the location of the definition as a label.
5778 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5779 if (isSymbolUsedInExpression(Sym, Value))
5780 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005781 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5782 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005783 ; // Allow redefinitions of undefined symbols only used in directives.
5784 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5785 ; // Allow redefinitions of variables that haven't yet been used.
5786 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5787 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5788 else if (!Sym->isVariable())
5789 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5790 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5791 return Parser.Error(EqualLoc,
5792 "invalid reassignment of non-absolute variable '" +
5793 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005794 } else if (Name == ".") {
Oliver Stannard268f42f2016-12-14 10:43:58 +00005795 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005796 return false;
5797 } else
5798 Sym = Parser.getContext().getOrCreateSymbol(Name);
5799
5800 Sym->setRedefinable(allow_redef);
5801
5802 return false;
5803}
5804
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005805} // end namespace MCParserUtils
5806} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005807
Daniel Dunbar01e36072010-07-17 02:26:10 +00005808/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005809MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
Sanne Wouda29338752017-02-08 14:48:05 +00005810 MCStreamer &Out, const MCAsmInfo &MAI,
5811 unsigned CB) {
5812 return new AsmParser(SM, C, Out, MAI, CB);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005813}