blob: daf01ead13a118ae4013301c8789fd5f1c414d7c [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
Paul Robinson43095b22018-03-08 22:39:47 +0000314 /// Should we emit DWARF describing this assembler source? (Returns false if
315 /// the source has .file directives, which means we don't want to generate
316 /// info describing the assembler source itself.)
317 bool enabledGenDwarfForAssembly();
318
Jim Grosbach4b905842013-09-20 23:08:21 +0000319 /// \brief Enter the specified file. This returns true on failure.
320 bool enterIncludeFile(const std::string &Filename);
321
322 /// \brief Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000323 /// This returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000324 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
325 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
Daniel Dunbar43235712010-07-18 18:54:11 +0000326
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000327 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000328 /// current token is not set; clients should ensure Lex() is called
329 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000330 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000331 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000332 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000333 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000334
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000335 /// \brief Parse up to the end of statement and a return the contents from the
336 /// current token until the end of the statement; the current token on exit
337 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000338 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000339
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000340 /// \brief Parse until the end of a statement or a comma is encountered,
341 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000342 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000343
Jim Grosbach4b905842013-09-20 23:08:21 +0000344 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +0000345 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000346
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000347 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
348 MCBinaryExpr::Opcode &Kind);
349
Jim Grosbach4b905842013-09-20 23:08:21 +0000350 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
351 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
352 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000353
Jim Grosbach4b905842013-09-20 23:08:21 +0000354 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000355
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000356 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
357 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
358
Eli Bendersky17233942013-01-15 22:59:42 +0000359 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000360 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000361 DK_NO_DIRECTIVE, // Placeholder
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000362 DK_SET,
363 DK_EQU,
364 DK_EQUIV,
365 DK_ASCII,
366 DK_ASCIZ,
367 DK_STRING,
368 DK_BYTE,
369 DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000370 DK_RELOC,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000371 DK_VALUE,
372 DK_2BYTE,
373 DK_LONG,
374 DK_INT,
375 DK_4BYTE,
376 DK_QUAD,
377 DK_8BYTE,
378 DK_OCTA,
379 DK_DC,
380 DK_DC_A,
381 DK_DC_B,
382 DK_DC_D,
383 DK_DC_L,
384 DK_DC_S,
385 DK_DC_W,
386 DK_DC_X,
387 DK_DCB,
388 DK_DCB_B,
389 DK_DCB_D,
390 DK_DCB_L,
391 DK_DCB_S,
392 DK_DCB_W,
393 DK_DCB_X,
394 DK_DS,
395 DK_DS_B,
396 DK_DS_D,
397 DK_DS_L,
398 DK_DS_P,
399 DK_DS_S,
400 DK_DS_W,
401 DK_DS_X,
402 DK_SINGLE,
403 DK_FLOAT,
404 DK_DOUBLE,
405 DK_ALIGN,
406 DK_ALIGN32,
407 DK_BALIGN,
408 DK_BALIGNW,
409 DK_BALIGNL,
410 DK_P2ALIGN,
411 DK_P2ALIGNW,
412 DK_P2ALIGNL,
413 DK_ORG,
414 DK_FILL,
415 DK_ENDR,
416 DK_BUNDLE_ALIGN_MODE,
417 DK_BUNDLE_LOCK,
418 DK_BUNDLE_UNLOCK,
419 DK_ZERO,
420 DK_EXTERN,
421 DK_GLOBL,
422 DK_GLOBAL,
423 DK_LAZY_REFERENCE,
424 DK_NO_DEAD_STRIP,
425 DK_SYMBOL_RESOLVER,
426 DK_PRIVATE_EXTERN,
427 DK_REFERENCE,
428 DK_WEAK_DEFINITION,
429 DK_WEAK_REFERENCE,
430 DK_WEAK_DEF_CAN_BE_HIDDEN,
431 DK_COMM,
432 DK_COMMON,
433 DK_LCOMM,
434 DK_ABORT,
435 DK_INCLUDE,
436 DK_INCBIN,
437 DK_CODE16,
438 DK_CODE16GCC,
439 DK_REPT,
440 DK_IRP,
441 DK_IRPC,
442 DK_IF,
443 DK_IFEQ,
444 DK_IFGE,
445 DK_IFGT,
446 DK_IFLE,
447 DK_IFLT,
448 DK_IFNE,
449 DK_IFB,
450 DK_IFNB,
451 DK_IFC,
452 DK_IFEQS,
453 DK_IFNC,
454 DK_IFNES,
455 DK_IFDEF,
456 DK_IFNDEF,
457 DK_IFNOTDEF,
458 DK_ELSEIF,
459 DK_ELSE,
460 DK_ENDIF,
461 DK_SPACE,
462 DK_SKIP,
463 DK_FILE,
464 DK_LINE,
465 DK_LOC,
466 DK_STABS,
467 DK_CV_FILE,
468 DK_CV_FUNC_ID,
469 DK_CV_INLINE_SITE_ID,
470 DK_CV_LOC,
471 DK_CV_LINETABLE,
472 DK_CV_INLINE_LINETABLE,
473 DK_CV_DEF_RANGE,
474 DK_CV_STRINGTABLE,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000475 DK_CV_FILECHECKSUMS,
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000476 DK_CV_FILECHECKSUM_OFFSET,
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000477 DK_CV_FPO_DATA,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000478 DK_CFI_SECTIONS,
479 DK_CFI_STARTPROC,
480 DK_CFI_ENDPROC,
481 DK_CFI_DEF_CFA,
482 DK_CFI_DEF_CFA_OFFSET,
483 DK_CFI_ADJUST_CFA_OFFSET,
484 DK_CFI_DEF_CFA_REGISTER,
485 DK_CFI_OFFSET,
486 DK_CFI_REL_OFFSET,
487 DK_CFI_PERSONALITY,
488 DK_CFI_LSDA,
489 DK_CFI_REMEMBER_STATE,
490 DK_CFI_RESTORE_STATE,
491 DK_CFI_SAME_VALUE,
492 DK_CFI_RESTORE,
493 DK_CFI_ESCAPE,
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000494 DK_CFI_RETURN_COLUMN,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000495 DK_CFI_SIGNAL_FRAME,
496 DK_CFI_UNDEFINED,
497 DK_CFI_REGISTER,
498 DK_CFI_WINDOW_SAVE,
499 DK_MACROS_ON,
500 DK_MACROS_OFF,
501 DK_ALTMACRO,
502 DK_NOALTMACRO,
503 DK_MACRO,
504 DK_EXITM,
505 DK_ENDM,
506 DK_ENDMACRO,
507 DK_PURGEM,
508 DK_SLEB128,
509 DK_ULEB128,
510 DK_ERR,
511 DK_ERROR,
512 DK_WARNING,
Coby Tayree01e53202017-10-02 14:36:31 +0000513 DK_PRINT,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000514 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000515 };
516
Jim Grosbach4b905842013-09-20 23:08:21 +0000517 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000518 /// directives parsed by this class.
519 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000520
521 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000522 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000523 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Nirav Dave1a9044b2016-10-24 14:35:29 +0000524 bool parseDirectiveValue(StringRef IDVal,
525 unsigned Size); // ".byte", ".long", ...
526 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
527 bool parseDirectiveRealValue(StringRef IDVal,
528 const fltSemantics &); // ".single", ...
Jim Grosbach4b905842013-09-20 23:08:21 +0000529 bool parseDirectiveFill(); // ".fill"
530 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000531 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000532 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
533 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000534 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000535 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000536
Eli Bendersky17233942013-01-15 22:59:42 +0000537 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000538 bool parseDirectiveFile(SMLoc DirectiveLoc);
539 bool parseDirectiveLine();
540 bool parseDirectiveLoc();
541 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000542
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000543 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
544 // ".cv_inline_linetable", ".cv_def_range"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000545 bool parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000546 bool parseDirectiveCVFuncId();
547 bool parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000548 bool parseDirectiveCVLoc();
549 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000550 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000551 bool parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000552 bool parseDirectiveCVStringTable();
553 bool parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000554 bool parseDirectiveCVFileChecksumOffset();
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000555 bool parseDirectiveCVFPOData();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000556
Eli Bendersky17233942013-01-15 22:59:42 +0000557 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000558 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000559 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000560 bool parseDirectiveCFISections();
561 bool parseDirectiveCFIStartProc();
562 bool parseDirectiveCFIEndProc();
563 bool parseDirectiveCFIDefCfaOffset();
564 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
565 bool parseDirectiveCFIAdjustCfaOffset();
566 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
567 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
568 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
569 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
570 bool parseDirectiveCFIRememberState();
571 bool parseDirectiveCFIRestoreState();
572 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
573 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
574 bool parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000575 bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +0000576 bool parseDirectiveCFISignalFrame();
577 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000578
579 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000580 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000581 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000582 bool parseDirectiveEndMacro(StringRef Directive);
583 bool parseDirectiveMacro(SMLoc DirectiveLoc);
584 bool parseDirectiveMacrosOnOff(StringRef Directive);
Michael Zuckerman56704612017-05-01 13:20:12 +0000585 // alternate macro mode directives
586 bool parseDirectiveAltmacro(StringRef Directive);
Eli Benderskyf483ff92012-12-20 19:05:53 +0000587 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000588 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000589 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000590 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000591 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000592 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000593
Eli Bendersky17233942013-01-15 22:59:42 +0000594 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000595 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000596
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000597 // ".dcb"
598 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
599 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
Petr Hosek85b2f672016-09-23 21:53:36 +0000600 // ".ds"
601 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000602
Eli Bendersky17233942013-01-15 22:59:42 +0000603 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000604 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000605
Jim Grosbach4b905842013-09-20 23:08:21 +0000606 /// \brief Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000607 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000608 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000609
Jim Grosbach4b905842013-09-20 23:08:21 +0000610 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000611
Jim Grosbach4b905842013-09-20 23:08:21 +0000612 bool parseDirectiveAbort(); // ".abort"
613 bool parseDirectiveInclude(); // ".include"
614 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000615
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000616 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
617 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000618 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000619 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000620 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000621 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000622 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
623 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000624 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000625 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
626 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
627 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
628 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000629 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000630
Jim Grosbach4b905842013-09-20 23:08:21 +0000631 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000632 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000633
Rafael Espindola34b9c512012-06-03 23:57:14 +0000634 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000635 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
636 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000637 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000638 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000639 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
640 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
641 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000642
Chad Rosierc7f552c2013-02-12 21:33:51 +0000643 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000644 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000645 size_t Len);
646
647 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000648 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000649
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000650 // "end"
651 bool parseDirectiveEnd(SMLoc DirectiveLoc);
652
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000653 // ".err" or ".error"
654 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000655
Nico Weber404012b2014-07-24 16:26:06 +0000656 // ".warning"
657 bool parseDirectiveWarning(SMLoc DirectiveLoc);
658
Coby Tayree01e53202017-10-02 14:36:31 +0000659 // .print <double-quotes-string>
660 bool parseDirectivePrint(SMLoc DirectiveLoc);
661
Eli Bendersky17233942013-01-15 22:59:42 +0000662 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000663};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000664
665} // end anonymous namespace
Daniel Dunbar86033402010-07-12 17:54:38 +0000666
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000667namespace llvm {
668
669extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000670extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000671extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000672
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000673} // end namespace llvm
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000674
Chris Lattnerc35681b2010-01-19 19:46:13 +0000675enum { DEFAULT_ADDRSPACE = 0 };
676
David Blaikie9f380a32015-03-16 18:06:57 +0000677AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000678 const MCAsmInfo &MAI, unsigned CB = 0)
David Blaikie9f380a32015-03-16 18:06:57 +0000679 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000680 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
Nirav Dave2364748a2016-09-16 18:30:20 +0000681 HadError = false;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000682 // Save the old handler.
683 SavedDiagHandler = SrcMgr.getDiagHandler();
684 SavedDiagContext = SrcMgr.getDiagContext();
685 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000686 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000687 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000688
Daniel Dunbarc5011082010-07-12 18:12:02 +0000689 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000690 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
691 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000692 PlatformParser.reset(createCOFFAsmParser());
693 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000694 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000695 PlatformParser.reset(createDarwinAsmParser());
696 IsDarwin = true;
697 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000698 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000699 PlatformParser.reset(createELFAsmParser());
700 break;
Dan Gohman18eafb62017-02-22 01:23:18 +0000701 case MCObjectFileInfo::IsWasm:
702 llvm_unreachable("Wasm parsing not supported yet");
703 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000704 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000705
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000706 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000707 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000708
709 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000710}
711
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000712AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000713 assert((HadError || ActiveMacros.empty()) &&
714 "Unexpected active macro instantiation!");
Sanne Wouda29338752017-02-08 14:48:05 +0000715
716 // Restore the saved diagnostics handler and context for use during
717 // finalization.
718 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000719}
720
Jim Grosbach4b905842013-09-20 23:08:21 +0000721void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000722 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000723 for (std::vector<MacroInstantiation *>::const_reverse_iterator
724 it = ActiveMacros.rbegin(),
725 ie = ActiveMacros.rend();
726 it != ie; ++it)
727 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000728 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000729}
730
Nirav Dave2364748a2016-09-16 18:30:20 +0000731void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
732 printPendingErrors();
733 printMessage(L, SourceMgr::DK_Note, Msg, Range);
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000734 printMacroInstantiations();
735}
736
Nirav Dave2364748a2016-09-16 18:30:20 +0000737bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000738 if(getTargetParser().getTargetOptions().MCNoWarn)
739 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000740 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Nirav Dave2364748a2016-09-16 18:30:20 +0000741 return Error(L, Msg, Range);
742 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000743 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000744 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000745}
746
Nirav Dave2364748a2016-09-16 18:30:20 +0000747bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000748 HadError = true;
Nirav Dave2364748a2016-09-16 18:30:20 +0000749 printMessage(L, SourceMgr::DK_Error, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000750 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000751 return true;
752}
753
Jim Grosbach4b905842013-09-20 23:08:21 +0000754bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000755 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000756 unsigned NewBuf =
757 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
758 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000759 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000760
Sean Callanan7a77eae2010-01-21 00:19:58 +0000761 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000762 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000763 return false;
764}
Daniel Dunbar43235712010-07-18 18:54:11 +0000765
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000766/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000767/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000768/// returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000769bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
770 const MCExpr *Count, SMLoc Loc) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000771 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000772 unsigned NewBuf =
773 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
774 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000775 return true;
776
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000777 // Pick up the bytes from the file and emit them.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000778 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
779 Bytes = Bytes.drop_front(Skip);
780 if (Count) {
781 int64_t Res;
782 if (!Count->evaluateAsAbsolute(Res))
783 return Error(Loc, "expected absolute expression");
784 if (Res < 0)
785 return Warning(Loc, "negative count has no effect");
786 Bytes = Bytes.take_front(Res);
787 }
788 getStreamer().EmitBytes(Bytes);
Kevin Enderby109f25c2011-12-14 21:47:48 +0000789 return false;
790}
791
Alp Tokera55b95b2014-07-06 10:33:31 +0000792void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
793 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000794 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
795 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000796}
797
Sean Callanan7a77eae2010-01-21 00:19:58 +0000798const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000799 if (Lexer.getTok().is(AsmToken::Error))
800 Error(Lexer.getErrLoc(), Lexer.getErr());
801
Nirav Dave53a72f42016-07-11 12:42:14 +0000802 // if it's a end of statement with a comment in it
803 if (getTok().is(AsmToken::EndOfStatement)) {
804 // if this is a line comment output it.
Nirav Dave670109d2017-06-09 14:04:03 +0000805 if (!getTok().getString().empty() && getTok().getString().front() != '\n' &&
Nirav Dave53a72f42016-07-11 12:42:14 +0000806 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
807 Out.addExplicitComment(Twine(getTok().getString()));
808 }
809
Sean Callanan7a77eae2010-01-21 00:19:58 +0000810 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000811
812 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000813 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000814 if (MAI.preserveAsmComments())
815 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000816 tok = &Lexer.Lex();
817 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000818
Sean Callanan7a77eae2010-01-21 00:19:58 +0000819 if (tok->is(AsmToken::Eof)) {
820 // If this is the end of an included file, pop the parent file off the
821 // include stack.
822 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
823 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000824 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000825 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000826 }
827 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000828
Sean Callanan7a77eae2010-01-21 00:19:58 +0000829 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000830}
831
Paul Robinson43095b22018-03-08 22:39:47 +0000832bool AsmParser::enabledGenDwarfForAssembly() {
833 // Check whether the user specified -g.
834 if (!getContext().getGenDwarfForAssembly())
835 return false;
836 // If we haven't encountered any .file directives (which would imply that
837 // the assembler source was produced with debug info already) then emit one
838 // describing the assembler source file itself.
839 if (getContext().getGenDwarfFileNumber() == 0)
840 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
841 0, StringRef(), getContext().getMainFileName()));
842 return true;
843}
844
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000845bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000846 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000847 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000848 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000849
Chris Lattner36e02122009-06-21 20:54:55 +0000850 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000851 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000852
853 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000854 AsmCond StartingCondState = TheCondState;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000855 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000856
Kevin Enderby6469fc22011-11-01 22:27:22 +0000857 // If we are generating dwarf for assembly source files save the initial text
Paul Robinson43095b22018-03-08 22:39:47 +0000858 // section. (Don't use enabledGenDwarfForAssembly() here, as we aren't
859 // emitting any actual debug info yet and haven't had a chance to parse any
860 // embedded .file directives.)
Kevin Enderby6469fc22011-11-01 22:27:22 +0000861 if (getContext().getGenDwarfForAssembly()) {
Eric Christopher445c9522016-10-14 05:47:37 +0000862 MCSection *Sec = getStreamer().getCurrentSectionOnly();
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000863 if (!Sec->getBeginSymbol()) {
864 MCSymbol *SectionStartSym = getContext().createTempSymbol();
865 getStreamer().EmitLabel(SectionStartSym);
866 Sec->setBeginSymbol(SectionStartSym);
867 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000868 bool InsertResult = getContext().addGenDwarfSection(Sec);
869 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000870 (void)InsertResult;
Kevin Enderby6469fc22011-11-01 22:27:22 +0000871 }
872
Chris Lattner73f36112009-07-02 21:53:43 +0000873 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000874 while (Lexer.isNot(AsmToken::Eof)) {
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000875 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000876 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000877 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000878
Nirav Dave2364748a2016-09-16 18:30:20 +0000879 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
880 // for printing ErrMsg via Lex() only if no (presumably better) parser error
881 // exists.
882 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
Nirav Dave1180e6892016-06-02 17:15:05 +0000883 Lex();
884 }
885
Nirav Dave2364748a2016-09-16 18:30:20 +0000886 // parseStatement returned true so may need to emit an error.
887 printPendingErrors();
888
889 // Skipping to the next line if needed.
890 if (!getLexer().isAtStartOfStatement())
891 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000892 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000893
Nirav Dave2364748a2016-09-16 18:30:20 +0000894 // All errors should have been emitted.
895 assert(!hasPendingError() && "unexpected error from parseStatement");
896
Oliver Stannard21718282016-07-26 14:19:47 +0000897 getTargetParser().flushPendingInstructions(getStreamer());
898
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000899 if (TheCondState.TheCond != StartingCondState.TheCond ||
900 TheCondState.Ignore != StartingCondState.Ignore)
Nirav Dave2364748a2016-09-16 18:30:20 +0000901 printError(getTok().getLoc(), "unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000902 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000903 const auto &LineTables = getContext().getMCDwarfLineTables();
904 if (!LineTables.empty()) {
905 unsigned Index = 0;
906 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
907 if (File.Name.empty() && Index != 0)
Nirav Dave2364748a2016-09-16 18:30:20 +0000908 printError(getTok().getLoc(), "unassigned file number: " +
909 Twine(Index) +
910 " for .file directives");
David Blaikie8bf66c42014-04-01 07:35:52 +0000911 ++Index;
912 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000913 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000914
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000915 // Check to see that all assembler local symbols were actually defined.
916 // Targets that don't do subsections via symbols may not want this, though,
917 // so conservatively exclude them. Only do this if we're finalizing, though,
918 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000919 if (!NoFinalize) {
920 if (MAI.hasSubsectionsViaSymbols()) {
921 for (const auto &TableEntry : getContext().getSymbols()) {
922 MCSymbol *Sym = TableEntry.getValue();
923 // Variable symbols may not be marked as defined, so check those
924 // explicitly. If we know it's a variable, we have a definition for
925 // the purposes of this check.
926 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
927 // FIXME: We would really like to refer back to where the symbol was
928 // first referenced for a source location. We need to add something
929 // to track that. Currently, we just point to the end of the file.
Nirav Dave2364748a2016-09-16 18:30:20 +0000930 printError(getTok().getLoc(), "assembler local symbol '" +
931 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000932 }
933 }
934
935 // Temporary symbols like the ones for directional jumps don't go in the
936 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000937 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
938 if (std::get<2>(LocSym)->isUndefined()) {
939 // Reset the state of any "# line file" directives we've seen to the
940 // context as it was at the diagnostic site.
941 CppHashInfo = std::get<1>(LocSym);
Nirav Dave2364748a2016-09-16 18:30:20 +0000942 printError(std::get<0>(LocSym), "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000943 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000944 }
945 }
946
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000947 // Finalize the output stream if there are no errors and if the client wants
948 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000949 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000950 Out.Finish();
951
Oliver Stannard07b43d32015-11-17 09:58:07 +0000952 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000953}
954
Nirav Davef43cc9f2016-10-10 15:24:54 +0000955bool AsmParser::checkForValidSection() {
Eric Christopher445c9522016-10-14 05:47:37 +0000956 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000957 Out.InitSections(false);
Nirav Davef43cc9f2016-10-10 15:24:54 +0000958 return Error(getTok().getLoc(),
959 "expected section directive before assembly directive");
Daniel Dunbare5444a82010-09-09 22:42:59 +0000960 }
Nirav Davef43cc9f2016-10-10 15:24:54 +0000961 return false;
Daniel Dunbare5444a82010-09-09 22:42:59 +0000962}
963
Jim Grosbach4b905842013-09-20 23:08:21 +0000964/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000965void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000966 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000967 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000968
Chris Lattnere5074c42009-06-22 01:29:09 +0000969 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000970 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000971 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000972}
973
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000974StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000975 const char *Start = getTok().getLoc().getPointer();
976
Jim Grosbach4b905842013-09-20 23:08:21 +0000977 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000978 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000979
980 const char *End = getTok().getLoc().getPointer();
981 return StringRef(Start, End - Start);
982}
Chris Lattner78db3622009-06-22 05:51:26 +0000983
Jim Grosbach4b905842013-09-20 23:08:21 +0000984StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000985 const char *Start = getTok().getLoc().getPointer();
986
987 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000988 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000989 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000990
991 const char *End = getTok().getLoc().getPointer();
992 return StringRef(Start, End - Start);
993}
994
Jim Grosbach4b905842013-09-20 23:08:21 +0000995/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000996/// NOTE: This assumes the leading '(' has already been consumed.
997///
998/// parenexpr ::= expr)
999///
Jim Grosbach4b905842013-09-20 23:08:21 +00001000bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1001 if (parseExpression(Res))
1002 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001003 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +00001004 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001005 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001006 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +00001007 return false;
1008}
Chris Lattner78db3622009-06-22 05:51:26 +00001009
Jim Grosbach4b905842013-09-20 23:08:21 +00001010/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001011/// NOTE: This assumes the leading '[' has already been consumed.
1012///
1013/// bracketexpr ::= expr]
1014///
Jim Grosbach4b905842013-09-20 23:08:21 +00001015bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1016 if (parseExpression(Res))
1017 return true;
Nirav Davea645433c2016-07-18 15:24:03 +00001018 EndLoc = getTok().getEndLoc();
1019 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
1020 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001021 return false;
1022}
1023
Jim Grosbach4b905842013-09-20 23:08:21 +00001024/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001025/// primaryexpr ::= (parenexpr
1026/// primaryexpr ::= symbol
1027/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +00001028/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +00001029/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +00001030bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001031 SMLoc FirstTokenLoc = getLexer().getLoc();
1032 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
1033 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +00001034 default:
1035 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +00001036 // If we have an error assume that we've already handled it.
1037 case AsmToken::Error:
1038 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001039 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001040 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001041 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001042 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001043 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001044 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +00001045 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +00001046 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00001047 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +00001048 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +00001049 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001050 if (parseIdentifier(Identifier)) {
Nirav Daved0463322016-10-12 13:58:07 +00001051 // We may have failed but $ may be a valid token.
1052 if (getTok().is(AsmToken::Dollar)) {
David Majnemer0c58bc62013-09-25 10:47:21 +00001053 if (Lexer.getMAI().getDollarIsPC()) {
Nirav Daved0463322016-10-12 13:58:07 +00001054 Lex();
David Majnemer0c58bc62013-09-25 10:47:21 +00001055 // This is a '$' reference, which references the current PC. Emit a
1056 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001057 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +00001058 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001059 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +00001060 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +00001061 EndLoc = FirstTokenLoc;
1062 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +00001063 }
1064 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +00001065 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001066 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001067 // Parse symbol variant
1068 std::pair<StringRef, StringRef> Split;
1069 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +00001070 if (FirstTokenKind == AsmToken::String) {
1071 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +00001072 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +00001073 SMLoc AtLoc = getLexer().getLoc();
1074 StringRef VName;
1075 if (parseIdentifier(VName))
1076 return Error(AtLoc, "expected symbol variant after '@'");
1077
1078 Split = std::make_pair(Identifier, VName);
1079 }
1080 } else {
1081 Split = Identifier.split('@');
1082 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001083 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +00001084 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +00001085 StringRef VName;
1086 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +00001087 // eat ')'.
1088 if (parseToken(AsmToken::RParen,
1089 "unexpected token in variant, expected ')'"))
1090 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +00001091 Split = std::make_pair(Identifier, VName);
1092 }
Daniel Dunbar24764322010-08-24 19:13:42 +00001093
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001094 EndLoc = SMLoc::getFromPointer(Identifier.end());
1095
Daniel Dunbard20cda02009-10-16 01:34:54 +00001096 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +00001097 StringRef SymbolName = Identifier;
Weiming Zhaocf26d562016-12-01 18:00:36 +00001098 if (SymbolName.empty())
1099 return true;
1100
Hans Wennborgce69d772013-10-18 20:46:28 +00001101 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +00001102
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001103 // Lookup the symbol variant if used.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001104 if (!Split.second.empty()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001105 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +00001106 if (Variant != MCSymbolRefExpr::VK_Invalid) {
1107 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +00001108 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +00001109 Variant = MCSymbolRefExpr::VK_None;
1110 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +00001111 return Error(SMLoc::getFromPointer(Split.second.begin()),
1112 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001113 }
1114 }
Daniel Dunbar55992562010-03-15 23:51:06 +00001115
Jim Grosbach6f482002015-05-18 18:43:14 +00001116 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +00001117
Daniel Dunbard20cda02009-10-16 01:34:54 +00001118 // If this is an absolute variable reference, substitute it now to preserve
1119 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +00001120 if (Sym->isVariable() &&
1121 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +00001122 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +00001123 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +00001124
Vedant Kumar86dbd922015-08-31 17:44:53 +00001125 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +00001126 return false;
1127 }
1128
1129 // Otherwise create a symbol ref.
Chad Rosier9245e122017-01-19 20:06:32 +00001130 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
Chris Lattner78db3622009-06-22 05:51:26 +00001131 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001132 }
David Woodhousef42a6662014-02-01 16:20:54 +00001133 case AsmToken::BigNum:
1134 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001135 case AsmToken::Integer: {
1136 SMLoc Loc = getTok().getLoc();
1137 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001138 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001139 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001140 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001141 // Look for 'b' or 'f' following an Integer as a directional label
1142 if (Lexer.getKind() == AsmToken::Identifier) {
1143 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001144 // Lookup the symbol variant if used.
1145 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1146 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1147 if (Split.first.size() != IDVal.size()) {
1148 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001149 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001150 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001151 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001152 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001153 if (IDVal == "f" || IDVal == "b") {
1154 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001155 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001156 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001157 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001158 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001159 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001160 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001161 Lex(); // Eat identifier.
1162 }
1163 }
Chris Lattner78db3622009-06-22 05:51:26 +00001164 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001165 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001166 case AsmToken::Real: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001167 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001168 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001169 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001170 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001171 Lex(); // Eat token.
1172 return false;
1173 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001174 case AsmToken::Dot: {
1175 // This is a '.' reference, which references the current PC. Emit a
1176 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001177 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001178 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001179 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001180 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001181 Lex(); // Eat identifier.
1182 return false;
1183 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001184 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001185 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001186 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001187 case AsmToken::LBrac:
1188 if (!PlatformParser->HasBracketExpressions())
1189 return TokError("brackets expression not supported on this target");
1190 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001191 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001192 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001193 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001194 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001195 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001196 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001197 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001198 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001199 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001200 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001201 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001202 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001203 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001204 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001205 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001206 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001207 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001208 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001209 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001210 // MIPS unary expression operators. The lexer won't generate these tokens if
1211 // MCAsmInfo::HasMipsExpressions is false for the target.
1212 case AsmToken::PercentCall16:
1213 case AsmToken::PercentCall_Hi:
1214 case AsmToken::PercentCall_Lo:
1215 case AsmToken::PercentDtprel_Hi:
1216 case AsmToken::PercentDtprel_Lo:
1217 case AsmToken::PercentGot:
1218 case AsmToken::PercentGot_Disp:
1219 case AsmToken::PercentGot_Hi:
1220 case AsmToken::PercentGot_Lo:
1221 case AsmToken::PercentGot_Ofst:
1222 case AsmToken::PercentGot_Page:
1223 case AsmToken::PercentGottprel:
1224 case AsmToken::PercentGp_Rel:
1225 case AsmToken::PercentHi:
1226 case AsmToken::PercentHigher:
1227 case AsmToken::PercentHighest:
1228 case AsmToken::PercentLo:
1229 case AsmToken::PercentNeg:
1230 case AsmToken::PercentPcrel_Hi:
1231 case AsmToken::PercentPcrel_Lo:
1232 case AsmToken::PercentTlsgd:
1233 case AsmToken::PercentTlsldm:
1234 case AsmToken::PercentTprel_Hi:
1235 case AsmToken::PercentTprel_Lo:
1236 Lex(); // Eat the operator.
1237 if (Lexer.isNot(AsmToken::LParen))
1238 return TokError("expected '(' after operator");
1239 Lex(); // Eat the operator.
1240 if (parseExpression(Res, EndLoc))
1241 return true;
1242 if (Lexer.isNot(AsmToken::RParen))
1243 return TokError("expected ')'");
1244 Lex(); // Eat the operator.
1245 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1246 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001247 }
1248}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001249
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001250bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001251 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001252 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001253}
1254
Daniel Dunbar55f16672010-09-17 02:47:07 +00001255const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001256AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001257 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001258 // Ask the target implementation about this expression first.
1259 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1260 if (NewE)
1261 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001262 // Recurse over the given expression, rebuilding it to apply the given variant
1263 // if there is exactly one symbol.
1264 switch (E->getKind()) {
1265 case MCExpr::Target:
1266 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001267 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001268
1269 case MCExpr::SymbolRef: {
1270 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1271
1272 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001273 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1274 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001275 return E;
1276 }
1277
Jim Grosbach13760bd2015-05-30 01:25:56 +00001278 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001279 }
1280
1281 case MCExpr::Unary: {
1282 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001283 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001284 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001285 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001286 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001287 }
1288
1289 case MCExpr::Binary: {
1290 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001291 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1292 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001293
1294 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001295 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001296
Jim Grosbach4b905842013-09-20 23:08:21 +00001297 if (!LHS)
1298 LHS = BE->getLHS();
1299 if (!RHS)
1300 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001301
Jim Grosbach13760bd2015-05-30 01:25:56 +00001302 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001303 }
1304 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001305
Craig Toppera2886c22012-02-07 05:05:23 +00001306 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001307}
1308
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001309/// This function checks if the next token is <string> type or arithmetic.
1310/// string that begin with character '<' must end with character '>'.
1311/// otherwise it is arithmetics.
1312/// If the function returns a 'true' value,
1313/// the End argument will be filled with the last location pointed to the '>'
1314/// character.
1315
1316/// There is a gap between the AltMacro's documentation and the single quote implementation.
1317/// GCC does not fully support this feature and so we will not support it.
1318/// TODO: Adding single quote as a string.
1319bool AsmParser::isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc) {
1320 assert((StrLoc.getPointer() != NULL) &&
1321 "Argument to the function cannot be a NULL value");
1322 const char *CharPtr = StrLoc.getPointer();
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001323 while ((*CharPtr != '>') && (*CharPtr != '\n') && (*CharPtr != '\r') &&
1324 (*CharPtr != '\0')) {
1325 if (*CharPtr == '!')
1326 CharPtr++;
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001327 CharPtr++;
1328 }
1329 if (*CharPtr == '>') {
1330 EndLoc = StrLoc.getFromPointer(CharPtr + 1);
1331 return true;
1332 }
1333 return false;
1334}
1335
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001336/// \brief creating a string without the escape characters '!'.
1337void AsmParser::altMacroString(StringRef AltMacroStr,std::string &Res) {
Michael Zuckermanff298792017-05-10 14:00:57 +00001338 for (size_t Pos = 0; Pos < AltMacroStr.size(); Pos++) {
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001339 if (AltMacroStr[Pos] == '!')
1340 Pos++;
1341 Res += AltMacroStr[Pos];
1342 }
1343}
1344
Jim Grosbach4b905842013-09-20 23:08:21 +00001345/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001346///
Jim Grosbachbd164242011-08-20 16:24:13 +00001347/// expr ::= expr &&,|| expr -> lowest.
1348/// expr ::= expr |,^,&,! expr
1349/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1350/// expr ::= expr <<,>> expr
1351/// expr ::= expr +,- expr
1352/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001353/// expr ::= primaryexpr
1354///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001355bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001356 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001357 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001358 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001359 return true;
1360
Daniel Dunbar55f16672010-09-17 02:47:07 +00001361 // As a special case, we support 'a op b @ modifier' by rewriting the
1362 // expression to include the modifier. This is inefficient, but in general we
1363 // expect users to use 'a@modifier op b'.
1364 if (Lexer.getKind() == AsmToken::At) {
1365 Lex();
1366
1367 if (Lexer.isNot(AsmToken::Identifier))
1368 return TokError("unexpected symbol modifier following '@'");
1369
1370 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001371 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001372 if (Variant == MCSymbolRefExpr::VK_Invalid)
1373 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1374
Jim Grosbach4b905842013-09-20 23:08:21 +00001375 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001376 if (!ModifiedRes) {
1377 return TokError("invalid modifier '" + getTok().getIdentifier() +
1378 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001379 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001380
Daniel Dunbar55f16672010-09-17 02:47:07 +00001381 Res = ModifiedRes;
1382 Lex();
1383 }
1384
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001385 // Try to constant fold it up front, if possible.
1386 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001387 if (Res->evaluateAsAbsolute(Value))
1388 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001389
1390 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001391}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001392
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001393bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001394 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001395 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001396}
1397
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001398bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1399 SMLoc &EndLoc) {
1400 if (parseParenExpr(Res, EndLoc))
1401 return true;
1402
1403 for (; ParenDepth > 0; --ParenDepth) {
1404 if (parseBinOpRHS(1, Res, EndLoc))
1405 return true;
1406
1407 // We don't Lex() the last RParen.
1408 // This is the same behavior as parseParenExpression().
1409 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001410 EndLoc = getTok().getEndLoc();
1411 if (parseToken(AsmToken::RParen,
1412 "expected ')' in parentheses expression"))
1413 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001414 }
1415 }
1416 return false;
1417}
1418
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001419bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001420 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001421
Daniel Dunbar75630b32009-06-30 02:10:03 +00001422 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001423 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001424 return true;
1425
Jim Grosbach13760bd2015-05-30 01:25:56 +00001426 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001427 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001428
1429 return false;
1430}
1431
David Majnemer0993e0b2015-10-26 03:15:34 +00001432static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1433 MCBinaryExpr::Opcode &Kind,
1434 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001435 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001436 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001437 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001438
Jim Grosbach4b905842013-09-20 23:08:21 +00001439 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001440 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001441 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001442 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001443 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001444 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001445 return 1;
1446
Jim Grosbach4b905842013-09-20 23:08:21 +00001447 // Low Precedence: |, &, ^
1448 //
1449 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001450 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001451 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001452 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001453 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001454 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001455 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001456 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001457 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001458 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001459
Jim Grosbach4b905842013-09-20 23:08:21 +00001460 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001461 case AsmToken::EqualEqual:
1462 Kind = MCBinaryExpr::EQ;
1463 return 3;
1464 case AsmToken::ExclaimEqual:
1465 case AsmToken::LessGreater:
1466 Kind = MCBinaryExpr::NE;
1467 return 3;
1468 case AsmToken::Less:
1469 Kind = MCBinaryExpr::LT;
1470 return 3;
1471 case AsmToken::LessEqual:
1472 Kind = MCBinaryExpr::LTE;
1473 return 3;
1474 case AsmToken::Greater:
1475 Kind = MCBinaryExpr::GT;
1476 return 3;
1477 case AsmToken::GreaterEqual:
1478 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001479 return 3;
1480
Jim Grosbach4b905842013-09-20 23:08:21 +00001481 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001482 case AsmToken::LessLess:
1483 Kind = MCBinaryExpr::Shl;
1484 return 4;
1485 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001486 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001487 return 4;
1488
Jim Grosbach4b905842013-09-20 23:08:21 +00001489 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001490 case AsmToken::Plus:
1491 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001492 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001493 case AsmToken::Minus:
1494 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001495 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001496
Jim Grosbach4b905842013-09-20 23:08:21 +00001497 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001498 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001499 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001500 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001501 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001502 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001503 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001504 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001505 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001506 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001507 }
1508}
1509
David Majnemer0993e0b2015-10-26 03:15:34 +00001510static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1511 MCBinaryExpr::Opcode &Kind,
1512 bool ShouldUseLogicalShr) {
1513 switch (K) {
1514 default:
1515 return 0; // not a binop.
1516
1517 // Lowest Precedence: &&, ||
1518 case AsmToken::AmpAmp:
1519 Kind = MCBinaryExpr::LAnd;
1520 return 2;
1521 case AsmToken::PipePipe:
1522 Kind = MCBinaryExpr::LOr;
1523 return 1;
1524
1525 // Low Precedence: ==, !=, <>, <, <=, >, >=
1526 case AsmToken::EqualEqual:
1527 Kind = MCBinaryExpr::EQ;
1528 return 3;
1529 case AsmToken::ExclaimEqual:
1530 case AsmToken::LessGreater:
1531 Kind = MCBinaryExpr::NE;
1532 return 3;
1533 case AsmToken::Less:
1534 Kind = MCBinaryExpr::LT;
1535 return 3;
1536 case AsmToken::LessEqual:
1537 Kind = MCBinaryExpr::LTE;
1538 return 3;
1539 case AsmToken::Greater:
1540 Kind = MCBinaryExpr::GT;
1541 return 3;
1542 case AsmToken::GreaterEqual:
1543 Kind = MCBinaryExpr::GTE;
1544 return 3;
1545
1546 // Low Intermediate Precedence: +, -
1547 case AsmToken::Plus:
1548 Kind = MCBinaryExpr::Add;
1549 return 4;
1550 case AsmToken::Minus:
1551 Kind = MCBinaryExpr::Sub;
1552 return 4;
1553
1554 // High Intermediate Precedence: |, &, ^
1555 //
1556 // FIXME: gas seems to support '!' as an infix operator?
1557 case AsmToken::Pipe:
1558 Kind = MCBinaryExpr::Or;
1559 return 5;
1560 case AsmToken::Caret:
1561 Kind = MCBinaryExpr::Xor;
1562 return 5;
1563 case AsmToken::Amp:
1564 Kind = MCBinaryExpr::And;
1565 return 5;
1566
1567 // Highest Precedence: *, /, %, <<, >>
1568 case AsmToken::Star:
1569 Kind = MCBinaryExpr::Mul;
1570 return 6;
1571 case AsmToken::Slash:
1572 Kind = MCBinaryExpr::Div;
1573 return 6;
1574 case AsmToken::Percent:
1575 Kind = MCBinaryExpr::Mod;
1576 return 6;
1577 case AsmToken::LessLess:
1578 Kind = MCBinaryExpr::Shl;
1579 return 6;
1580 case AsmToken::GreaterGreater:
1581 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1582 return 6;
1583 }
1584}
1585
1586unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1587 MCBinaryExpr::Opcode &Kind) {
1588 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1589 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1590 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1591}
1592
Jim Grosbach4b905842013-09-20 23:08:21 +00001593/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001594/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001595bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001596 SMLoc &EndLoc) {
Chad Rosier9245e122017-01-19 20:06:32 +00001597 SMLoc StartLoc = Lexer.getLoc();
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001598 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001599 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001600 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001601
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001602 // If the next token is lower precedence than we are allowed to eat, return
1603 // successfully with what we ate already.
1604 if (TokPrec < Precedence)
1605 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001606
Sean Callanan686ed8d2010-01-19 20:22:31 +00001607 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001608
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001609 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001610 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001611 if (parsePrimaryExpr(RHS, EndLoc))
1612 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001613
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001614 // If BinOp binds less tightly with RHS than the operator after RHS, let
1615 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001616 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001617 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001618 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1619 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001620
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001621 // Merge LHS and RHS according to operator.
Chad Rosier9245e122017-01-19 20:06:32 +00001622 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001623 }
1624}
1625
Chris Lattner36e02122009-06-21 20:54:55 +00001626/// ParseStatement:
1627/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001628/// ::= Label* Directive ...Operands... EndOfStatement
1629/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001630bool AsmParser::parseStatement(ParseStatementInfo &Info,
1631 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001632 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001633 // Eat initial spaces and comments
1634 while (Lexer.is(AsmToken::Space))
1635 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001636 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001637 // if this is a line comment we can drop it safely
Nirav Dave670109d2017-06-09 14:04:03 +00001638 if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
Nirav Davefd910412016-06-17 16:06:17 +00001639 getTok().getString().front() == '\n')
1640 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001641 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001642 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001643 }
Nirav Davefd910412016-06-17 16:06:17 +00001644 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001645 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001646 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001647 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001648 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001649 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001650 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001651 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001652 if (Lexer.is(AsmToken::Integer)) {
1653 LocalLabelVal = getTok().getIntVal();
1654 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001655 if (!TheCondState.Ignore) {
1656 Lex(); // always eat a token
1657 return Error(IDLoc, "unexpected token at start of statement");
1658 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001659 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001660 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001661 IDVal = getTok().getString();
1662 Lex(); // Consume the integer token to be used as an identifier token.
1663 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001664 if (!TheCondState.Ignore) {
1665 Lex(); // always eat a token
1666 return Error(IDLoc, "unexpected token at start of statement");
1667 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001668 }
1669 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001670 } else if (Lexer.is(AsmToken::Dot)) {
1671 // Treat '.' as a valid identifier in this context.
1672 Lex();
1673 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001674 } else if (Lexer.is(AsmToken::LCurly)) {
1675 // Treat '{' as a valid identifier in this context.
1676 Lex();
1677 IDVal = "{";
1678
1679 } else if (Lexer.is(AsmToken::RCurly)) {
1680 // Treat '}' as a valid identifier in this context.
1681 Lex();
1682 IDVal = "}";
Yonghong Song06ff6552017-09-12 17:55:23 +00001683 } else if (Lexer.is(AsmToken::Star) &&
1684 getTargetParser().starIsStartOfStatement()) {
1685 // Accept '*' as a valid start of statement.
1686 Lex();
1687 IDVal = "*";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001688 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001689 if (!TheCondState.Ignore) {
1690 Lex(); // always eat a token
1691 return Error(IDLoc, "unexpected token at start of statement");
1692 }
Chris Lattner926885c2010-04-17 18:14:27 +00001693 IDVal = "";
1694 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001695
Chris Lattner926885c2010-04-17 18:14:27 +00001696 // Handle conditional assembly here before checking for skipping. We
1697 // have to do this so that .endif isn't skipped in a ".if 0" block for
1698 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001699 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001700 DirectiveKindMap.find(IDVal);
1701 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1702 ? DK_NO_DIRECTIVE
1703 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001704 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001705 default:
1706 break;
1707 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001708 case DK_IFEQ:
1709 case DK_IFGE:
1710 case DK_IFGT:
1711 case DK_IFLE:
1712 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001713 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001714 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001715 case DK_IFB:
1716 return parseDirectiveIfb(IDLoc, true);
1717 case DK_IFNB:
1718 return parseDirectiveIfb(IDLoc, false);
1719 case DK_IFC:
1720 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001721 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001722 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001723 case DK_IFNC:
1724 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001725 case DK_IFNES:
1726 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001727 case DK_IFDEF:
1728 return parseDirectiveIfdef(IDLoc, true);
1729 case DK_IFNDEF:
1730 case DK_IFNOTDEF:
1731 return parseDirectiveIfdef(IDLoc, false);
1732 case DK_ELSEIF:
1733 return parseDirectiveElseIf(IDLoc);
1734 case DK_ELSE:
1735 return parseDirectiveElse(IDLoc);
1736 case DK_ENDIF:
1737 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001738 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001739
Eli Bendersky88024712013-01-16 19:32:36 +00001740 // Ignore the statement if in the middle of inactive conditional
1741 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001742 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001743 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001744 return false;
1745 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001746
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001747 // FIXME: Recurse on local labels?
1748
1749 // See what kind of statement we have.
1750 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001751 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001752 if (!getTargetParser().isLabel(ID))
1753 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001754 if (checkForValidSection())
1755 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001756
Chris Lattner36e02122009-06-21 20:54:55 +00001757 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001758 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001759
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001760 // Diagnose attempt to use '.' as a label.
1761 if (IDVal == ".")
1762 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1763
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001764 // Diagnose attempt to use a variable as a label.
1765 //
1766 // FIXME: Diagnostics. Note the location of the definition as a label.
1767 // FIXME: This doesn't diagnose assignment to a symbol which has been
1768 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001769 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001770 if (LocalLabelVal == -1) {
1771 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001772 StringRef RewrittenLabel =
1773 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001774 assert(!RewrittenLabel.empty() &&
Nico Weber67e715f2015-06-19 23:43:47 +00001775 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001776 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1777 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001778 IDVal = RewrittenLabel;
1779 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001780 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001781 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001782 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
Nirav Dave9263ae32016-08-02 19:17:54 +00001783 // End of Labels should be treated as end of line for lexing
1784 // purposes but that information is not available to the Lexer who
1785 // does not understand Labels. This may cause us to see a Hash
1786 // here instead of a preprocessor line comment.
1787 if (getTok().is(AsmToken::Hash)) {
1788 StringRef CommentStr = parseStringToEndOfStatement();
1789 Lexer.Lex();
1790 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1791 }
1792
Nirav Dave8ea792d2016-07-13 14:03:12 +00001793 // Consume any end of statement token, if present, to avoid spurious
1794 // AddBlankLine calls().
1795 if (getTok().is(AsmToken::EndOfStatement)) {
1796 Lex();
1797 }
1798
Daniel Dunbare73b2672009-08-26 22:13:22 +00001799 // Emit the label.
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00001800 if (!getTargetParser().isParsingInlineAsm())
Rafael Espindolabe991572017-02-10 15:13:12 +00001801 Out.EmitLabel(Sym, IDLoc);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001802
Kevin Enderbye7739d42011-12-09 18:09:40 +00001803 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001804 // info to make a dwarf label entry for this label if needed.
Paul Robinson43095b22018-03-08 22:39:47 +00001805 if (enabledGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001806 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1807 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001808
Tim Northover1744d0a2013-10-25 12:49:50 +00001809 getTargetParser().onLabelParsed(Sym);
1810
Eli Friedman0f4871d2012-10-22 23:58:19 +00001811 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001812 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001813
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001814 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001815 if (!getTargetParser().equalIsAsmAssignment())
1816 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001817 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001818 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001819
Jim Grosbach4b905842013-09-20 23:08:21 +00001820 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001821
1822 default: // Normal instruction or directive.
1823 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001824 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001825
1826 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001827 if (areMacrosEnabled())
Rafael Espindola22c38a02018-02-14 16:34:27 +00001828 if (const MCAsmMacro *M = getContext().lookupMacro(IDVal)) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001829 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001830 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001831
Michael J. Spencer530ce852010-10-09 11:00:50 +00001832 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001833
Eli Bendersky17233942013-01-15 22:59:42 +00001834 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001835 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001836 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001837 //
Eli Bendersky17233942013-01-15 22:59:42 +00001838 // 1. The target-specific assembly parser. Some directives are target
1839 // specific or may potentially behave differently on certain targets.
1840 // 2. Asm parser extensions. For example, platform-specific parsers
1841 // (like the ELF parser) register themselves as extensions.
1842 // 3. The generic directive parser implemented by this class. These are
1843 // all the directives that behave in a target and platform independent
1844 // manner, or at least have a default behavior that's shared between
1845 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001846
Oliver Stannard21718282016-07-26 14:19:47 +00001847 getTargetParser().flushPendingInstructions(getStreamer());
1848
Nirav Dave2364748a2016-09-16 18:30:20 +00001849 SMLoc StartTokLoc = getTok().getLoc();
1850 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1851
1852 if (hasPendingError())
1853 return true;
1854 // Currently the return value should be true if we are
1855 // uninterested but as this is at odds with the standard parsing
1856 // convention (return true = error) we have instances of a parsed
1857 // directive that fails returning true as an error. Catch these
1858 // cases as best as possible errors here.
1859 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1860 return true;
1861 // Return if we did some parsing or believe we succeeded.
1862 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001863 return false;
1864
Alp Tokercb402912014-01-24 17:20:08 +00001865 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001866 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001867 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1868 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001869 if (Handler.first)
1870 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1871
1872 // Finally, if no one else is interested in this directive, it must be
1873 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001874 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001875 default:
1876 break;
1877 case DK_SET:
1878 case DK_EQU:
1879 return parseDirectiveSet(IDVal, true);
1880 case DK_EQUIV:
1881 return parseDirectiveSet(IDVal, false);
1882 case DK_ASCII:
1883 return parseDirectiveAscii(IDVal, false);
1884 case DK_ASCIZ:
1885 case DK_STRING:
1886 return parseDirectiveAscii(IDVal, true);
1887 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001888 case DK_DC_B:
1889 return parseDirectiveValue(IDVal, 1);
1890 case DK_DC:
1891 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001892 case DK_SHORT:
1893 case DK_VALUE:
1894 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001895 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001896 case DK_LONG:
1897 case DK_INT:
1898 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001899 case DK_DC_L:
1900 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001901 case DK_QUAD:
1902 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001903 return parseDirectiveValue(IDVal, 8);
1904 case DK_DC_A:
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001905 return parseDirectiveValue(
1906 IDVal, getContext().getAsmInfo()->getCodePointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001907 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001908 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001909 case DK_SINGLE:
1910 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001911 case DK_DC_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001912 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
Jim Grosbach4b905842013-09-20 23:08:21 +00001913 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001914 case DK_DC_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001915 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
Jim Grosbach4b905842013-09-20 23:08:21 +00001916 case DK_ALIGN: {
1917 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1918 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1919 }
1920 case DK_ALIGN32: {
1921 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1922 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1923 }
1924 case DK_BALIGN:
1925 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1926 case DK_BALIGNW:
1927 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1928 case DK_BALIGNL:
1929 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1930 case DK_P2ALIGN:
1931 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1932 case DK_P2ALIGNW:
1933 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1934 case DK_P2ALIGNL:
1935 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1936 case DK_ORG:
1937 return parseDirectiveOrg();
1938 case DK_FILL:
1939 return parseDirectiveFill();
1940 case DK_ZERO:
1941 return parseDirectiveZero();
1942 case DK_EXTERN:
1943 eatToEndOfStatement(); // .extern is the default, ignore it.
1944 return false;
1945 case DK_GLOBL:
1946 case DK_GLOBAL:
1947 return parseDirectiveSymbolAttribute(MCSA_Global);
1948 case DK_LAZY_REFERENCE:
1949 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1950 case DK_NO_DEAD_STRIP:
1951 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1952 case DK_SYMBOL_RESOLVER:
1953 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1954 case DK_PRIVATE_EXTERN:
1955 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1956 case DK_REFERENCE:
1957 return parseDirectiveSymbolAttribute(MCSA_Reference);
1958 case DK_WEAK_DEFINITION:
1959 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1960 case DK_WEAK_REFERENCE:
1961 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1962 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1963 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1964 case DK_COMM:
1965 case DK_COMMON:
1966 return parseDirectiveComm(/*IsLocal=*/false);
1967 case DK_LCOMM:
1968 return parseDirectiveComm(/*IsLocal=*/true);
1969 case DK_ABORT:
1970 return parseDirectiveAbort();
1971 case DK_INCLUDE:
1972 return parseDirectiveInclude();
1973 case DK_INCBIN:
1974 return parseDirectiveIncbin();
1975 case DK_CODE16:
1976 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001977 return TokError(Twine(IDVal) +
1978 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001979 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001980 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001981 case DK_IRP:
1982 return parseDirectiveIrp(IDLoc);
1983 case DK_IRPC:
1984 return parseDirectiveIrpc(IDLoc);
1985 case DK_ENDR:
1986 return parseDirectiveEndr(IDLoc);
1987 case DK_BUNDLE_ALIGN_MODE:
1988 return parseDirectiveBundleAlignMode();
1989 case DK_BUNDLE_LOCK:
1990 return parseDirectiveBundleLock();
1991 case DK_BUNDLE_UNLOCK:
1992 return parseDirectiveBundleUnlock();
1993 case DK_SLEB128:
1994 return parseDirectiveLEB128(true);
1995 case DK_ULEB128:
1996 return parseDirectiveLEB128(false);
1997 case DK_SPACE:
1998 case DK_SKIP:
1999 return parseDirectiveSpace(IDVal);
2000 case DK_FILE:
2001 return parseDirectiveFile(IDLoc);
2002 case DK_LINE:
2003 return parseDirectiveLine();
2004 case DK_LOC:
2005 return parseDirectiveLoc();
2006 case DK_STABS:
2007 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002008 case DK_CV_FILE:
2009 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00002010 case DK_CV_FUNC_ID:
2011 return parseDirectiveCVFuncId();
2012 case DK_CV_INLINE_SITE_ID:
2013 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002014 case DK_CV_LOC:
2015 return parseDirectiveCVLoc();
2016 case DK_CV_LINETABLE:
2017 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00002018 case DK_CV_INLINE_LINETABLE:
2019 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00002020 case DK_CV_DEF_RANGE:
2021 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002022 case DK_CV_STRINGTABLE:
2023 return parseDirectiveCVStringTable();
2024 case DK_CV_FILECHECKSUMS:
2025 return parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00002026 case DK_CV_FILECHECKSUM_OFFSET:
2027 return parseDirectiveCVFileChecksumOffset();
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00002028 case DK_CV_FPO_DATA:
2029 return parseDirectiveCVFPOData();
Jim Grosbach4b905842013-09-20 23:08:21 +00002030 case DK_CFI_SECTIONS:
2031 return parseDirectiveCFISections();
2032 case DK_CFI_STARTPROC:
2033 return parseDirectiveCFIStartProc();
2034 case DK_CFI_ENDPROC:
2035 return parseDirectiveCFIEndProc();
2036 case DK_CFI_DEF_CFA:
2037 return parseDirectiveCFIDefCfa(IDLoc);
2038 case DK_CFI_DEF_CFA_OFFSET:
2039 return parseDirectiveCFIDefCfaOffset();
2040 case DK_CFI_ADJUST_CFA_OFFSET:
2041 return parseDirectiveCFIAdjustCfaOffset();
2042 case DK_CFI_DEF_CFA_REGISTER:
2043 return parseDirectiveCFIDefCfaRegister(IDLoc);
2044 case DK_CFI_OFFSET:
2045 return parseDirectiveCFIOffset(IDLoc);
2046 case DK_CFI_REL_OFFSET:
2047 return parseDirectiveCFIRelOffset(IDLoc);
2048 case DK_CFI_PERSONALITY:
2049 return parseDirectiveCFIPersonalityOrLsda(true);
2050 case DK_CFI_LSDA:
2051 return parseDirectiveCFIPersonalityOrLsda(false);
2052 case DK_CFI_REMEMBER_STATE:
2053 return parseDirectiveCFIRememberState();
2054 case DK_CFI_RESTORE_STATE:
2055 return parseDirectiveCFIRestoreState();
2056 case DK_CFI_SAME_VALUE:
2057 return parseDirectiveCFISameValue(IDLoc);
2058 case DK_CFI_RESTORE:
2059 return parseDirectiveCFIRestore(IDLoc);
2060 case DK_CFI_ESCAPE:
2061 return parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00002062 case DK_CFI_RETURN_COLUMN:
2063 return parseDirectiveCFIReturnColumn(IDLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +00002064 case DK_CFI_SIGNAL_FRAME:
2065 return parseDirectiveCFISignalFrame();
2066 case DK_CFI_UNDEFINED:
2067 return parseDirectiveCFIUndefined(IDLoc);
2068 case DK_CFI_REGISTER:
2069 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00002070 case DK_CFI_WINDOW_SAVE:
2071 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00002072 case DK_MACROS_ON:
2073 case DK_MACROS_OFF:
2074 return parseDirectiveMacrosOnOff(IDVal);
2075 case DK_MACRO:
2076 return parseDirectiveMacro(IDLoc);
Michael Zuckerman56704612017-05-01 13:20:12 +00002077 case DK_ALTMACRO:
2078 case DK_NOALTMACRO:
2079 return parseDirectiveAltmacro(IDVal);
Nico Weber155dccd12014-07-24 17:08:39 +00002080 case DK_EXITM:
2081 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00002082 case DK_ENDM:
2083 case DK_ENDMACRO:
2084 return parseDirectiveEndMacro(IDVal);
2085 case DK_PURGEM:
2086 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00002087 case DK_END:
2088 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00002089 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00002090 return parseDirectiveError(IDLoc, false);
2091 case DK_ERROR:
2092 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00002093 case DK_WARNING:
2094 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002095 case DK_RELOC:
2096 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002097 case DK_DCB:
2098 case DK_DCB_W:
2099 return parseDirectiveDCB(IDVal, 2);
2100 case DK_DCB_B:
2101 return parseDirectiveDCB(IDVal, 1);
2102 case DK_DCB_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002103 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002104 case DK_DCB_L:
2105 return parseDirectiveDCB(IDVal, 4);
2106 case DK_DCB_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002107 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
Petr Hosek731bb9c2016-08-23 21:34:53 +00002108 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002109 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00002110 return TokError(Twine(IDVal) +
2111 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00002112 case DK_DS:
2113 case DK_DS_W:
2114 return parseDirectiveDS(IDVal, 2);
2115 case DK_DS_B:
2116 return parseDirectiveDS(IDVal, 1);
2117 case DK_DS_D:
2118 return parseDirectiveDS(IDVal, 8);
2119 case DK_DS_L:
2120 case DK_DS_S:
2121 return parseDirectiveDS(IDVal, 4);
2122 case DK_DS_P:
2123 case DK_DS_X:
2124 return parseDirectiveDS(IDVal, 12);
Coby Tayree01e53202017-10-02 14:36:31 +00002125 case DK_PRINT:
2126 return parseDirectivePrint(IDLoc);
Eli Friedman20b02642010-07-19 04:17:25 +00002127 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002128
Jim Grosbach758e0cc2012-05-01 18:38:27 +00002129 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00002130 }
Chris Lattner36e02122009-06-21 20:54:55 +00002131
Chad Rosierc7f552c2013-02-12 21:33:51 +00002132 // __asm _emit or __asm __emit
2133 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
2134 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002135 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00002136
2137 // __asm align
2138 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002139 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00002140
Coby Tayree3847be92017-04-04 17:57:23 +00002141 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
Michael Zuckerman02ecd432015-12-13 17:07:23 +00002142 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00002143 if (checkForValidSection())
2144 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00002145
Chris Lattner7cbfa442010-05-19 23:34:33 +00002146 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00002147 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00002148 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00002149 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
2150 Info.ParsedOperands);
2151 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00002152
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002153 // Dump the parsed representation, if requested.
2154 if (getShowParsedOperands()) {
2155 SmallString<256> Str;
2156 raw_svector_ostream OS(Str);
2157 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002158 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002159 if (i != 0)
2160 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002161 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002162 }
2163 OS << "]";
2164
Jim Grosbach4b905842013-09-20 23:08:21 +00002165 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002166 }
2167
Nirav Dave2364748a2016-09-16 18:30:20 +00002168 // Fail even if ParseInstruction erroneously returns false.
2169 if (hasPendingError() || ParseHadError)
2170 return true;
2171
Oliver Stannard8b273082014-06-19 15:52:37 +00002172 // If we are generating dwarf for the current section then generate a .loc
2173 // directive for the instruction.
Paul Robinson43095b22018-03-08 22:39:47 +00002174 if (!ParseHadError && enabledGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002175 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002176 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002177 unsigned Line;
2178 if (ActiveMacros.empty())
2179 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2180 else
Frederic Riss16238d92015-06-25 21:57:33 +00002181 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2182 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002183
Eli Bendersky88024712013-01-16 19:32:36 +00002184 // If we previously parsed a cpp hash file line comment then make sure the
2185 // current Dwarf File is for the CppHashFilename if not then emit the
2186 // Dwarf File table for it and adjust the line number for the .loc.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00002187 if (!CppHashInfo.Filename.empty()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002188 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002189 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002190 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002191
Jim Grosbach4b905842013-09-20 23:08:21 +00002192 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
2193 // cache with the different Loc from the call above we save the last
2194 // info we queried here with SrcMgr.FindLineNumber().
2195 unsigned CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002196 if (LastQueryIDLoc == CppHashInfo.Loc &&
2197 LastQueryBuffer == CppHashInfo.Buf)
Jim Grosbach4b905842013-09-20 23:08:21 +00002198 CppHashLocLineNo = LastQueryLine;
2199 else {
Tim Northoverc0bef992016-04-13 19:46:54 +00002200 CppHashLocLineNo =
2201 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002202 LastQueryLine = CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002203 LastQueryIDLoc = CppHashInfo.Loc;
2204 LastQueryBuffer = CppHashInfo.Buf;
Jim Grosbach4b905842013-09-20 23:08:21 +00002205 }
Tim Northoverc0bef992016-04-13 19:46:54 +00002206 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002207 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002208
Jim Grosbach4b905842013-09-20 23:08:21 +00002209 getStreamer().EmitDwarfLocDirective(
2210 getContext().getGenDwarfFileNumber(), Line, 0,
2211 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2212 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002213 }
2214
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002215 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002216 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002217 uint64_t ErrorInfo;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00002218 if (getTargetParser().MatchAndEmitInstruction(
2219 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2220 getTargetParser().isParsingInlineAsm()))
Nirav Dave2364748a2016-09-16 18:30:20 +00002221 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002222 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002223 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002224}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002225
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002226// Parse and erase curly braces marking block start/end
2227bool
2228AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2229 // Identify curly brace marking block start/end
2230 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2231 return false;
2232
2233 SMLoc StartLoc = Lexer.getLoc();
2234 Lex(); // Eat the brace
2235 if (Lexer.is(AsmToken::EndOfStatement))
2236 Lex(); // Eat EndOfStatement following the brace
2237
2238 // Erase the block start/end brace from the output asm string
2239 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2240 StartLoc.getPointer());
2241 return true;
2242}
2243
Jim Grosbach4b905842013-09-20 23:08:21 +00002244/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002245/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002246bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002247 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002248 // Lexer only ever emits HashDirective if it fully formed if it's
2249 // done the checking already so this is an internal error.
2250 assert(getTok().is(AsmToken::Integer) &&
2251 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002252 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002253 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002254 assert(getTok().is(AsmToken::String) &&
2255 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002256 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002257 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002258
Kevin Enderby72553612011-09-13 23:45:18 +00002259 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002260 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002261
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002262 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002263 CppHashInfo.Loc = L;
2264 CppHashInfo.Filename = Filename;
2265 CppHashInfo.LineNumber = LineNumber;
2266 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002267 return false;
2268}
2269
Jim Grosbach4b905842013-09-20 23:08:21 +00002270/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002271/// for the Filename and LineNo if any in the diagnostic.
2272void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002273 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002274 raw_ostream &OS = errs();
2275
2276 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002277 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002278 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2279 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002280 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002281
Jim Grosbach4b905842013-09-20 23:08:21 +00002282 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002283 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002284 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2285 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2286 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002287 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2288 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002289 }
2290
Eric Christophera7c32732012-12-18 00:30:54 +00002291 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002292 // manager changed or buffer changed (like in a nested include) then just
2293 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002294 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002295 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002296 if (Parser->SavedDiagHandler)
2297 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2298 else
Craig Topper353eda42014-04-24 06:44:33 +00002299 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002300 return;
2301 }
2302
Eric Christophera7c32732012-12-18 00:30:54 +00002303 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002304 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2305 // for the diagnostic.
2306 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002307
2308 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2309 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002310 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002311 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002312 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002313
Jim Grosbach4b905842013-09-20 23:08:21 +00002314 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2315 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002316 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002317
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002318 if (Parser->SavedDiagHandler)
2319 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2320 else
Craig Topper353eda42014-04-24 06:44:33 +00002321 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002322}
2323
Rafael Espindola2c064482012-08-21 18:29:30 +00002324// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2325// difference being that that function accepts '@' as part of identifiers and
2326// we can't do that. AsmLexer.cpp should probably be changed to handle
2327// '@' as a special case when needed.
2328static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002329 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2330 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002331}
2332
Rafael Espindola34b9c512012-06-03 23:57:14 +00002333bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002334 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002335 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002336 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002337 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002338 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002339 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002340 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002341
Preston Gurd05500642012-09-19 20:36:12 +00002342 // A macro without parameters is handled differently on Darwin:
2343 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002344 while (!Body.empty()) {
2345 // Scan for the next substitution.
2346 std::size_t End = Body.size(), Pos = 0;
2347 for (; Pos != End; ++Pos) {
2348 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002349 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002350 // This macro has no parameters, look for $0, $1, etc.
2351 if (Body[Pos] != '$' || Pos + 1 == End)
2352 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002353
Rafael Espindola1134ab232011-06-05 02:43:45 +00002354 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002355 if (Next == '$' || Next == 'n' ||
2356 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002357 break;
2358 } else {
2359 // This macro has parameters, look for \foo, \bar, etc.
2360 if (Body[Pos] == '\\' && Pos + 1 != End)
2361 break;
2362 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002363 }
2364
2365 // Add the prefix.
2366 OS << Body.slice(0, Pos);
2367
2368 // Check if we reached the end.
2369 if (Pos == End)
2370 break;
2371
Benjamin Kramer513e7442014-02-20 13:36:32 +00002372 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002373 switch (Body[Pos + 1]) {
2374 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002375 case '$':
2376 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002377 break;
2378
Jim Grosbach4b905842013-09-20 23:08:21 +00002379 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002380 case 'n':
2381 OS << A.size();
2382 break;
2383
Jim Grosbach4b905842013-09-20 23:08:21 +00002384 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002385 default: {
2386 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002387 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002388 if (Index >= A.size())
2389 break;
2390
2391 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002392 for (const AsmToken &Token : A[Index])
2393 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002394 break;
2395 }
2396 }
2397 Pos += 2;
2398 } else {
2399 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002400
2401 // Check for the \@ pseudo-variable.
2402 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002403 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002404 else
2405 while (isIdentifierChar(Body[I]) && I + 1 != End)
2406 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002407
Jim Grosbach4b905842013-09-20 23:08:21 +00002408 const char *Begin = Body.data() + Pos + 1;
2409 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002410 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002411
Toma Tabacu217116e2015-04-27 10:50:29 +00002412 if (Argument == "@") {
2413 OS << NumOfMacroInstantiations;
2414 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002415 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002416 for (; Index < NParameters; ++Index)
2417 if (Parameters[Index].Name == Argument)
2418 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002419
Toma Tabacu217116e2015-04-27 10:50:29 +00002420 if (Index == NParameters) {
2421 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2422 Pos += 3;
2423 else {
2424 OS << '\\' << Argument;
2425 Pos = I;
2426 }
2427 } else {
2428 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002429 for (const AsmToken &Token : A[Index])
Michael Zuckerman56704612017-05-01 13:20:12 +00002430 // For altmacro mode, you can write '%expr'.
2431 // The prefix '%' evaluates the expression 'expr'
2432 // and uses the result as a string (e.g. replace %(1+2) with the string "3").
2433 // Here, we identify the integer token which is the result of the
2434 // absolute expression evaluation and replace it with its string representation.
2435 if ((Lexer.IsaAltMacroMode()) &&
2436 (*(Token.getString().begin()) == '%') && Token.is(AsmToken::Integer))
2437 // Emit an integer value to the buffer.
2438 OS << Token.getIntVal();
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002439 // Only Token that was validated as a string and begins with '<'
2440 // is considered altMacroString!!!
2441 else if ((Lexer.IsaAltMacroMode()) &&
2442 (*(Token.getString().begin()) == '<') &&
2443 Token.is(AsmToken::String)) {
2444 std::string Res;
2445 altMacroString(Token.getStringContents(), Res);
2446 OS << Res;
2447 }
Toma Tabacu217116e2015-04-27 10:50:29 +00002448 // We expect no quotes around the string's contents when
2449 // parsing for varargs.
Michael Zuckerman56704612017-05-01 13:20:12 +00002450 else if (Token.isNot(AsmToken::String) || VarargParameter)
Craig Topper84008482015-10-10 05:38:14 +00002451 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002452 else
Craig Topper84008482015-10-10 05:38:14 +00002453 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002454
2455 Pos += 1 + Argument.size();
2456 }
Preston Gurd05500642012-09-19 20:36:12 +00002457 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002458 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002459 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002460 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002461 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002462
Rafael Espindola1134ab232011-06-05 02:43:45 +00002463 return false;
2464}
Daniel Dunbar43235712010-07-18 18:54:11 +00002465
Nico Weber2a8f9222014-07-24 16:29:04 +00002466MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002467 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002468 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002469 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002470
Jim Grosbach4b905842013-09-20 23:08:21 +00002471static bool isOperator(AsmToken::TokenKind kind) {
2472 switch (kind) {
2473 default:
2474 return false;
2475 case AsmToken::Plus:
2476 case AsmToken::Minus:
2477 case AsmToken::Tilde:
2478 case AsmToken::Slash:
2479 case AsmToken::Star:
2480 case AsmToken::Dot:
2481 case AsmToken::Equal:
2482 case AsmToken::EqualEqual:
2483 case AsmToken::Pipe:
2484 case AsmToken::PipePipe:
2485 case AsmToken::Caret:
2486 case AsmToken::Amp:
2487 case AsmToken::AmpAmp:
2488 case AsmToken::Exclaim:
2489 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002490 case AsmToken::Less:
2491 case AsmToken::LessEqual:
2492 case AsmToken::LessLess:
2493 case AsmToken::LessGreater:
2494 case AsmToken::Greater:
2495 case AsmToken::GreaterEqual:
2496 case AsmToken::GreaterGreater:
2497 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002498 }
2499}
2500
David Majnemer16252452014-01-29 00:07:39 +00002501namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002502
David Majnemer16252452014-01-29 00:07:39 +00002503class AsmLexerSkipSpaceRAII {
2504public:
2505 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2506 Lexer.setSkipSpace(SkipSpace);
2507 }
2508
2509 ~AsmLexerSkipSpaceRAII() {
2510 Lexer.setSkipSpace(true);
2511 }
2512
2513private:
2514 AsmLexer &Lexer;
2515};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002516
2517} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002518
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002519bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2520
2521 if (Vararg) {
2522 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2523 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002524 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002525 }
2526 return false;
2527 }
2528
Rafael Espindola768b41c2012-06-15 14:02:34 +00002529 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002530
David Majnemer16252452014-01-29 00:07:39 +00002531 // Darwin doesn't use spaces to delmit arguments.
2532 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002533
Scott Egertona1fa68a2016-02-11 13:48:49 +00002534 bool SpaceEaten;
2535
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002536 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002537 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002538 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002539 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002540
Scott Egertona1fa68a2016-02-11 13:48:49 +00002541 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002542
Scott Egertona1fa68a2016-02-11 13:48:49 +00002543 if (Lexer.is(AsmToken::Comma))
2544 break;
2545
2546 if (Lexer.is(AsmToken::Space)) {
2547 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002548 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002549 }
Preston Gurd05500642012-09-19 20:36:12 +00002550
2551 // Spaces can delimit parameters, but could also be part an expression.
2552 // If the token after a space is an operator, add the token and the next
2553 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002554 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002555 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002556 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002557 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002558
Scott Egertona1fa68a2016-02-11 13:48:49 +00002559 // Whitespace after an operator can be ignored.
2560 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002561 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002562
2563 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002564 }
2565 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002566 if (SpaceEaten)
2567 break;
Preston Gurd05500642012-09-19 20:36:12 +00002568 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002569
Jim Grosbach4b905842013-09-20 23:08:21 +00002570 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002571 // to be able to fill in the remaining default parameter values
2572 if (Lexer.is(AsmToken::EndOfStatement))
2573 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002574
2575 // Adjust the current parentheses level.
2576 if (Lexer.is(AsmToken::LParen))
2577 ++ParenLevel;
2578 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2579 --ParenLevel;
2580
2581 // Append the token to the current argument list.
2582 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002583 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002584 }
Preston Gurd05500642012-09-19 20:36:12 +00002585
Rafael Espindola768b41c2012-06-15 14:02:34 +00002586 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002587 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002588 return false;
2589}
2590
2591// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002592bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002593 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002594 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002595 bool NamedParametersFound = false;
2596 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002597
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002598 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002599 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002600
Rafael Espindola768b41c2012-06-15 14:02:34 +00002601 // Parse two kinds of macro invocations:
2602 // - macros defined without any parameters accept an arbitrary number of them
2603 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002604 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002605 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2606 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002607 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002608 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002609
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002610 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002611 if (parseIdentifier(FA.Name))
2612 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002613
Nirav Dave2364748a2016-09-16 18:30:20 +00002614 if (Lexer.isNot(AsmToken::Equal))
2615 return TokError("expected '=' after formal parameter identifier");
2616
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002617 Lex();
2618
2619 NamedParametersFound = true;
2620 }
Michael Zuckerman56704612017-05-01 13:20:12 +00002621 bool Vararg = HasVararg && Parameter == (NParameters - 1);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002622
Nirav Dave2364748a2016-09-16 18:30:20 +00002623 if (NamedParametersFound && FA.Name.empty())
2624 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002625
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002626 SMLoc StrLoc = Lexer.getLoc();
2627 SMLoc EndLoc;
Michael Zuckerman56704612017-05-01 13:20:12 +00002628 if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Percent)) {
Michael Zuckerman56704612017-05-01 13:20:12 +00002629 const MCExpr *AbsoluteExp;
2630 int64_t Value;
2631 /// Eat '%'
2632 Lex();
2633 if (parseExpression(AbsoluteExp, EndLoc))
2634 return false;
2635 if (!AbsoluteExp->evaluateAsAbsolute(Value))
2636 return Error(StrLoc, "expected absolute expression");
2637 const char *StrChar = StrLoc.getPointer();
2638 const char *EndChar = EndLoc.getPointer();
2639 AsmToken newToken(AsmToken::Integer, StringRef(StrChar , EndChar - StrChar), Value);
2640 FA.Value.push_back(newToken);
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002641 } else if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Less) &&
2642 isAltmacroString(StrLoc, EndLoc)) {
2643 const char *StrChar = StrLoc.getPointer();
2644 const char *EndChar = EndLoc.getPointer();
2645 jumpToLoc(EndLoc, CurBuffer);
2646 /// Eat from '<' to '>'
2647 Lex();
2648 AsmToken newToken(AsmToken::String, StringRef(StrChar, EndChar - StrChar));
2649 FA.Value.push_back(newToken);
2650 } else if(parseMacroArgument(FA.Value, Vararg))
Michael Zuckerman56704612017-05-01 13:20:12 +00002651 return true;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002652
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002653 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002654 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002655 unsigned FAI = 0;
2656 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002657 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002658 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002659
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002660 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002661 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002662 return Error(IDLoc, "parameter named '" + FA.Name +
2663 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002664 }
2665 PI = FAI;
2666 }
2667
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002668 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002669 if (A.size() <= PI)
2670 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002671 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002672
2673 if (FALocs.size() <= PI)
2674 FALocs.resize(PI + 1);
2675
2676 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002677 }
Jim Grosbach206661622012-07-30 22:44:17 +00002678
Preston Gurd242ed3152012-09-19 20:29:04 +00002679 // At the end of the statement, fill in remaining arguments that have
2680 // default values. If there aren't any, then the next argument is
2681 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002682 if (Lexer.is(AsmToken::EndOfStatement)) {
2683 bool Failure = false;
2684 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2685 if (A[FAI].empty()) {
2686 if (M->Parameters[FAI].Required) {
2687 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2688 "missing value for required parameter "
2689 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2690 Failure = true;
2691 }
2692
2693 if (!M->Parameters[FAI].Value.empty())
2694 A[FAI] = M->Parameters[FAI].Value;
2695 }
2696 }
2697 return Failure;
2698 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002699
2700 if (Lexer.is(AsmToken::Comma))
2701 Lex();
2702 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002703
2704 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002705}
2706
Jim Grosbach4b905842013-09-20 23:08:21 +00002707bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002708 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2709 // eliminate this, although we should protect against infinite loops.
2710 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2711 if (ActiveMacros.size() == MaxNestingDepth) {
2712 std::ostringstream MaxNestingDepthError;
2713 MaxNestingDepthError << "macros cannot be nested more than "
2714 << MaxNestingDepth << " levels deep."
2715 << " Use -asm-macro-max-nesting-depth to increase "
2716 "this limit.";
2717 return TokError(MaxNestingDepthError.str());
2718 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002719
Eli Bendersky38274122013-01-14 23:22:36 +00002720 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002721 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002722 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002723
Rafael Espindola1134ab232011-06-05 02:43:45 +00002724 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2725 // to hold the macro body with substitutions.
2726 SmallString<256> Buf;
2727 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002728 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002729
Toma Tabacu217116e2015-04-27 10:50:29 +00002730 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002731 return true;
2732
Eli Bendersky38274122013-01-14 23:22:36 +00002733 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002734 // instantiation.
2735 OS << ".endmacro\n";
2736
Rafael Espindola3560ff22014-08-27 20:03:13 +00002737 std::unique_ptr<MemoryBuffer> Instantiation =
2738 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002739
Daniel Dunbar43235712010-07-18 18:54:11 +00002740 // Create the macro instantiation object and add to the current macro
2741 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002742 MacroInstantiation *MI = new MacroInstantiation(
2743 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002744 ActiveMacros.push_back(MI);
2745
Toma Tabacu217116e2015-04-27 10:50:29 +00002746 ++NumOfMacroInstantiations;
2747
Daniel Dunbar43235712010-07-18 18:54:11 +00002748 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002749 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002750 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002751 Lex();
2752
2753 return false;
2754}
2755
Jim Grosbach4b905842013-09-20 23:08:21 +00002756void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002757 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002758 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002759 Lex();
2760
2761 // Pop the instantiation entry.
2762 delete ActiveMacros.back();
2763 ActiveMacros.pop_back();
2764}
2765
Jim Grosbach4b905842013-09-20 23:08:21 +00002766bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002767 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002768 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002769 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002770 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2771 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002772 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002773
Pete Cooper80d21cb2015-06-22 19:35:57 +00002774 if (!Sym) {
2775 // In the case where we parse an expression starting with a '.', we will
2776 // not generate an error, nor will we create a symbol. In this case we
2777 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002778 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002779 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002780
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002781 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002782 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002783 if (NoDeadStrip)
2784 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2785
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002786 return false;
2787}
2788
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002789/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002790/// ::= identifier
2791/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002792bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002793 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002794 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2795 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002796 // handle this as a context dependent token, instead we detect adjacent tokens
2797 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002798 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2799 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002800
Hans Wennborgce69d772013-10-18 20:46:28 +00002801 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002802
2803 AsmToken Buf[1];
2804 Lexer.peekTokens(Buf, false);
2805
2806 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002807 return true;
2808
Hans Wennborgce69d772013-10-18 20:46:28 +00002809 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002810 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002811 return true;
2812
Nirav Daved0463322016-10-12 13:58:07 +00002813 // eat $ or @
2814 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002815 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002816 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002817 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002818 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002819 return false;
2820 }
2821
Jim Grosbach4b905842013-09-20 23:08:21 +00002822 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002823 return true;
2824
Sean Callanan936b0d32010-01-19 21:44:56 +00002825 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002826
Sean Callanan686ed8d2010-01-19 20:22:31 +00002827 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002828
2829 return false;
2830}
2831
Jim Grosbach4b905842013-09-20 23:08:21 +00002832/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002833/// ::= .equ identifier ',' expression
2834/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002835/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002836bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002837 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002838 if (check(parseIdentifier(Name), "expected identifier") ||
2839 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2840 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2841 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002842}
2843
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002844bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002845 if (check(getTok().isNot(AsmToken::String), "expected string"))
2846 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002847
2848 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002849 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002850 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2851 if (Str[i] != '\\') {
2852 Data += Str[i];
2853 continue;
2854 }
2855
2856 // Recognize escaped characters. Note that this escape semantics currently
2857 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2858 ++i;
2859 if (i == e)
2860 return TokError("unexpected backslash at end of string");
2861
2862 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002863 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002864 // Consume up to three octal characters.
2865 unsigned Value = Str[i] - '0';
2866
Jim Grosbach4b905842013-09-20 23:08:21 +00002867 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002868 ++i;
2869 Value = Value * 8 + (Str[i] - '0');
2870
Jim Grosbach4b905842013-09-20 23:08:21 +00002871 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002872 ++i;
2873 Value = Value * 8 + (Str[i] - '0');
2874 }
2875 }
2876
2877 if (Value > 255)
2878 return TokError("invalid octal escape sequence (out of range)");
2879
Jim Grosbach4b905842013-09-20 23:08:21 +00002880 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002881 continue;
2882 }
2883
2884 // Otherwise recognize individual escapes.
2885 switch (Str[i]) {
2886 default:
2887 // Just reject invalid escape sequences for now.
2888 return TokError("invalid escape sequence (unrecognized character)");
2889
2890 case 'b': Data += '\b'; break;
2891 case 'f': Data += '\f'; break;
2892 case 'n': Data += '\n'; break;
2893 case 'r': Data += '\r'; break;
2894 case 't': Data += '\t'; break;
2895 case '"': Data += '"'; break;
2896 case '\\': Data += '\\'; break;
2897 }
2898 }
2899
Nirav Davea645433c2016-07-18 15:24:03 +00002900 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002901 return false;
2902}
2903
Jim Grosbach4b905842013-09-20 23:08:21 +00002904/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002905/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002906bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002907 auto parseOp = [&]() -> bool {
2908 std::string Data;
2909 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002910 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002911 getStreamer().EmitBytes(Data);
2912 if (ZeroTerminated)
2913 getStreamer().EmitBytes(StringRef("\0", 1));
2914 return false;
2915 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002916
Nirav Dave1a9044b2016-10-24 14:35:29 +00002917 if (parseMany(parseOp))
2918 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002919 return false;
2920}
2921
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002922/// parseDirectiveReloc
2923/// ::= .reloc expression , identifier [ , expression ]
2924bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2925 const MCExpr *Offset;
2926 const MCExpr *Expr = nullptr;
2927
2928 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00002929 int64_t OffsetValue;
2930 // We can only deal with constant expressions at the moment.
2931
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002932 if (parseExpression(Offset))
2933 return true;
2934
Nirav Davea645433c2016-07-18 15:24:03 +00002935 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2936 "expression is not a constant value") ||
2937 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2938 parseToken(AsmToken::Comma, "expected comma") ||
2939 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2940 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002941
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002942 SMLoc NameLoc = Lexer.getTok().getLoc();
2943 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002944 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002945
2946 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002947 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002948 SMLoc ExprLoc = Lexer.getLoc();
2949 if (parseExpression(Expr))
2950 return true;
2951
2952 MCValue Value;
2953 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2954 return Error(ExprLoc, "expression must be relocatable");
2955 }
2956
Nirav Davea645433c2016-07-18 15:24:03 +00002957 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002958 "unexpected token in .reloc directive"))
2959 return true;
2960
2961 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2962 return Error(NameLoc, "unknown relocation name");
2963
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002964 return false;
2965}
2966
Jim Grosbach4b905842013-09-20 23:08:21 +00002967/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002968/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002969bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2970 auto parseOp = [&]() -> bool {
2971 const MCExpr *Value;
2972 SMLoc ExprLoc = getLexer().getLoc();
2973 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002974 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002975 // Special case constant expressions to match code generator.
2976 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2977 assert(Size <= 8 && "Invalid size");
2978 uint64_t IntValue = MCE->getValue();
2979 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2980 return Error(ExprLoc, "out of range literal value");
2981 getStreamer().EmitIntValue(IntValue, Size);
2982 } else
2983 getStreamer().EmitValue(Value, Size, ExprLoc);
2984 return false;
2985 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002986
Nirav Dave1a9044b2016-10-24 14:35:29 +00002987 if (parseMany(parseOp))
2988 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002989 return false;
2990}
2991
David Woodhoused6de0d92014-02-01 16:20:59 +00002992/// ParseDirectiveOctaValue
2993/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002994
2995bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
2996 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00002997 if (checkForValidSection())
2998 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002999 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
3000 return TokError("unknown token in expression");
3001 SMLoc ExprLoc = getTok().getLoc();
3002 APInt IntValue = getTok().getAPIntVal();
3003 uint64_t hi, lo;
3004 Lex();
3005 if (!IntValue.isIntN(128))
3006 return Error(ExprLoc, "out of range literal value");
3007 if (!IntValue.isIntN(64)) {
3008 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
3009 lo = IntValue.getLoBits(64).getZExtValue();
3010 } else {
3011 hi = 0;
3012 lo = IntValue.getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00003013 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003014 if (MAI.isLittleEndian()) {
3015 getStreamer().EmitIntValue(lo, 8);
3016 getStreamer().EmitIntValue(hi, 8);
3017 } else {
3018 getStreamer().EmitIntValue(hi, 8);
3019 getStreamer().EmitIntValue(lo, 8);
3020 }
3021 return false;
3022 };
David Woodhoused6de0d92014-02-01 16:20:59 +00003023
Nirav Dave1a9044b2016-10-24 14:35:29 +00003024 if (parseMany(parseOp))
3025 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00003026 return false;
3027}
3028
Petr Hosek4cb08ce2016-09-23 19:25:15 +00003029bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
3030 // We don't truly support arithmetic on floating point expressions, so we
3031 // have to manually parse unary prefixes.
3032 bool IsNeg = false;
3033 if (getLexer().is(AsmToken::Minus)) {
3034 Lexer.Lex();
3035 IsNeg = true;
3036 } else if (getLexer().is(AsmToken::Plus))
3037 Lexer.Lex();
3038
3039 if (Lexer.is(AsmToken::Error))
3040 return TokError(Lexer.getErr());
3041 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
3042 Lexer.isNot(AsmToken::Identifier))
3043 return TokError("unexpected token in directive");
3044
3045 // Convert to an APFloat.
3046 APFloat Value(Semantics);
3047 StringRef IDVal = getTok().getString();
3048 if (getLexer().is(AsmToken::Identifier)) {
3049 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
3050 Value = APFloat::getInf(Semantics);
3051 else if (!IDVal.compare_lower("nan"))
3052 Value = APFloat::getNaN(Semantics, false, ~0);
3053 else
3054 return TokError("invalid floating point literal");
3055 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
3056 APFloat::opInvalidOp)
3057 return TokError("invalid floating point literal");
3058 if (IsNeg)
3059 Value.changeSign();
3060
3061 // Consume the numeric token.
3062 Lex();
3063
3064 Res = Value.bitcastToAPInt();
3065
3066 return false;
3067}
3068
Jim Grosbach4b905842013-09-20 23:08:21 +00003069/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00003070/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003071bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
3072 const fltSemantics &Semantics) {
3073 auto parseOp = [&]() -> bool {
3074 APInt AsInt;
3075 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00003076 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003077 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
3078 AsInt.getBitWidth() / 8);
3079 return false;
3080 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00003081
Nirav Dave1a9044b2016-10-24 14:35:29 +00003082 if (parseMany(parseOp))
3083 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00003084 return false;
3085}
3086
Jim Grosbach4b905842013-09-20 23:08:21 +00003087/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00003088/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003089bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003090 SMLoc NumBytesLoc = Lexer.getLoc();
3091 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003092 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00003093 return true;
3094
Rafael Espindolab91bac62010-10-05 19:42:57 +00003095 int64_t Val = 0;
3096 if (getLexer().is(AsmToken::Comma)) {
3097 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003098 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00003099 return true;
3100 }
3101
Nirav Davea645433c2016-07-18 15:24:03 +00003102 if (parseToken(AsmToken::EndOfStatement,
3103 "unexpected token in '.zero' directive"))
3104 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00003105 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00003106
3107 return false;
3108}
3109
Jim Grosbach4b905842013-09-20 23:08:21 +00003110/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00003111/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003112bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003113 SMLoc NumValuesLoc = Lexer.getLoc();
3114 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003115 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00003116 return true;
3117
Roman Divackye33098f2013-09-24 17:44:41 +00003118 int64_t FillSize = 1;
3119 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00003120
David Majnemer522d3db2014-02-01 07:19:38 +00003121 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003122
Nirav Dave1a9044b2016-10-24 14:35:29 +00003123 if (parseOptionalToken(AsmToken::Comma)) {
3124 SizeLoc = getTok().getLoc();
3125 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00003126 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003127 if (parseOptionalToken(AsmToken::Comma)) {
3128 ExprLoc = getTok().getLoc();
3129 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00003130 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00003131 }
3132 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003133 if (parseToken(AsmToken::EndOfStatement,
3134 "unexpected token in '.fill' directive"))
3135 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003136
David Majnemer522d3db2014-02-01 07:19:38 +00003137 if (FillSize < 0) {
3138 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00003139 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00003140 }
3141 if (FillSize > 8) {
3142 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
3143 FillSize = 8;
3144 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00003145
David Majnemer522d3db2014-02-01 07:19:38 +00003146 if (!isUInt<32>(FillExpr) && FillSize > 4)
3147 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
3148
Petr Hosek67a94a72016-05-28 05:57:48 +00003149 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00003150
3151 return false;
3152}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003153
Jim Grosbach4b905842013-09-20 23:08:21 +00003154/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003155/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003156bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00003157 const MCExpr *Offset;
Oliver Stannard268f42f2016-12-14 10:43:58 +00003158 SMLoc OffsetLoc = Lexer.getLoc();
Nirav Davef43cc9f2016-10-10 15:24:54 +00003159 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003160 return true;
3161
3162 // Parse optional fill expression.
3163 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003164 if (parseOptionalToken(AsmToken::Comma))
3165 if (parseAbsoluteExpression(FillExpr))
3166 return addErrorSuffix(" in '.org' directive");
3167 if (parseToken(AsmToken::EndOfStatement))
3168 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00003169
Oliver Stannard268f42f2016-12-14 10:43:58 +00003170 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003171 return false;
3172}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003173
Jim Grosbach4b905842013-09-20 23:08:21 +00003174/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003175/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00003176bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003177 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003178 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003179 SMLoc MaxBytesLoc;
3180 bool HasFillExpr = false;
3181 int64_t FillExpr = 0;
3182 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003183
3184 auto parseAlign = [&]() -> bool {
Coby Tayreed483a102017-08-02 17:36:10 +00003185 if (parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00003186 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003187 if (parseOptionalToken(AsmToken::Comma)) {
3188 // The fill expression can be omitted while specifying a maximum number of
3189 // alignment bytes, e.g:
3190 // .align 3,,4
3191 if (getTok().isNot(AsmToken::Comma)) {
3192 HasFillExpr = true;
3193 if (parseAbsoluteExpression(FillExpr))
3194 return true;
3195 }
3196 if (parseOptionalToken(AsmToken::Comma))
3197 if (parseTokenLoc(MaxBytesLoc) ||
3198 parseAbsoluteExpression(MaxBytesToFill))
3199 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003200 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003201 return parseToken(AsmToken::EndOfStatement);
3202 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003203
Coby Tayreed483a102017-08-02 17:36:10 +00003204 if (checkForValidSection())
3205 return addErrorSuffix(" in directive");
3206 // Ignore empty '.p2align' directives for GNU-as compatibility
3207 if (IsPow2 && (ValueSize == 1) && getTok().is(AsmToken::EndOfStatement)) {
3208 Warning(AlignmentLoc, "p2align directive with no operand(s) is ignored");
3209 return parseToken(AsmToken::EndOfStatement);
3210 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003211 if (parseAlign())
3212 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003213
Nirav Dave2364748a2016-09-16 18:30:20 +00003214 // Always emit an alignment here even if we thrown an error.
3215 bool ReturnVal = false;
3216
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003217 // Compute alignment in bytes.
3218 if (IsPow2) {
3219 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003220 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003221 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003222 Alignment = 31;
3223 }
3224
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003225 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003226 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003227 // Reject alignments that aren't either a power of two or zero,
3228 // for gas compatibility. Alignment of zero is silently rounded
3229 // up to one.
3230 if (Alignment == 0)
3231 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003232 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003233 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003234 }
3235
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003236 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003237 if (MaxBytesLoc.isValid()) {
3238 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003239 ReturnVal |= Error(MaxBytesLoc,
3240 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003241 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003242 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003243 }
3244
3245 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003246 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003247 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003248 MaxBytesToFill = 0;
3249 }
3250 }
3251
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003252 // Check whether we should use optimal code alignment for this .align
3253 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003254 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003255 assert(Section && "must have section to emit alignment");
3256 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003257 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3258 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003259 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003260 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003261 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003262 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3263 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003264 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003265
Nirav Dave2364748a2016-09-16 18:30:20 +00003266 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003267}
3268
Jim Grosbach4b905842013-09-20 23:08:21 +00003269/// parseDirectiveFile
Paul Robinson29f5f982018-01-09 23:31:48 +00003270/// ::= .file filename
Scott Linder16c7bda2018-02-23 23:01:06 +00003271/// ::= .file number [directory] filename [md5 checksum] [source source-text]
Jim Grosbach4b905842013-09-20 23:08:21 +00003272bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003273 // FIXME: I'm not sure what this is.
3274 int64_t FileNumber = -1;
Eli Bendersky17233942013-01-15 22:59:42 +00003275 if (getLexer().is(AsmToken::Integer)) {
3276 FileNumber = getTok().getIntVal();
3277 Lex();
3278
Alexander Kornienkoe12a48b2018-03-07 16:27:44 +00003279 if (FileNumber < 1)
3280 return TokError("file number less than one");
Eli Bendersky17233942013-01-15 22:59:42 +00003281 }
3282
Nirav Davea645433c2016-07-18 15:24:03 +00003283 std::string Path = getTok().getString();
Eli Bendersky17233942013-01-15 22:59:42 +00003284
3285 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003286 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003287 if (check(getTok().isNot(AsmToken::String),
3288 "unexpected token in '.file' directive") ||
3289 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003290 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003291
3292 StringRef Directory;
3293 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003294 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003295 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003296 if (check(FileNumber == -1,
3297 "explicit path specified, but no file number") ||
3298 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003299 return true;
3300 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003301 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003302 } else {
3303 Filename = Path;
3304 }
3305
Paul Robinson29f5f982018-01-09 23:31:48 +00003306 std::string Checksum;
Scott Linder16c7bda2018-02-23 23:01:06 +00003307
3308 Optional<StringRef> Source;
3309 bool HasSource = false;
3310 std::string SourceString;
3311
3312 while (!parseOptionalToken(AsmToken::EndOfStatement)) {
Paul Robinson29f5f982018-01-09 23:31:48 +00003313 StringRef Keyword;
3314 if (check(getTok().isNot(AsmToken::Identifier),
3315 "unexpected token in '.file' directive") ||
Scott Linder16c7bda2018-02-23 23:01:06 +00003316 parseIdentifier(Keyword))
Paul Robinson29f5f982018-01-09 23:31:48 +00003317 return true;
Scott Linder16c7bda2018-02-23 23:01:06 +00003318 if (Keyword == "md5") {
3319 if (check(FileNumber == -1,
3320 "MD5 checksum specified, but no file number") ||
3321 check(getTok().isNot(AsmToken::String),
3322 "unexpected token in '.file' directive") ||
3323 parseEscapedString(Checksum) ||
3324 check(Checksum.size() != 32, "invalid MD5 checksum specified"))
3325 return true;
3326 } else if (Keyword == "source") {
3327 HasSource = true;
3328 if (check(FileNumber == -1,
3329 "source specified, but no file number") ||
3330 check(getTok().isNot(AsmToken::String),
3331 "unexpected token in '.file' directive") ||
3332 parseEscapedString(SourceString))
3333 return true;
3334 } else {
3335 return TokError("unexpected token in '.file' directive");
3336 }
Paul Robinson29f5f982018-01-09 23:31:48 +00003337 }
Eli Bendersky17233942013-01-15 22:59:42 +00003338
3339 if (FileNumber == -1)
3340 getStreamer().EmitFileDirective(Filename);
3341 else {
Paul Robinson29f5f982018-01-09 23:31:48 +00003342 MD5::MD5Result *CKMem = nullptr;
3343 if (!Checksum.empty()) {
3344 Checksum = fromHex(Checksum);
3345 if (check(Checksum.size() != 16, "invalid MD5 checksum specified"))
3346 return true;
3347 CKMem = (MD5::MD5Result *)Ctx.allocate(sizeof(MD5::MD5Result), 1);
3348 memcpy(&CKMem->Bytes, Checksum.data(), 16);
3349 }
Scott Linder16c7bda2018-02-23 23:01:06 +00003350 if (HasSource) {
3351 char *SourceBuf = static_cast<char *>(Ctx.allocate(SourceString.size()));
3352 memcpy(SourceBuf, SourceString.data(), SourceString.size());
3353 Source = StringRef(SourceBuf, SourceString.size());
3354 }
David Blaikie22748082016-05-26 00:22:26 +00003355 // If there is -g option as well as debug info from directive file,
3356 // we turn off -g option, directly use the existing debug info instead.
Paul Robinson43095b22018-03-08 22:39:47 +00003357 getContext().setGenDwarfForAssembly(false);
3358 Expected<unsigned> FileNumOrErr = getStreamer().tryEmitDwarfFileDirective(
3359 FileNumber, Directory, Filename, CKMem, Source);
3360 if (!FileNumOrErr)
3361 return Error(DirectiveLoc, toString(FileNumOrErr.takeError()));
3362 FileNumber = FileNumOrErr.get();
Eli Bendersky17233942013-01-15 22:59:42 +00003363 }
3364
3365 return false;
3366}
3367
Jim Grosbach4b905842013-09-20 23:08:21 +00003368/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003369/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003370bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003371 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003372 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003373 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3374 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003375 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003376 // FIXME: Do something with the .line.
3377 }
Nirav Davea645433c2016-07-18 15:24:03 +00003378 if (parseToken(AsmToken::EndOfStatement,
3379 "unexpected token in '.line' directive"))
3380 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003381
3382 return false;
3383}
3384
Jim Grosbach4b905842013-09-20 23:08:21 +00003385/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003386/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3387/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3388/// The first number is a file number, must have been previously assigned with
3389/// a .file directive, the second number is the line number and optionally the
3390/// third number is a column position (zero if not specified). The remaining
3391/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003392bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003393 int64_t FileNumber = 0, LineNumber = 0;
3394 SMLoc Loc = getTok().getLoc();
3395 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3396 check(FileNumber < 1, Loc,
3397 "file number less than one in '.loc' directive") ||
3398 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3399 "unassigned file number in '.loc' directive"))
3400 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003401
Nirav Davea645433c2016-07-18 15:24:03 +00003402 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003403 if (getLexer().is(AsmToken::Integer)) {
3404 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003405 if (LineNumber < 0)
3406 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003407 Lex();
3408 }
3409
3410 int64_t ColumnPos = 0;
3411 if (getLexer().is(AsmToken::Integer)) {
3412 ColumnPos = getTok().getIntVal();
3413 if (ColumnPos < 0)
3414 return TokError("column position less than zero in '.loc' directive");
3415 Lex();
3416 }
3417
3418 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3419 unsigned Isa = 0;
3420 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003421
Nirav Dave1a9044b2016-10-24 14:35:29 +00003422 auto parseLocOp = [&]() -> bool {
3423 StringRef Name;
3424 SMLoc Loc = getTok().getLoc();
3425 if (parseIdentifier(Name))
3426 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003427
Nirav Dave1a9044b2016-10-24 14:35:29 +00003428 if (Name == "basic_block")
3429 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3430 else if (Name == "prologue_end")
3431 Flags |= DWARF2_FLAG_PROLOGUE_END;
3432 else if (Name == "epilogue_begin")
3433 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3434 else if (Name == "is_stmt") {
3435 Loc = getTok().getLoc();
3436 const MCExpr *Value;
3437 if (parseExpression(Value))
3438 return true;
3439 // The expression must be the constant 0 or 1.
3440 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3441 int Value = MCE->getValue();
3442 if (Value == 0)
3443 Flags &= ~DWARF2_FLAG_IS_STMT;
3444 else if (Value == 1)
3445 Flags |= DWARF2_FLAG_IS_STMT;
3446 else
3447 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003448 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003449 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003450 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003451 } else if (Name == "isa") {
3452 Loc = getTok().getLoc();
3453 const MCExpr *Value;
3454 if (parseExpression(Value))
3455 return true;
3456 // The expression must be a constant greater or equal to 0.
3457 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3458 int Value = MCE->getValue();
3459 if (Value < 0)
3460 return Error(Loc, "isa number less than zero");
3461 Isa = Value;
3462 } else {
3463 return Error(Loc, "isa number not a constant value");
3464 }
3465 } else if (Name == "discriminator") {
3466 if (parseAbsoluteExpression(Discriminator))
3467 return true;
3468 } else {
3469 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003470 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003471 return false;
3472 };
3473
Nirav Davee2369aa2016-10-26 17:28:58 +00003474 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003475 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003476
3477 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3478 Isa, Discriminator, StringRef());
3479
3480 return false;
3481}
3482
Jim Grosbach4b905842013-09-20 23:08:21 +00003483/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003484/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003485bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003486 return TokError("unsupported directive '.stabs'");
3487}
3488
Reid Kleckner2214ed82016-01-29 00:49:42 +00003489/// parseDirectiveCVFile
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003490/// ::= .cv_file number filename [checksum] [checksumkind]
Reid Kleckner2214ed82016-01-29 00:49:42 +00003491bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003492 SMLoc FileNumberLoc = getTok().getLoc();
3493 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003494 std::string Filename;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003495 std::string Checksum;
3496 int64_t ChecksumKind = 0;
Nirav Davea645433c2016-07-18 15:24:03 +00003497
3498 if (parseIntToken(FileNumber,
3499 "expected file number in '.cv_file' directive") ||
3500 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3501 check(getTok().isNot(AsmToken::String),
3502 "unexpected token in '.cv_file' directive") ||
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003503 parseEscapedString(Filename))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003504 return true;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003505 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3506 if (check(getTok().isNot(AsmToken::String),
3507 "unexpected token in '.cv_file' directive") ||
3508 parseEscapedString(Checksum) ||
3509 parseIntToken(ChecksumKind,
3510 "expected checksum kind in '.cv_file' directive") ||
3511 parseToken(AsmToken::EndOfStatement,
3512 "unexpected token in '.cv_file' directive"))
3513 return true;
3514 }
Nirav Dave1ab71992016-07-18 19:35:21 +00003515
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003516 Checksum = fromHex(Checksum);
3517 void *CKMem = Ctx.allocate(Checksum.size(), 1);
3518 memcpy(CKMem, Checksum.data(), Checksum.size());
3519 ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem),
3520 Checksum.size());
3521
3522 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename, ChecksumAsBytes,
3523 static_cast<uint8_t>(ChecksumKind)))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003524 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003525
3526 return false;
3527}
3528
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003529bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3530 StringRef DirectiveName) {
3531 SMLoc Loc;
3532 return parseTokenLoc(Loc) ||
3533 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3534 "' directive") ||
3535 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3536 "expected function id within range [0, UINT_MAX)");
3537}
3538
3539bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3540 SMLoc Loc;
3541 return parseTokenLoc(Loc) ||
3542 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3543 "' directive") ||
3544 check(FileNumber < 1, Loc, "file number less than one in '" +
3545 DirectiveName + "' directive") ||
3546 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3547 "unassigned file number in '" + DirectiveName + "' directive");
3548}
3549
3550/// parseDirectiveCVFuncId
3551/// ::= .cv_func_id FunctionId
3552///
3553/// Introduces a function ID that can be used with .cv_loc.
3554bool AsmParser::parseDirectiveCVFuncId() {
3555 SMLoc FunctionIdLoc = getTok().getLoc();
3556 int64_t FunctionId;
3557
3558 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3559 parseToken(AsmToken::EndOfStatement,
3560 "unexpected token in '.cv_func_id' directive"))
3561 return true;
3562
3563 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003564 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003565
3566 return false;
3567}
3568
3569/// parseDirectiveCVInlineSiteId
3570/// ::= .cv_inline_site_id FunctionId
3571/// "within" IAFunc
3572/// "inlined_at" IAFile IALine [IACol]
3573///
3574/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3575/// at" source location information for use in the line table of the caller,
3576/// whether the caller is a real function or another inlined call site.
3577bool AsmParser::parseDirectiveCVInlineSiteId() {
3578 SMLoc FunctionIdLoc = getTok().getLoc();
3579 int64_t FunctionId;
3580 int64_t IAFunc;
3581 int64_t IAFile;
3582 int64_t IALine;
3583 int64_t IACol = 0;
3584
3585 // FunctionId
3586 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3587 return true;
3588
3589 // "within"
3590 if (check((getLexer().isNot(AsmToken::Identifier) ||
3591 getTok().getIdentifier() != "within"),
3592 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3593 return true;
3594 Lex();
3595
3596 // IAFunc
3597 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3598 return true;
3599
3600 // "inlined_at"
3601 if (check((getLexer().isNot(AsmToken::Identifier) ||
3602 getTok().getIdentifier() != "inlined_at"),
3603 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3604 "directive") )
3605 return true;
3606 Lex();
3607
3608 // IAFile IALine
3609 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3610 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3611 return true;
3612
3613 // [IACol]
3614 if (getLexer().is(AsmToken::Integer)) {
3615 IACol = getTok().getIntVal();
3616 Lex();
3617 }
3618
3619 if (parseToken(AsmToken::EndOfStatement,
3620 "unexpected token in '.cv_inline_site_id' directive"))
3621 return true;
3622
3623 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3624 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003625 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003626
3627 return false;
3628}
3629
Reid Kleckner2214ed82016-01-29 00:49:42 +00003630/// parseDirectiveCVLoc
3631/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3632/// [is_stmt VALUE]
3633/// The first number is a file number, must have been previously assigned with
3634/// a .file directive, the second number is the line number and optionally the
3635/// third number is a column position (zero if not specified). The remaining
3636/// optional items are .loc sub-directives.
3637bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003638 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003639 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003640 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3641 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003642 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003643
3644 int64_t LineNumber = 0;
3645 if (getLexer().is(AsmToken::Integer)) {
3646 LineNumber = getTok().getIntVal();
3647 if (LineNumber < 0)
3648 return TokError("line number less than zero in '.cv_loc' directive");
3649 Lex();
3650 }
3651
3652 int64_t ColumnPos = 0;
3653 if (getLexer().is(AsmToken::Integer)) {
3654 ColumnPos = getTok().getIntVal();
3655 if (ColumnPos < 0)
3656 return TokError("column position less than zero in '.cv_loc' directive");
3657 Lex();
3658 }
3659
3660 bool PrologueEnd = false;
3661 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003662
3663 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003664 StringRef Name;
3665 SMLoc Loc = getTok().getLoc();
3666 if (parseIdentifier(Name))
3667 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003668 if (Name == "prologue_end")
3669 PrologueEnd = true;
3670 else if (Name == "is_stmt") {
3671 Loc = getTok().getLoc();
3672 const MCExpr *Value;
3673 if (parseExpression(Value))
3674 return true;
3675 // The expression must be the constant 0 or 1.
3676 IsStmt = ~0ULL;
3677 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3678 IsStmt = MCE->getValue();
3679
3680 if (IsStmt > 1)
3681 return Error(Loc, "is_stmt value not 0 or 1");
3682 } else {
3683 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3684 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003685 return false;
3686 };
3687
3688 if (parseMany(parseOp, false /*hasComma*/))
3689 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003690
3691 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003692 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3693 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003694 return false;
3695}
3696
3697/// parseDirectiveCVLinetable
3698/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3699bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003700 int64_t FunctionId;
3701 StringRef FnStartName, FnEndName;
3702 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003703 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003704 parseToken(AsmToken::Comma,
3705 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003706 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3707 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003708 parseToken(AsmToken::Comma,
3709 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003710 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3711 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003712 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003713
3714 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3715 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3716
3717 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3718 return false;
3719}
3720
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003721/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003722/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003723bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003724 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3725 StringRef FnStartName, FnEndName;
3726 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003727 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003728 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003729 parseIntToken(
3730 SourceFileId,
3731 "expected SourceField in '.cv_inline_linetable' directive") ||
3732 check(SourceFileId <= 0, Loc,
3733 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003734 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003735 parseIntToken(
3736 SourceLineNum,
3737 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3738 check(SourceLineNum < 0, Loc,
3739 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003740 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3741 "expected identifier in directive") ||
3742 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3743 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003744 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003745
Nirav Davea645433c2016-07-18 15:24:03 +00003746 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3747 return true;
3748
3749 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3750 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003751 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3752 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003753 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003754 return false;
3755}
3756
David Majnemer408b5e62016-02-05 01:55:49 +00003757/// parseDirectiveCVDefRange
3758/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3759bool AsmParser::parseDirectiveCVDefRange() {
3760 SMLoc Loc;
3761 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3762 while (getLexer().is(AsmToken::Identifier)) {
3763 Loc = getLexer().getLoc();
3764 StringRef GapStartName;
3765 if (parseIdentifier(GapStartName))
3766 return Error(Loc, "expected identifier in directive");
3767 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3768
3769 Loc = getLexer().getLoc();
3770 StringRef GapEndName;
3771 if (parseIdentifier(GapEndName))
3772 return Error(Loc, "expected identifier in directive");
3773 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3774
3775 Ranges.push_back({GapStartSym, GapEndSym});
3776 }
3777
David Majnemer408b5e62016-02-05 01:55:49 +00003778 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003779 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3780 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003781 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003782
3783 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3784 return false;
3785}
3786
Reid Kleckner2214ed82016-01-29 00:49:42 +00003787/// parseDirectiveCVStringTable
3788/// ::= .cv_stringtable
3789bool AsmParser::parseDirectiveCVStringTable() {
3790 getStreamer().EmitCVStringTableDirective();
3791 return false;
3792}
3793
3794/// parseDirectiveCVFileChecksums
3795/// ::= .cv_filechecksums
3796bool AsmParser::parseDirectiveCVFileChecksums() {
3797 getStreamer().EmitCVFileChecksumsDirective();
3798 return false;
3799}
3800
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003801/// parseDirectiveCVFileChecksumOffset
3802/// ::= .cv_filechecksumoffset fileno
3803bool AsmParser::parseDirectiveCVFileChecksumOffset() {
3804 int64_t FileNo;
3805 if (parseIntToken(FileNo, "expected identifier in directive"))
3806 return true;
3807 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3808 return true;
3809 getStreamer().EmitCVFileChecksumOffsetDirective(FileNo);
3810 return false;
3811}
3812
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00003813/// parseDirectiveCVFPOData
3814/// ::= .cv_fpo_data procsym
3815bool AsmParser::parseDirectiveCVFPOData() {
3816 SMLoc DirLoc = getLexer().getLoc();
3817 StringRef ProcName;
3818 if (parseIdentifier(ProcName))
3819 return TokError("expected symbol name");
3820 if (parseEOL("unexpected tokens"))
3821 return addErrorSuffix(" in '.cv_fpo_data' directive");
3822 MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName);
3823 getStreamer().EmitCVFPOData(ProcSym, DirLoc);
3824 return false;
3825}
3826
Jim Grosbach4b905842013-09-20 23:08:21 +00003827/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003828/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003829bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003830 StringRef Name;
3831 bool EH = false;
3832 bool Debug = false;
3833
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003834 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003835 return TokError("Expected an identifier");
3836
3837 if (Name == ".eh_frame")
3838 EH = true;
3839 else if (Name == ".debug_frame")
3840 Debug = true;
3841
3842 if (getLexer().is(AsmToken::Comma)) {
3843 Lex();
3844
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003845 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003846 return TokError("Expected an identifier");
3847
3848 if (Name == ".eh_frame")
3849 EH = true;
3850 else if (Name == ".debug_frame")
3851 Debug = true;
3852 }
3853
3854 getStreamer().EmitCFISections(EH, Debug);
3855 return false;
3856}
3857
Jim Grosbach4b905842013-09-20 23:08:21 +00003858/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003859/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003860bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003861 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003862 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3863 if (check(parseIdentifier(Simple) || Simple != "simple",
3864 "unexpected token") ||
3865 parseToken(AsmToken::EndOfStatement))
3866 return addErrorSuffix(" in '.cfi_startproc' directive");
3867 }
Nirav Davea645433c2016-07-18 15:24:03 +00003868
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003869 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003870 return false;
3871}
3872
Jim Grosbach4b905842013-09-20 23:08:21 +00003873/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003874/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003875bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003876 getStreamer().EmitCFIEndProc();
3877 return false;
3878}
3879
Jim Grosbach4b905842013-09-20 23:08:21 +00003880/// \brief parse register name or number.
3881bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003882 SMLoc DirectiveLoc) {
3883 unsigned RegNo;
3884
3885 if (getLexer().isNot(AsmToken::Integer)) {
3886 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3887 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003888 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003889 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003890 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003891
3892 return false;
3893}
3894
Jim Grosbach4b905842013-09-20 23:08:21 +00003895/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003896/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003897bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003898 int64_t Register = 0, Offset = 0;
3899 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3900 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3901 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003902 return true;
3903
3904 getStreamer().EmitCFIDefCfa(Register, Offset);
3905 return false;
3906}
3907
Jim Grosbach4b905842013-09-20 23:08:21 +00003908/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003909/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003910bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003911 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003912 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003913 return true;
3914
3915 getStreamer().EmitCFIDefCfaOffset(Offset);
3916 return false;
3917}
3918
Jim Grosbach4b905842013-09-20 23:08:21 +00003919/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003920/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003921bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003922 int64_t Register1 = 0, Register2 = 0;
3923 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3924 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3925 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003926 return true;
3927
3928 getStreamer().EmitCFIRegister(Register1, Register2);
3929 return false;
3930}
3931
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003932/// parseDirectiveCFIWindowSave
3933/// ::= .cfi_window_save
3934bool AsmParser::parseDirectiveCFIWindowSave() {
3935 getStreamer().EmitCFIWindowSave();
3936 return false;
3937}
3938
Jim Grosbach4b905842013-09-20 23:08:21 +00003939/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003940/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003941bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003942 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003943 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003944 return true;
3945
3946 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3947 return false;
3948}
3949
Jim Grosbach4b905842013-09-20 23:08:21 +00003950/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003951/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003952bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003953 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003954 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003955 return true;
3956
3957 getStreamer().EmitCFIDefCfaRegister(Register);
3958 return false;
3959}
3960
Jim Grosbach4b905842013-09-20 23:08:21 +00003961/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003962/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003963bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003964 int64_t Register = 0;
3965 int64_t Offset = 0;
3966
Nirav Davea645433c2016-07-18 15:24:03 +00003967 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3968 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3969 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003970 return true;
3971
3972 getStreamer().EmitCFIOffset(Register, Offset);
3973 return false;
3974}
3975
Jim Grosbach4b905842013-09-20 23:08:21 +00003976/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003977/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003978bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003979 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003980
Nirav Davea645433c2016-07-18 15:24:03 +00003981 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3982 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3983 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003984 return true;
3985
3986 getStreamer().EmitCFIRelOffset(Register, Offset);
3987 return false;
3988}
3989
3990static bool isValidEncoding(int64_t Encoding) {
3991 if (Encoding & ~0xff)
3992 return false;
3993
3994 if (Encoding == dwarf::DW_EH_PE_omit)
3995 return true;
3996
3997 const unsigned Format = Encoding & 0xf;
3998 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3999 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
4000 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
4001 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
4002 return false;
4003
4004 const unsigned Application = Encoding & 0x70;
4005 if (Application != dwarf::DW_EH_PE_absptr &&
4006 Application != dwarf::DW_EH_PE_pcrel)
4007 return false;
4008
4009 return true;
4010}
4011
Jim Grosbach4b905842013-09-20 23:08:21 +00004012/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00004013/// IsPersonality true for cfi_personality, false for cfi_lsda
4014/// ::= .cfi_personality encoding, [symbol_name]
4015/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00004016bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00004017 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004018 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00004019 return true;
4020 if (Encoding == dwarf::DW_EH_PE_omit)
4021 return false;
4022
Eli Bendersky17233942013-01-15 22:59:42 +00004023 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004024 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
4025 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4026 check(parseIdentifier(Name), "expected identifier in directive"))
4027 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004028
Jim Grosbach6f482002015-05-18 18:43:14 +00004029 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004030
4031 if (IsPersonality)
4032 getStreamer().EmitCFIPersonality(Sym, Encoding);
4033 else
4034 getStreamer().EmitCFILsda(Sym, Encoding);
4035 return false;
4036}
4037
Jim Grosbach4b905842013-09-20 23:08:21 +00004038/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00004039/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004040bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004041 getStreamer().EmitCFIRememberState();
4042 return false;
4043}
4044
Jim Grosbach4b905842013-09-20 23:08:21 +00004045/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00004046/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004047bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004048 getStreamer().EmitCFIRestoreState();
4049 return false;
4050}
4051
Jim Grosbach4b905842013-09-20 23:08:21 +00004052/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00004053/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00004054bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004055 int64_t Register = 0;
4056
Jim Grosbach4b905842013-09-20 23:08:21 +00004057 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004058 return true;
4059
4060 getStreamer().EmitCFISameValue(Register);
4061 return false;
4062}
4063
Jim Grosbach4b905842013-09-20 23:08:21 +00004064/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00004065/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00004066bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004067 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00004068 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004069 return true;
4070
4071 getStreamer().EmitCFIRestore(Register);
4072 return false;
4073}
4074
Jim Grosbach4b905842013-09-20 23:08:21 +00004075/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00004076/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004077bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00004078 std::string Values;
4079 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004080 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004081 return true;
4082
4083 Values.push_back((uint8_t)CurrValue);
4084
4085 while (getLexer().is(AsmToken::Comma)) {
4086 Lex();
4087
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004088 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004089 return true;
4090
4091 Values.push_back((uint8_t)CurrValue);
4092 }
4093
4094 getStreamer().EmitCFIEscape(Values);
4095 return false;
4096}
4097
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00004098/// parseDirectiveCFIReturnColumn
4099/// ::= .cfi_return_column register
4100bool AsmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc) {
4101 int64_t Register = 0;
4102 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4103 return true;
4104 getStreamer().EmitCFIReturnColumn(Register);
4105 return false;
4106}
4107
Jim Grosbach4b905842013-09-20 23:08:21 +00004108/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00004109/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00004110bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00004111 if (parseToken(AsmToken::EndOfStatement,
4112 "unexpected token in '.cfi_signal_frame'"))
4113 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004114
4115 getStreamer().EmitCFISignalFrame();
4116 return false;
4117}
4118
Jim Grosbach4b905842013-09-20 23:08:21 +00004119/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00004120/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00004121bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004122 int64_t Register = 0;
4123
Jim Grosbach4b905842013-09-20 23:08:21 +00004124 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004125 return true;
4126
4127 getStreamer().EmitCFIUndefined(Register);
4128 return false;
4129}
4130
Michael Zuckerman56704612017-05-01 13:20:12 +00004131/// parseDirectiveAltmacro
4132/// ::= .altmacro
4133/// ::= .noaltmacro
4134bool AsmParser::parseDirectiveAltmacro(StringRef Directive) {
4135 if (getLexer().isNot(AsmToken::EndOfStatement))
4136 return TokError("unexpected token in '" + Directive + "' directive");
4137 if (Directive == ".altmacro")
4138 getLexer().SetAltMacroMode(true);
4139 else
4140 getLexer().SetAltMacroMode(false);
4141 return false;
4142}
4143
Jim Grosbach4b905842013-09-20 23:08:21 +00004144/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00004145/// ::= .macros_on
4146/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00004147bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004148 if (parseToken(AsmToken::EndOfStatement,
4149 "unexpected token in '" + Directive + "' directive"))
4150 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004151
Jim Grosbach4b905842013-09-20 23:08:21 +00004152 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00004153 return false;
4154}
4155
Jim Grosbach4b905842013-09-20 23:08:21 +00004156/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004157/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00004158bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004159 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004160 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00004161 return TokError("expected identifier in '.macro' directive");
4162
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004163 if (getLexer().is(AsmToken::Comma))
4164 Lex();
4165
Eli Bendersky17233942013-01-15 22:59:42 +00004166 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00004167 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004168
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00004169 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004170 return Error(Lexer.getLoc(),
4171 "Vararg parameter '" + Parameters.back().Name +
4172 "' should be last one in the list of parameters.");
4173
David Majnemer91fc4c22014-01-29 18:57:46 +00004174 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004175 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00004176 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004177
Coby Tayreebedaae02017-04-08 20:29:03 +00004178 // Emit an error if two (or more) named parameters share the same name
4179 for (const MCAsmMacroParameter& CurrParam : Parameters)
4180 if (CurrParam.Name.equals(Parameter.Name))
4181 return TokError("macro '" + Name + "' has multiple parameters"
4182 " named '" + Parameter.Name + "'");
4183
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004184 if (Lexer.is(AsmToken::Colon)) {
4185 Lex(); // consume ':'
4186
4187 SMLoc QualLoc;
4188 StringRef Qualifier;
4189
4190 QualLoc = Lexer.getLoc();
4191 if (parseIdentifier(Qualifier))
4192 return Error(QualLoc, "missing parameter qualifier for "
4193 "'" + Parameter.Name + "' in macro '" + Name + "'");
4194
4195 if (Qualifier == "req")
4196 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00004197 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004198 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004199 else
4200 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
4201 "for '" + Parameter.Name + "' in macro '" + Name + "'");
4202 }
4203
David Majnemer91fc4c22014-01-29 18:57:46 +00004204 if (getLexer().is(AsmToken::Equal)) {
4205 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004206
4207 SMLoc ParamLoc;
4208
4209 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004210 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00004211 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004212
4213 if (Parameter.Required)
4214 Warning(ParamLoc, "pointless default value for required parameter "
4215 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00004216 }
David Majnemer91fc4c22014-01-29 18:57:46 +00004217
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00004218 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00004219
4220 if (getLexer().is(AsmToken::Comma))
4221 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004222 }
4223
Nirav Dave1180e6892016-06-02 17:15:05 +00004224 // Eat just the end of statement.
4225 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004226
Nirav Dave1180e6892016-06-02 17:15:05 +00004227 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00004228 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004229 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00004230 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004231 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00004232 // Ignore Lexing errors in macros.
4233 while (Lexer.is(AsmToken::Error)) {
4234 Lexer.Lex();
4235 }
4236
Eli Bendersky17233942013-01-15 22:59:42 +00004237 // Check whether we have reached the end of the file.
4238 if (getLexer().is(AsmToken::Eof))
4239 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
4240
4241 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004242 if (getLexer().is(AsmToken::Identifier)) {
4243 if (getTok().getIdentifier() == ".endm" ||
4244 getTok().getIdentifier() == ".endmacro") {
4245 if (MacroDepth == 0) { // Outermost macro.
4246 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00004247 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004248 if (getLexer().isNot(AsmToken::EndOfStatement))
4249 return TokError("unexpected token in '" + EndToken.getIdentifier() +
4250 "' directive");
4251 break;
4252 } else {
4253 // Otherwise we just found the end of an inner macro.
4254 --MacroDepth;
4255 }
4256 } else if (getTok().getIdentifier() == ".macro") {
4257 // We allow nested macros. Those aren't instantiated until the outermost
4258 // macro is expanded so just ignore them for now.
4259 ++MacroDepth;
4260 }
Eli Bendersky17233942013-01-15 22:59:42 +00004261 }
4262
4263 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004264 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00004265 }
4266
Rafael Espindola22c38a02018-02-14 16:34:27 +00004267 if (getContext().lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00004268 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
4269 }
4270
4271 const char *BodyStart = StartToken.getLoc().getPointer();
4272 const char *BodyEnd = EndToken.getLoc().getPointer();
4273 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00004274 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Oliver Stannardc3e7c6d2018-03-06 15:32:34 +00004275 MCAsmMacro Macro(Name, Body, std::move(Parameters));
4276 DEBUG_WITH_TYPE("asm-macros", dbgs() << "Defining new macro:\n";
4277 Macro.dump());
4278 getContext().defineMacro(Name, std::move(Macro));
Eli Bendersky17233942013-01-15 22:59:42 +00004279 return false;
4280}
4281
Jim Grosbach4b905842013-09-20 23:08:21 +00004282/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00004283///
4284/// With the support added for named parameters there may be code out there that
4285/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00004286/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00004287/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00004288/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00004289/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4290/// warning that the positional parameter found in body which have no effect.
4291/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00004292/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00004293/// intended or change the macro to use the named parameters. It is possible
4294/// this warning will trigger when the none of the named parameters are used
4295/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00004296void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00004297 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004298 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00004299 // If this macro is not defined with named parameters the warning we are
4300 // checking for here doesn't apply.
4301 unsigned NParameters = Parameters.size();
4302 if (NParameters == 0)
4303 return;
4304
4305 bool NamedParametersFound = false;
4306 bool PositionalParametersFound = false;
4307
4308 // Look at the body of the macro for use of both the named parameters and what
4309 // are likely to be positional parameters. This is what expandMacro() is
4310 // doing when it finds the parameters in the body.
4311 while (!Body.empty()) {
4312 // Scan for the next possible parameter.
4313 std::size_t End = Body.size(), Pos = 0;
4314 for (; Pos != End; ++Pos) {
4315 // Check for a substitution or escape.
4316 // This macro is defined with parameters, look for \foo, \bar, etc.
4317 if (Body[Pos] == '\\' && Pos + 1 != End)
4318 break;
4319
4320 // This macro should have parameters, but look for $0, $1, ..., $n too.
4321 if (Body[Pos] != '$' || Pos + 1 == End)
4322 continue;
4323 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004324 if (Next == '$' || Next == 'n' ||
4325 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004326 break;
4327 }
4328
4329 // Check if we reached the end.
4330 if (Pos == End)
4331 break;
4332
4333 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004334 switch (Body[Pos + 1]) {
4335 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004336 case '$':
4337 break;
4338
Jim Grosbach4b905842013-09-20 23:08:21 +00004339 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004340 case 'n':
4341 PositionalParametersFound = true;
4342 break;
4343
Jim Grosbach4b905842013-09-20 23:08:21 +00004344 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004345 default: {
4346 PositionalParametersFound = true;
4347 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004348 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004349 }
4350 Pos += 2;
4351 } else {
4352 unsigned I = Pos + 1;
4353 while (isIdentifierChar(Body[I]) && I + 1 != End)
4354 ++I;
4355
Jim Grosbach4b905842013-09-20 23:08:21 +00004356 const char *Begin = Body.data() + Pos + 1;
4357 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004358 unsigned Index = 0;
4359 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004360 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004361 break;
4362
4363 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004364 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4365 Pos += 3;
4366 else {
4367 Pos = I;
4368 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004369 } else {
4370 NamedParametersFound = true;
4371 Pos += 1 + Argument.size();
4372 }
4373 }
4374 // Update the scan point.
4375 Body = Body.substr(Pos);
4376 }
4377
4378 if (!NamedParametersFound && PositionalParametersFound)
4379 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4380 "used in macro body, possible positional parameter "
4381 "found in body which will have no effect");
4382}
4383
Nico Weber155dccd12014-07-24 17:08:39 +00004384/// parseDirectiveExitMacro
4385/// ::= .exitm
4386bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004387 if (parseToken(AsmToken::EndOfStatement,
4388 "unexpected token in '" + Directive + "' directive"))
4389 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004390
4391 if (!isInsideMacroInstantiation())
4392 return TokError("unexpected '" + Directive + "' in file, "
4393 "no current macro definition");
4394
4395 // Exit all conditionals that are active in the current macro.
4396 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4397 TheCondState = TheCondStack.back();
4398 TheCondStack.pop_back();
4399 }
4400
4401 handleMacroExit();
4402 return false;
4403}
4404
Jim Grosbach4b905842013-09-20 23:08:21 +00004405/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004406/// ::= .endm
4407/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004408bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004409 if (getLexer().isNot(AsmToken::EndOfStatement))
4410 return TokError("unexpected token in '" + Directive + "' directive");
4411
4412 // If we are inside a macro instantiation, terminate the current
4413 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004414 if (isInsideMacroInstantiation()) {
4415 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004416 return false;
4417 }
4418
4419 // Otherwise, this .endmacro is a stray entry in the file; well formed
4420 // .endmacro directives are handled during the macro definition parsing.
4421 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004422 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004423}
4424
Jim Grosbach4b905842013-09-20 23:08:21 +00004425/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004426/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004427bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004428 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004429 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004430 if (parseTokenLoc(Loc) ||
4431 check(parseIdentifier(Name), Loc,
4432 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004433 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004434 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004435 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004436
Rafael Espindola22c38a02018-02-14 16:34:27 +00004437 if (!getContext().lookupMacro(Name))
Nirav Dave1ab71992016-07-18 19:35:21 +00004438 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4439
Rafael Espindola22c38a02018-02-14 16:34:27 +00004440 getContext().undefineMacro(Name);
Oliver Stannardc3e7c6d2018-03-06 15:32:34 +00004441 DEBUG_WITH_TYPE("asm-macros", dbgs()
4442 << "Un-defining macro: " << Name << "\n");
Eli Bendersky17233942013-01-15 22:59:42 +00004443 return false;
4444}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004445
Jim Grosbach4b905842013-09-20 23:08:21 +00004446/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004447/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004448bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004449 // Expect a single argument: an expression that evaluates to a constant
4450 // in the inclusive range 0-30.
4451 SMLoc ExprLoc = getLexer().getLoc();
4452 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004453 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004454 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4455 "in '.bundle_align_mode' "
4456 "directive") ||
4457 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4458 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004459 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004460
4461 // Because of AlignSizePow2's verified range we can safely truncate it to
4462 // unsigned.
4463 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4464 return false;
4465}
4466
Jim Grosbach4b905842013-09-20 23:08:21 +00004467/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004468/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004469bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004470 if (checkForValidSection())
4471 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004472 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004473
Nirav Dave1a9044b2016-10-24 14:35:29 +00004474 StringRef Option;
4475 SMLoc Loc = getTok().getLoc();
4476 const char *kInvalidOptionError =
4477 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004478
Nirav Dave1a9044b2016-10-24 14:35:29 +00004479 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004480 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4481 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004482 parseToken(AsmToken::EndOfStatement,
4483 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004484 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004485 AlignToEnd = true;
4486 }
4487
Eli Bendersky802b6282013-01-07 21:51:08 +00004488 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004489 return false;
4490}
4491
Jim Grosbach4b905842013-09-20 23:08:21 +00004492/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004493/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004494bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004495 if (checkForValidSection() ||
4496 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004497 "unexpected token in '.bundle_unlock' directive"))
4498 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004499
4500 getStreamer().EmitBundleUnlock();
4501 return false;
4502}
4503
Jim Grosbach4b905842013-09-20 23:08:21 +00004504/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004505/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004506bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Petr Hosek67a94a72016-05-28 05:57:48 +00004507 SMLoc NumBytesLoc = Lexer.getLoc();
4508 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004509 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004510 return true;
4511
4512 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004513 if (parseOptionalToken(AsmToken::Comma))
4514 if (parseAbsoluteExpression(FillExpr))
4515 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4516 if (parseToken(AsmToken::EndOfStatement))
4517 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004518
Eli Bendersky17233942013-01-15 22:59:42 +00004519 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004520 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004521
4522 return false;
4523}
4524
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004525/// parseDirectiveDCB
4526/// ::= .dcb.{b, l, w} expression, expression
4527bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004528 SMLoc NumValuesLoc = Lexer.getLoc();
4529 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004530 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004531 return true;
4532
4533 if (NumValues < 0) {
4534 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4535 return false;
4536 }
4537
4538 if (parseToken(AsmToken::Comma,
4539 "unexpected token in '" + Twine(IDVal) + "' directive"))
4540 return true;
4541
4542 const MCExpr *Value;
4543 SMLoc ExprLoc = getLexer().getLoc();
4544 if (parseExpression(Value))
4545 return true;
4546
4547 // Special case constant expressions to match code generator.
4548 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4549 assert(Size <= 8 && "Invalid size");
4550 uint64_t IntValue = MCE->getValue();
4551 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4552 return Error(ExprLoc, "literal value out of range for directive");
4553 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4554 getStreamer().EmitIntValue(IntValue, Size);
4555 } else {
4556 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4557 getStreamer().EmitValue(Value, Size, ExprLoc);
4558 }
4559
4560 if (parseToken(AsmToken::EndOfStatement,
4561 "unexpected token in '" + Twine(IDVal) + "' directive"))
4562 return true;
4563
4564 return false;
4565}
4566
4567/// parseDirectiveRealDCB
4568/// ::= .dcb.{d, s} expression, expression
4569bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004570 SMLoc NumValuesLoc = Lexer.getLoc();
4571 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004572 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004573 return true;
4574
4575 if (NumValues < 0) {
4576 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4577 return false;
4578 }
4579
4580 if (parseToken(AsmToken::Comma,
4581 "unexpected token in '" + Twine(IDVal) + "' directive"))
4582 return true;
4583
4584 APInt AsInt;
4585 if (parseRealValue(Semantics, AsInt))
4586 return true;
4587
4588 if (parseToken(AsmToken::EndOfStatement,
4589 "unexpected token in '" + Twine(IDVal) + "' directive"))
4590 return true;
4591
4592 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4593 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4594 AsInt.getBitWidth() / 8);
4595
4596 return false;
4597}
4598
Petr Hosek85b2f672016-09-23 21:53:36 +00004599/// parseDirectiveDS
4600/// ::= .ds.{b, d, l, p, s, w, x} expression
4601bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004602 SMLoc NumValuesLoc = Lexer.getLoc();
4603 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004604 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004605 return true;
4606
4607 if (NumValues < 0) {
4608 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4609 return false;
4610 }
4611
4612 if (parseToken(AsmToken::EndOfStatement,
4613 "unexpected token in '" + Twine(IDVal) + "' directive"))
4614 return true;
4615
4616 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4617 getStreamer().emitFill(Size, 0);
4618
4619 return false;
4620}
4621
Jim Grosbach4b905842013-09-20 23:08:21 +00004622/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004623/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004624bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004625 if (checkForValidSection())
4626 return true;
4627
Nirav Dave1a9044b2016-10-24 14:35:29 +00004628 auto parseOp = [&]() -> bool {
4629 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004630 if (parseExpression(Value))
4631 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004632 if (Signed)
4633 getStreamer().EmitSLEB128Value(Value);
4634 else
4635 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004636 return false;
4637 };
Eli Bendersky17233942013-01-15 22:59:42 +00004638
Nirav Dave1a9044b2016-10-24 14:35:29 +00004639 if (parseMany(parseOp))
4640 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004641
4642 return false;
4643}
4644
Jim Grosbach4b905842013-09-20 23:08:21 +00004645/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004646/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004647bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004648 auto parseOp = [&]() -> bool {
4649 StringRef Name;
4650 SMLoc Loc = getTok().getLoc();
4651 if (parseIdentifier(Name))
4652 return Error(Loc, "expected identifier");
4653 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004654
Nirav Dave1a9044b2016-10-24 14:35:29 +00004655 // Assembler local symbols don't make any sense here. Complain loudly.
4656 if (Sym->isTemporary())
4657 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004658
Nirav Dave1a9044b2016-10-24 14:35:29 +00004659 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4660 return Error(Loc, "unable to emit symbol attribute");
4661 return false;
4662 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004663
Nirav Dave1a9044b2016-10-24 14:35:29 +00004664 if (parseMany(parseOp))
4665 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004666 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004667}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004668
Jim Grosbach4b905842013-09-20 23:08:21 +00004669/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004670/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004671bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004672 if (checkForValidSection())
4673 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004674
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004675 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004676 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004677 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004678 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004679
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004680 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004681 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004682
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004683 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004684 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004685 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004686
4687 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004688 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004689 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004690 return true;
4691
4692 int64_t Pow2Alignment = 0;
4693 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004694 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004695 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004696 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004697 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004698 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004699
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004700 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4701 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004702 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4703
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004704 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004705 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4706 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004707 if (!isPowerOf2_64(Pow2Alignment))
4708 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4709 Pow2Alignment = Log2_64(Pow2Alignment);
4710 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004711 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004712
Nirav Dave1a9044b2016-10-24 14:35:29 +00004713 if (parseToken(AsmToken::EndOfStatement,
4714 "unexpected token in '.comm' or '.lcomm' directive"))
4715 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004716
Chris Lattner28ad7542009-07-09 17:25:12 +00004717 // NOTE: a size of zero for a .comm should create a undefined symbol
4718 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004719 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004720 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004721 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004722
Eric Christopherbc818852010-05-14 01:38:54 +00004723 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004724 // may internally end up wanting an alignment in bytes.
4725 // FIXME: Diagnose overflow.
4726 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004727 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004728 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004729
Rafael Espindola13a79bb2017-02-02 21:26:06 +00004730 Sym->redefineIfPossible();
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004731 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004732 return Error(IDLoc, "invalid symbol redefinition");
4733
Chris Lattner28ad7542009-07-09 17:25:12 +00004734 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004735 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004736 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004737 return false;
4738 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004739
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004740 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004741 return false;
4742}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004743
Jim Grosbach4b905842013-09-20 23:08:21 +00004744/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004745/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004746bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004747 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004748 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004749
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004750 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004751 if (parseToken(AsmToken::EndOfStatement,
4752 "unexpected token in '.abort' directive"))
4753 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004754
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004755 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004756 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004757 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004758 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004759 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004760
4761 return false;
4762}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004763
Jim Grosbach4b905842013-09-20 23:08:21 +00004764/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004765/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004766bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004767 // Allow the strings to have escaped octal character sequence.
4768 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004769 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004770
Nirav Davea645433c2016-07-18 15:24:03 +00004771 if (check(getTok().isNot(AsmToken::String),
4772 "expected string in '.include' directive") ||
4773 parseEscapedString(Filename) ||
4774 check(getTok().isNot(AsmToken::EndOfStatement),
4775 "unexpected token in '.include' directive") ||
4776 // Attempt to switch the lexer to the included file before consuming the
4777 // end of statement to avoid losing it when we switch.
4778 check(enterIncludeFile(Filename), IncludeLoc,
4779 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004780 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004781
4782 return false;
4783}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004784
Jim Grosbach4b905842013-09-20 23:08:21 +00004785/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004786/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004787bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004788 // Allow the strings to have escaped octal character sequence.
4789 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004790 SMLoc IncbinLoc = getTok().getLoc();
4791 if (check(getTok().isNot(AsmToken::String),
4792 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00004793 parseEscapedString(Filename))
4794 return true;
4795
4796 int64_t Skip = 0;
4797 const MCExpr *Count = nullptr;
4798 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004799 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00004800 // The skip expression can be omitted while specifying the count, e.g:
4801 // .incbin "filename",,4
4802 if (getTok().isNot(AsmToken::Comma)) {
4803 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4804 return true;
4805 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00004806 if (parseOptionalToken(AsmToken::Comma)) {
4807 CountLoc = getTok().getLoc();
4808 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00004809 return true;
4810 }
4811 }
4812
4813 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004814 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004815 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004816
Petr Hosek2f4ac442016-09-23 00:41:06 +00004817 if (check(Skip < 0, SkipLoc, "skip is negative"))
4818 return true;
4819
Nirav Dave1ab71992016-07-18 19:35:21 +00004820 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00004821 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00004822 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004823 return false;
4824}
4825
Jim Grosbach4b905842013-09-20 23:08:21 +00004826/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004827/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4828bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004829 TheCondStack.push_back(TheCondState);
4830 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004831 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004832 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004833 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004834 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004835 if (parseAbsoluteExpression(ExprValue) ||
4836 parseToken(AsmToken::EndOfStatement,
4837 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004838 return true;
4839
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004840 switch (DirKind) {
4841 default:
4842 llvm_unreachable("unsupported directive");
4843 case DK_IF:
4844 case DK_IFNE:
4845 break;
4846 case DK_IFEQ:
4847 ExprValue = ExprValue == 0;
4848 break;
4849 case DK_IFGE:
4850 ExprValue = ExprValue >= 0;
4851 break;
4852 case DK_IFGT:
4853 ExprValue = ExprValue > 0;
4854 break;
4855 case DK_IFLE:
4856 ExprValue = ExprValue <= 0;
4857 break;
4858 case DK_IFLT:
4859 ExprValue = ExprValue < 0;
4860 break;
4861 }
4862
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004863 TheCondState.CondMet = ExprValue;
4864 TheCondState.Ignore = !TheCondState.CondMet;
4865 }
4866
4867 return false;
4868}
4869
Jim Grosbach4b905842013-09-20 23:08:21 +00004870/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004871/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004872bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004873 TheCondStack.push_back(TheCondState);
4874 TheCondState.TheCond = AsmCond::IfCond;
4875
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004876 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004877 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004878 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004879 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004880
Nirav Davea645433c2016-07-18 15:24:03 +00004881 if (parseToken(AsmToken::EndOfStatement,
4882 "unexpected token in '.ifb' directive"))
4883 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004884
4885 TheCondState.CondMet = ExpectBlank == Str.empty();
4886 TheCondState.Ignore = !TheCondState.CondMet;
4887 }
4888
4889 return false;
4890}
4891
Jim Grosbach4b905842013-09-20 23:08:21 +00004892/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004893/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004894/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004895bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004896 TheCondStack.push_back(TheCondState);
4897 TheCondState.TheCond = AsmCond::IfCond;
4898
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004899 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004900 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004901 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004902 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004903
Nirav Davea645433c2016-07-18 15:24:03 +00004904 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4905 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004906
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004907 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004908
Nirav Davea645433c2016-07-18 15:24:03 +00004909 if (parseToken(AsmToken::EndOfStatement,
4910 "unexpected token in '.ifc' directive"))
4911 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004912
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004913 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004914 TheCondState.Ignore = !TheCondState.CondMet;
4915 }
4916
4917 return false;
4918}
4919
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004920/// parseDirectiveIfeqs
4921/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004922bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004923 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004924 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004925 return TokError("expected string parameter for '.ifeqs' directive");
4926 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004927 }
4928
4929 StringRef String1 = getTok().getStringContents();
4930 Lex();
4931
4932 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004933 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004934 return TokError(
4935 "expected comma after first string for '.ifeqs' directive");
4936 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004937 }
4938
4939 Lex();
4940
4941 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004942 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004943 return TokError("expected string parameter for '.ifeqs' directive");
4944 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004945 }
4946
4947 StringRef String2 = getTok().getStringContents();
4948 Lex();
4949
4950 TheCondStack.push_back(TheCondState);
4951 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004952 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004953 TheCondState.Ignore = !TheCondState.CondMet;
4954
4955 return false;
4956}
4957
Jim Grosbach4b905842013-09-20 23:08:21 +00004958/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004959/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004960bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004961 StringRef Name;
4962 TheCondStack.push_back(TheCondState);
4963 TheCondState.TheCond = AsmCond::IfCond;
4964
4965 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004966 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004967 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00004968 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4969 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4970 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004971
Jim Grosbach6f482002015-05-18 18:43:14 +00004972 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004973
4974 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004975 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004976 else
Craig Topper353eda42014-04-24 06:44:33 +00004977 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004978 TheCondState.Ignore = !TheCondState.CondMet;
4979 }
4980
4981 return false;
4982}
4983
Jim Grosbach4b905842013-09-20 23:08:21 +00004984/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004985/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004986bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004987 if (TheCondState.TheCond != AsmCond::IfCond &&
4988 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004989 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
4990 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004991 TheCondState.TheCond = AsmCond::ElseIfCond;
4992
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004993 bool LastIgnoreState = false;
4994 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004995 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004996 if (LastIgnoreState || TheCondState.CondMet) {
4997 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004998 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004999 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005000 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005001 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005002 return true;
5003
Nirav Dave1a9044b2016-10-24 14:35:29 +00005004 if (parseToken(AsmToken::EndOfStatement,
5005 "unexpected token in '.elseif' directive"))
5006 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00005007
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005008 TheCondState.CondMet = ExprValue;
5009 TheCondState.Ignore = !TheCondState.CondMet;
5010 }
5011
5012 return false;
5013}
5014
Jim Grosbach4b905842013-09-20 23:08:21 +00005015/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005016/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00005017bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005018 if (parseToken(AsmToken::EndOfStatement,
5019 "unexpected token in '.else' directive"))
5020 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005021
5022 if (TheCondState.TheCond != AsmCond::IfCond &&
5023 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00005024 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
5025 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005026 TheCondState.TheCond = AsmCond::ElseCond;
5027 bool LastIgnoreState = false;
5028 if (!TheCondStack.empty())
5029 LastIgnoreState = TheCondStack.back().Ignore;
5030 if (LastIgnoreState || TheCondState.CondMet)
5031 TheCondState.Ignore = true;
5032 else
5033 TheCondState.Ignore = false;
5034
5035 return false;
5036}
5037
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005038/// parseDirectiveEnd
5039/// ::= .end
5040bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005041 if (parseToken(AsmToken::EndOfStatement,
5042 "unexpected token in '.end' directive"))
5043 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005044
5045 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00005046 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005047
5048 return false;
5049}
5050
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005051/// parseDirectiveError
5052/// ::= .err
5053/// ::= .error [string]
5054bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
5055 if (!TheCondStack.empty()) {
5056 if (TheCondStack.back().Ignore) {
5057 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005058 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005059 }
5060 }
5061
5062 if (!WithMessage)
5063 return Error(L, ".err encountered");
5064
5065 StringRef Message = ".error directive invoked in source file";
5066 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005067 if (Lexer.isNot(AsmToken::String))
5068 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005069
5070 Message = getTok().getStringContents();
5071 Lex();
5072 }
5073
Nirav Dave2364748a2016-09-16 18:30:20 +00005074 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005075}
5076
Nico Weber404012b2014-07-24 16:26:06 +00005077/// parseDirectiveWarning
5078/// ::= .warning [string]
5079bool AsmParser::parseDirectiveWarning(SMLoc L) {
5080 if (!TheCondStack.empty()) {
5081 if (TheCondStack.back().Ignore) {
5082 eatToEndOfStatement();
5083 return false;
5084 }
5085 }
5086
5087 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00005088
5089 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005090 if (Lexer.isNot(AsmToken::String))
5091 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00005092
5093 Message = getTok().getStringContents();
5094 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00005095 if (parseToken(AsmToken::EndOfStatement,
5096 "expected end of statement in '.warning' directive"))
5097 return true;
Nico Weber404012b2014-07-24 16:26:06 +00005098 }
5099
Nirav Dave2364748a2016-09-16 18:30:20 +00005100 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00005101}
5102
Jim Grosbach4b905842013-09-20 23:08:21 +00005103/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005104/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00005105bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005106 if (parseToken(AsmToken::EndOfStatement,
5107 "unexpected token in '.endif' directive"))
5108 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005109
Jim Grosbach4b905842013-09-20 23:08:21 +00005110 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00005111 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
5112 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005113 if (!TheCondStack.empty()) {
5114 TheCondState = TheCondStack.back();
5115 TheCondStack.pop_back();
5116 }
5117
5118 return false;
5119}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00005120
Eli Bendersky17233942013-01-15 22:59:42 +00005121void AsmParser::initializeDirectiveKindMap() {
5122 DirectiveKindMap[".set"] = DK_SET;
5123 DirectiveKindMap[".equ"] = DK_EQU;
5124 DirectiveKindMap[".equiv"] = DK_EQUIV;
5125 DirectiveKindMap[".ascii"] = DK_ASCII;
5126 DirectiveKindMap[".asciz"] = DK_ASCIZ;
5127 DirectiveKindMap[".string"] = DK_STRING;
5128 DirectiveKindMap[".byte"] = DK_BYTE;
5129 DirectiveKindMap[".short"] = DK_SHORT;
5130 DirectiveKindMap[".value"] = DK_VALUE;
5131 DirectiveKindMap[".2byte"] = DK_2BYTE;
5132 DirectiveKindMap[".long"] = DK_LONG;
5133 DirectiveKindMap[".int"] = DK_INT;
5134 DirectiveKindMap[".4byte"] = DK_4BYTE;
5135 DirectiveKindMap[".quad"] = DK_QUAD;
5136 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00005137 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00005138 DirectiveKindMap[".single"] = DK_SINGLE;
5139 DirectiveKindMap[".float"] = DK_FLOAT;
5140 DirectiveKindMap[".double"] = DK_DOUBLE;
5141 DirectiveKindMap[".align"] = DK_ALIGN;
5142 DirectiveKindMap[".align32"] = DK_ALIGN32;
5143 DirectiveKindMap[".balign"] = DK_BALIGN;
5144 DirectiveKindMap[".balignw"] = DK_BALIGNW;
5145 DirectiveKindMap[".balignl"] = DK_BALIGNL;
5146 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
5147 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
5148 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
5149 DirectiveKindMap[".org"] = DK_ORG;
5150 DirectiveKindMap[".fill"] = DK_FILL;
5151 DirectiveKindMap[".zero"] = DK_ZERO;
5152 DirectiveKindMap[".extern"] = DK_EXTERN;
5153 DirectiveKindMap[".globl"] = DK_GLOBL;
5154 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00005155 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
5156 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
5157 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
5158 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
5159 DirectiveKindMap[".reference"] = DK_REFERENCE;
5160 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
5161 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
5162 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
5163 DirectiveKindMap[".comm"] = DK_COMM;
5164 DirectiveKindMap[".common"] = DK_COMMON;
5165 DirectiveKindMap[".lcomm"] = DK_LCOMM;
5166 DirectiveKindMap[".abort"] = DK_ABORT;
5167 DirectiveKindMap[".include"] = DK_INCLUDE;
5168 DirectiveKindMap[".incbin"] = DK_INCBIN;
5169 DirectiveKindMap[".code16"] = DK_CODE16;
5170 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
5171 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005172 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00005173 DirectiveKindMap[".irp"] = DK_IRP;
5174 DirectiveKindMap[".irpc"] = DK_IRPC;
5175 DirectiveKindMap[".endr"] = DK_ENDR;
5176 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
5177 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
5178 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
5179 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00005180 DirectiveKindMap[".ifeq"] = DK_IFEQ;
5181 DirectiveKindMap[".ifge"] = DK_IFGE;
5182 DirectiveKindMap[".ifgt"] = DK_IFGT;
5183 DirectiveKindMap[".ifle"] = DK_IFLE;
5184 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00005185 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00005186 DirectiveKindMap[".ifb"] = DK_IFB;
5187 DirectiveKindMap[".ifnb"] = DK_IFNB;
5188 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005189 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00005190 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00005191 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00005192 DirectiveKindMap[".ifdef"] = DK_IFDEF;
5193 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
5194 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
5195 DirectiveKindMap[".elseif"] = DK_ELSEIF;
5196 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005197 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00005198 DirectiveKindMap[".endif"] = DK_ENDIF;
5199 DirectiveKindMap[".skip"] = DK_SKIP;
5200 DirectiveKindMap[".space"] = DK_SPACE;
5201 DirectiveKindMap[".file"] = DK_FILE;
5202 DirectiveKindMap[".line"] = DK_LINE;
5203 DirectiveKindMap[".loc"] = DK_LOC;
5204 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005205 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005206 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005207 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
5208 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00005209 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005210 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00005211 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005212 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
5213 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00005214 DirectiveKindMap[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET;
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00005215 DirectiveKindMap[".cv_fpo_data"] = DK_CV_FPO_DATA;
Eli Bendersky17233942013-01-15 22:59:42 +00005216 DirectiveKindMap[".sleb128"] = DK_SLEB128;
5217 DirectiveKindMap[".uleb128"] = DK_ULEB128;
5218 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
5219 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
5220 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
5221 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
5222 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
5223 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
5224 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
5225 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
5226 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
5227 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
5228 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
5229 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
5230 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
5231 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
5232 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
5233 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00005234 DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN;
Eli Bendersky17233942013-01-15 22:59:42 +00005235 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
5236 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
5237 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00005238 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00005239 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
5240 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
5241 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00005242 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00005243 DirectiveKindMap[".endm"] = DK_ENDM;
5244 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
5245 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005246 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005247 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00005248 DirectiveKindMap[".warning"] = DK_WARNING;
Michael Zuckerman56704612017-05-01 13:20:12 +00005249 DirectiveKindMap[".altmacro"] = DK_ALTMACRO;
5250 DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00005251 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00005252 DirectiveKindMap[".dc"] = DK_DC;
5253 DirectiveKindMap[".dc.a"] = DK_DC_A;
5254 DirectiveKindMap[".dc.b"] = DK_DC_B;
5255 DirectiveKindMap[".dc.d"] = DK_DC_D;
5256 DirectiveKindMap[".dc.l"] = DK_DC_L;
5257 DirectiveKindMap[".dc.s"] = DK_DC_S;
5258 DirectiveKindMap[".dc.w"] = DK_DC_W;
5259 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00005260 DirectiveKindMap[".dcb"] = DK_DCB;
5261 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
5262 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
5263 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
5264 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
5265 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
5266 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00005267 DirectiveKindMap[".ds"] = DK_DS;
5268 DirectiveKindMap[".ds.b"] = DK_DS_B;
5269 DirectiveKindMap[".ds.d"] = DK_DS_D;
5270 DirectiveKindMap[".ds.l"] = DK_DS_L;
5271 DirectiveKindMap[".ds.p"] = DK_DS_P;
5272 DirectiveKindMap[".ds.s"] = DK_DS_S;
5273 DirectiveKindMap[".ds.w"] = DK_DS_W;
5274 DirectiveKindMap[".ds.x"] = DK_DS_X;
Coby Tayree01e53202017-10-02 14:36:31 +00005275 DirectiveKindMap[".print"] = DK_PRINT;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00005276}
5277
Jim Grosbach4b905842013-09-20 23:08:21 +00005278MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005279 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005280
Rafael Espindola34b9c512012-06-03 23:57:14 +00005281 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005282 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005283 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00005284 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005285 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00005286 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005287 }
5288
Rafael Espindola34b9c512012-06-03 23:57:14 +00005289 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00005290 (getTok().getIdentifier() == ".rept" ||
5291 getTok().getIdentifier() == ".irp" ||
5292 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005293 ++NestLevel;
5294 }
5295
5296 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00005297 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005298 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005299 EndToken = getTok();
5300 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005301 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005302 printError(getTok().getLoc(),
5303 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00005304 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005305 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005306 break;
5307 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005308 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005309 }
5310
Rafael Espindola34b9c512012-06-03 23:57:14 +00005311 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005312 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005313 }
5314
5315 const char *BodyStart = StartToken.getLoc().getPointer();
5316 const char *BodyEnd = EndToken.getLoc().getPointer();
5317 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5318
Rafael Espindola34b9c512012-06-03 23:57:14 +00005319 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005320 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00005321 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005322}
5323
Jim Grosbach4b905842013-09-20 23:08:21 +00005324void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005325 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005326 OS << ".endr\n";
5327
Rafael Espindola3560ff22014-08-27 20:03:13 +00005328 std::unique_ptr<MemoryBuffer> Instantiation =
5329 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005330
Rafael Espindola34b9c512012-06-03 23:57:14 +00005331 // Create the macro instantiation object and add to the current macro
5332 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005333 MacroInstantiation *MI = new MacroInstantiation(
5334 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005335 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005336
Rafael Espindola34b9c512012-06-03 23:57:14 +00005337 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005338 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005339 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005340 Lex();
5341}
5342
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005343/// parseDirectiveRept
5344/// ::= .rep | .rept count
5345bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005346 const MCExpr *CountExpr;
5347 SMLoc CountLoc = getTok().getLoc();
5348 if (parseExpression(CountExpr))
5349 return true;
5350
Rafael Espindola34b9c512012-06-03 23:57:14 +00005351 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00005352 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005353 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5354 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005355
Nirav Davea645433c2016-07-18 15:24:03 +00005356 if (check(Count < 0, CountLoc, "Count is negative") ||
5357 parseToken(AsmToken::EndOfStatement,
5358 "unexpected token in '" + Dir + "' directive"))
5359 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005360
5361 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005362 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005363 if (!M)
5364 return true;
5365
5366 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5367 // to hold the macro body with substitutions.
5368 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005369 raw_svector_ostream OS(Buf);
5370 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005371 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5372 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005373 return true;
5374 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005375 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005376
5377 return false;
5378}
5379
Jim Grosbach4b905842013-09-20 23:08:21 +00005380/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005381/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005382bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005383 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005384 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005385 if (check(parseIdentifier(Parameter.Name),
5386 "expected identifier in '.irp' directive") ||
5387 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5388 parseMacroArguments(nullptr, A) ||
5389 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005390 return true;
5391
Rafael Espindola768b41c2012-06-15 14:02:34 +00005392 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005393 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +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
Craig Topper84008482015-10-10 05:38:14 +00005402 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005403 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5404 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005405 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005406 return true;
5407 }
5408
Jim Grosbach4b905842013-09-20 23:08:21 +00005409 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005410
5411 return false;
5412}
5413
Jim Grosbach4b905842013-09-20 23:08:21 +00005414/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005415/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005416bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005417 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005418 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005419
5420 if (check(parseIdentifier(Parameter.Name),
5421 "expected identifier in '.irpc' directive") ||
5422 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5423 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005424 return true;
5425
5426 if (A.size() != 1 || A.front().size() != 1)
5427 return TokError("unexpected token in '.irpc' directive");
5428
5429 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005430 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5431 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005432
5433 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005434 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005435 if (!M)
5436 return true;
5437
5438 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5439 // to hold the macro body with substitutions.
5440 SmallString<256> Buf;
5441 raw_svector_ostream OS(Buf);
5442
5443 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005444 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005445 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005446 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005447
Toma Tabacu217116e2015-04-27 10:50:29 +00005448 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5449 // This is undocumented, but GAS seems to support it.
5450 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005451 return true;
5452 }
5453
Jim Grosbach4b905842013-09-20 23:08:21 +00005454 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005455
5456 return false;
5457}
5458
Jim Grosbach4b905842013-09-20 23:08:21 +00005459bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005460 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005461 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005462
5463 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005464 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005465 assert(getLexer().is(AsmToken::EndOfStatement));
5466
Jim Grosbach4b905842013-09-20 23:08:21 +00005467 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005468 return false;
5469}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005470
Jim Grosbach4b905842013-09-20 23:08:21 +00005471bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005472 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005473 const MCExpr *Value;
5474 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005475 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005476 return true;
5477 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5478 if (!MCE)
5479 return Error(ExprLoc, "unexpected expression in _emit");
5480 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005481 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005482 return Error(ExprLoc, "literal value out of range for directive");
5483
Craig Topper7d5b2312015-10-10 05:25:02 +00005484 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005485 return false;
5486}
5487
Jim Grosbach4b905842013-09-20 23:08:21 +00005488bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005489 const MCExpr *Value;
5490 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005491 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005492 return true;
5493 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5494 if (!MCE)
5495 return Error(ExprLoc, "unexpected expression in align");
5496 uint64_t IntValue = MCE->getValue();
5497 if (!isPowerOf2_64(IntValue))
5498 return Error(ExprLoc, "literal value not a power of two greater then zero");
5499
Craig Topper7d5b2312015-10-10 05:25:02 +00005500 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005501 return false;
5502}
5503
Coby Tayree01e53202017-10-02 14:36:31 +00005504bool AsmParser::parseDirectivePrint(SMLoc DirectiveLoc) {
5505 const AsmToken StrTok = getTok();
5506 Lex();
5507 if (StrTok.isNot(AsmToken::String) || StrTok.getString().front() != '"')
5508 return Error(DirectiveLoc, "expected double quoted string after .print");
5509 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5510 return true;
5511 llvm::outs() << StrTok.getStringContents() << '\n';
5512 return false;
5513}
5514
Chad Rosierf43fcf52013-02-13 21:27:17 +00005515// We are comparing pointers, but the pointers are relative to a single string.
5516// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005517static int rewritesSort(const AsmRewrite *AsmRewriteA,
5518 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005519 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5520 return -1;
5521 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5522 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005523
Chad Rosierfce4fab2013-04-08 17:43:47 +00005524 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5525 // rewrite to the same location. Make sure the SizeDirective rewrite is
5526 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5527 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005528 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5529 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005530 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005531
Jim Grosbach4b905842013-09-20 23:08:21 +00005532 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5533 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005534 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005535 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005536}
5537
Jim Grosbach4b905842013-09-20 23:08:21 +00005538bool AsmParser::parseMSInlineAsm(
5539 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00005540 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
Jim Grosbach4b905842013-09-20 23:08:21 +00005541 SmallVectorImpl<std::string> &Constraints,
5542 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5543 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005544 SmallVector<void *, 4> InputDecls;
5545 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005546 SmallVector<bool, 4> InputDeclsAddressOf;
5547 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005548 SmallVector<std::string, 4> InputConstraints;
5549 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005550 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005551
Benjamin Kramer1a136112013-02-15 20:37:21 +00005552 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005553
5554 // Prime the lexer.
5555 Lex();
5556
5557 // While we have input, parse each statement.
5558 unsigned InputIdx = 0;
5559 unsigned OutputIdx = 0;
5560 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005561 // Parse curly braces marking block start/end
5562 if (parseCurlyBlockScope(AsmStrRewrites))
5563 continue;
5564
Eli Friedman0f4871d2012-10-22 23:58:19 +00005565 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005566 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005567
Nirav Dave2364748a2016-09-16 18:30:20 +00005568 if (StatementErr || Info.ParseError) {
5569 // Emit pending errors if any exist.
5570 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005571 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005572 }
5573
5574 // No pending error should exist here.
5575 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005576
Benjamin Kramer1a136112013-02-15 20:37:21 +00005577 if (Info.Opcode == ~0U)
5578 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005579
Benjamin Kramer1a136112013-02-15 20:37:21 +00005580 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005581
Benjamin Kramer1a136112013-02-15 20:37:21 +00005582 // Build the list of clobbers, outputs and inputs.
5583 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005584 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005585
Benjamin Kramer1a136112013-02-15 20:37:21 +00005586 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005587 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005588 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005589
Benjamin Kramer1a136112013-02-15 20:37:21 +00005590 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005591 if (Operand.isReg() && !Operand.needAddressOf() &&
5592 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005593 unsigned NumDefs = Desc.getNumDefs();
5594 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005595 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5596 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005597 continue;
5598 }
5599
5600 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005601 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005602 if (SymName.empty())
5603 continue;
5604
David Blaikie960ea3f2014-06-08 16:18:35 +00005605 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005606 if (!OpDecl)
5607 continue;
5608
5609 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005610 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005611 if (isOutput) {
5612 ++InputIdx;
5613 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005614 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005615 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005616 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005617 } else {
5618 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005619 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5620 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005621 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005622 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005623 }
Reid Kleckneree088972013-12-10 18:27:32 +00005624
5625 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005626 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5627 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005628 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005629 }
5630
5631 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005632 NumOutputs = OutputDecls.size();
5633 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005634
5635 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005636 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5637 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5638 ClobberRegs.end());
5639 Clobbers.assign(ClobberRegs.size(), std::string());
5640 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5641 raw_string_ostream OS(Clobbers[I]);
5642 IP->printRegName(OS, ClobberRegs[I]);
5643 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005644
5645 // Merge the various outputs and inputs. Output are expected first.
5646 if (NumOutputs || NumInputs) {
5647 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005648 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005649 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005650 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005651 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005652 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005653 }
5654 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005655 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005656 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005657 }
5658 }
5659
5660 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005661 std::string AsmStringIR;
5662 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005663 StringRef ASMString =
5664 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5665 const char *AsmStart = ASMString.begin();
5666 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005667 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005668 for (const AsmRewrite &AR : AsmStrRewrites) {
5669 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005670
David Majnemer8114c1a2014-06-23 02:17:16 +00005671 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005672 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005673
Chad Rosier120eefd2013-03-19 17:32:17 +00005674 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005675 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005676 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005677
Chad Rosier37e755c2012-10-23 17:43:43 +00005678 // Skip the original expression.
5679 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005680 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005681 continue;
5682 }
5683
Chad Rosierff10ed12013-04-12 16:26:42 +00005684 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005685 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005686 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005687 default:
5688 break;
Coby Tayreed8912892017-08-24 08:46:25 +00005689 case AOK_IntelExpr:
5690 assert(AR.IntelExp.isValid() && "cannot write invalid intel expression");
5691 if (AR.IntelExp.NeedBracs)
5692 OS << "[";
5693 if (AR.IntelExp.hasBaseReg())
5694 OS << AR.IntelExp.BaseReg;
5695 if (AR.IntelExp.hasIndexReg())
5696 OS << (AR.IntelExp.hasBaseReg() ? " + " : "")
5697 << AR.IntelExp.IndexReg;
5698 if (AR.IntelExp.Scale > 1)
5699 OS << " * $$" << AR.IntelExp.Scale;
5700 if (AR.IntelExp.Imm || !AR.IntelExp.hasRegs())
5701 OS << (AR.IntelExp.hasRegs() ? " + $$" : "$$") << AR.IntelExp.Imm;
5702 if (AR.IntelExp.NeedBracs)
5703 OS << "]";
Chad Rosier8bce6642012-10-18 15:49:34 +00005704 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005705 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005706 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005707 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005708 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005709 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005710 break;
5711 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005712 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005713 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005714 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005715 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005716 default: break;
5717 case 8: OS << "byte ptr "; break;
5718 case 16: OS << "word ptr "; break;
5719 case 32: OS << "dword ptr "; break;
5720 case 64: OS << "qword ptr "; break;
5721 case 80: OS << "xword ptr "; break;
5722 case 128: OS << "xmmword ptr "; break;
5723 case 256: OS << "ymmword ptr "; break;
5724 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005725 break;
5726 case AOK_Emit:
5727 OS << ".byte";
5728 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005729 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005730 // MS alignment directives are measured in bytes. If the native assembler
5731 // measures alignment in bytes, we can pass it straight through.
5732 OS << ".align";
5733 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5734 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005735
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005736 // Alignment is in log2 form, so print that instead and skip the original
5737 // immediate.
5738 unsigned Val = AR.Val;
5739 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005740 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005741 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5742 break;
5743 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005744 case AOK_EVEN:
5745 OS << ".even";
5746 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005747 case AOK_EndOfStatement:
5748 OS << "\n\t";
5749 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005750 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005751
Chad Rosier8bce6642012-10-18 15:49:34 +00005752 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005753 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005754 }
5755
5756 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005757 if (AsmStart != AsmEnd)
5758 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005759
5760 AsmString = OS.str();
5761 return false;
5762}
5763
Pete Cooper80d21cb2015-06-22 19:35:57 +00005764namespace llvm {
5765namespace MCParserUtils {
5766
5767/// Returns whether the given symbol is used anywhere in the given expression,
5768/// or subexpressions.
5769static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5770 switch (Value->getKind()) {
5771 case MCExpr::Binary: {
5772 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5773 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5774 isSymbolUsedInExpression(Sym, BE->getRHS());
5775 }
5776 case MCExpr::Target:
5777 case MCExpr::Constant:
5778 return false;
5779 case MCExpr::SymbolRef: {
5780 const MCSymbol &S =
5781 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5782 if (S.isVariable())
5783 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5784 return &S == Sym;
5785 }
5786 case MCExpr::Unary:
5787 return isSymbolUsedInExpression(
5788 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5789 }
5790
5791 llvm_unreachable("Unknown expr kind!");
5792}
5793
5794bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5795 MCAsmParser &Parser, MCSymbol *&Sym,
5796 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005797
5798 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005799 SMLoc EqualLoc = Parser.getTok().getLoc();
Pete Cooper80d21cb2015-06-22 19:35:57 +00005800
5801 if (Parser.parseExpression(Value)) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00005802 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005803 }
5804
5805 // Note: we don't count b as used in "a = b". This is to allow
5806 // a = b
5807 // b = c
5808
Nirav Dave1a9044b2016-10-24 14:35:29 +00005809 if (Parser.parseToken(AsmToken::EndOfStatement))
5810 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00005811
5812 // Validate that the LHS is allowed to be a variable (either it has not been
5813 // used as a symbol, or it is an absolute symbol).
5814 Sym = Parser.getContext().lookupSymbol(Name);
5815 if (Sym) {
5816 // Diagnose assignment to a label.
5817 //
5818 // FIXME: Diagnostics. Note the location of the definition as a label.
5819 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5820 if (isSymbolUsedInExpression(Sym, Value))
5821 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005822 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5823 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005824 ; // Allow redefinitions of undefined symbols only used in directives.
5825 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5826 ; // Allow redefinitions of variables that haven't yet been used.
5827 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5828 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5829 else if (!Sym->isVariable())
5830 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5831 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5832 return Parser.Error(EqualLoc,
5833 "invalid reassignment of non-absolute variable '" +
5834 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005835 } else if (Name == ".") {
Oliver Stannard268f42f2016-12-14 10:43:58 +00005836 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005837 return false;
5838 } else
5839 Sym = Parser.getContext().getOrCreateSymbol(Name);
5840
5841 Sym->setRedefinable(allow_redef);
5842
5843 return false;
5844}
5845
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005846} // end namespace MCParserUtils
5847} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005848
Daniel Dunbar01e36072010-07-17 02:26:10 +00005849/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005850MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
Sanne Wouda29338752017-02-08 14:48:05 +00005851 MCStreamer &Out, const MCAsmInfo &MAI,
5852 unsigned CB) {
5853 return new AsmParser(SM, C, Out, MAI, CB);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005854}