blob: 69720135432e8d494542f64c274b19142ab9d21f [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
Devang Patela173ee52012-01-31 18:14:05 +0000171 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000172 unsigned AssemblerDialect = ~0U;
Devang Patela173ee52012-01-31 18:14:05 +0000173
Jim Grosbach4b905842013-09-20 23:08:21 +0000174 /// \brief is Darwin compatibility enabled?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000175 bool IsDarwin = false;
Preston Gurd05500642012-09-19 20:36:12 +0000176
Jim Grosbach4b905842013-09-20 23:08:21 +0000177 /// \brief Are we parsing ms-style inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000178 bool ParsingInlineAsm = false;
Chad Rosier49963552012-10-13 00:26:04 +0000179
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000180public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000181 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000182 const MCAsmInfo &MAI, unsigned CB);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000183 AsmParser(const AsmParser &) = delete;
184 AsmParser &operator=(const AsmParser &) = delete;
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000185 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000186
Craig Topper59be68f2014-03-08 07:14:16 +0000187 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000188
Craig Topper59be68f2014-03-08 07:14:16 +0000189 void addDirectiveHandler(StringRef Directive,
190 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000191 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000192 }
193
Toma Tabacu11e14a92015-04-21 11:50:52 +0000194 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
195 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
196 }
197
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000198 /// @name MCAsmParser Interface
199 /// {
200
Craig Topper59be68f2014-03-08 07:14:16 +0000201 SourceMgr &getSourceManager() override { return SrcMgr; }
202 MCAsmLexer &getLexer() override { return Lexer; }
203 MCContext &getContext() override { return Ctx; }
204 MCStreamer &getStreamer() override { return Out; }
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000205
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000206 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
207
Craig Topper59be68f2014-03-08 07:14:16 +0000208 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000209 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000210 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000211 else
212 return AssemblerDialect;
213 }
Craig Topper59be68f2014-03-08 07:14:16 +0000214 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000215 AssemblerDialect = i;
216 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000217
Nirav Dave2364748a2016-09-16 18:30:20 +0000218 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
219 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
220 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000221
Craig Topper59be68f2014-03-08 07:14:16 +0000222 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000223
Yunzhong Gao27ea29b2016-09-02 23:15:29 +0000224 void setParsingInlineAsm(bool V) override {
225 ParsingInlineAsm = V;
226 Lexer.setParsingMSInlineAsm(V);
227 }
Craig Topper59be68f2014-03-08 07:14:16 +0000228 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000229
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000230 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000231 unsigned &NumOutputs, unsigned &NumInputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000232 SmallVectorImpl<std::pair<void *,bool>> &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000233 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000234 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000235 const MCInstrInfo *MII, const MCInstPrinter *IP,
236 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000237
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000238 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000239 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
240 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
241 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000242 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
243 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000244 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000245
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000246 /// \brief Parse a floating point expression using the float \p Semantics
247 /// and set \p Res to the value.
248 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
249
Jim Grosbach4b905842013-09-20 23:08:21 +0000250 /// \brief Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000251 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000252 bool parseIdentifier(StringRef &Res) override;
253 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000254
Nirav Davef43cc9f2016-10-10 15:24:54 +0000255 bool checkForValidSection() override;
Nirav Davea645433c2016-07-18 15:24:03 +0000256
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000257 /// }
258
259private:
Michael Zuckerman763e60e2017-05-04 10:37:00 +0000260 bool isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc);
Michael Zuckerman1f1a9122017-05-10 13:08:11 +0000261 void altMacroString(StringRef AltMacroStr, std::string &Res);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000262 bool parseStatement(ParseStatementInfo &Info,
263 MCAsmParserSemaCallback *SI);
Marina Yatsina5f5de9f2016-03-07 18:11:16 +0000264 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
Craig Topper3c76c522015-09-20 23:35:59 +0000265 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000266
Jim Grosbach4b905842013-09-20 23:08:21 +0000267 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000268 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000269 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000270 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000271 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000272 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000273
Eli Benderskya313ae62013-01-16 18:56:50 +0000274 /// \brief Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000275 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000276
277 /// \brief Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000278 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000279
Eli Benderskya313ae62013-01-16 18:56:50 +0000280 /// \brief Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000281 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000282
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000283 /// \brief Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000284 ///
285 /// \param M The macro.
286 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000287 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000288
289 /// \brief Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000290 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000291
David Majnemer91fc4c22014-01-29 18:57:46 +0000292 /// \brief Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000293 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000294
295 /// \brief Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000296 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000297
Jim Grosbach4b905842013-09-20 23:08:21 +0000298 void printMacroInstantiations();
299 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Nirav Dave2364748a2016-09-16 18:30:20 +0000300 SMRange Range = None) const {
301 ArrayRef<SMRange> Ranges(Range);
Chris Lattner72845262011-10-16 05:47:55 +0000302 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000303 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000304 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000305
Paul Robinson938d9a02018-03-22 15:48:01 +0000306 /// Should we emit DWARF describing this assembler source? (Returns false if
307 /// the source has .file directives, which means we don't want to generate
308 /// info describing the assembler source itself.)
309 bool enabledGenDwarfForAssembly();
310
Jim Grosbach4b905842013-09-20 23:08:21 +0000311 /// \brief Enter the specified file. This returns true on failure.
312 bool enterIncludeFile(const std::string &Filename);
313
314 /// \brief Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000315 /// This returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000316 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
317 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
Daniel Dunbar43235712010-07-18 18:54:11 +0000318
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000319 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000320 /// current token is not set; clients should ensure Lex() is called
321 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000322 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000323 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000324 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000325 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000326
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000327 /// \brief Parse up to the end of statement and a return the contents from the
328 /// current token until the end of the statement; the current token on exit
329 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000330 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000331
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000332 /// \brief Parse until the end of a statement or a comma is encountered,
333 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000334 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000335
Jim Grosbach4b905842013-09-20 23:08:21 +0000336 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +0000337 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000338
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000339 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
340 MCBinaryExpr::Opcode &Kind);
341
Jim Grosbach4b905842013-09-20 23:08:21 +0000342 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
343 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
344 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000345
Jim Grosbach4b905842013-09-20 23:08:21 +0000346 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000347
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000348 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
349 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
350
Eli Bendersky17233942013-01-15 22:59:42 +0000351 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000352 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000353 DK_NO_DIRECTIVE, // Placeholder
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000354 DK_SET,
355 DK_EQU,
356 DK_EQUIV,
357 DK_ASCII,
358 DK_ASCIZ,
359 DK_STRING,
360 DK_BYTE,
361 DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000362 DK_RELOC,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000363 DK_VALUE,
364 DK_2BYTE,
365 DK_LONG,
366 DK_INT,
367 DK_4BYTE,
368 DK_QUAD,
369 DK_8BYTE,
370 DK_OCTA,
371 DK_DC,
372 DK_DC_A,
373 DK_DC_B,
374 DK_DC_D,
375 DK_DC_L,
376 DK_DC_S,
377 DK_DC_W,
378 DK_DC_X,
379 DK_DCB,
380 DK_DCB_B,
381 DK_DCB_D,
382 DK_DCB_L,
383 DK_DCB_S,
384 DK_DCB_W,
385 DK_DCB_X,
386 DK_DS,
387 DK_DS_B,
388 DK_DS_D,
389 DK_DS_L,
390 DK_DS_P,
391 DK_DS_S,
392 DK_DS_W,
393 DK_DS_X,
394 DK_SINGLE,
395 DK_FLOAT,
396 DK_DOUBLE,
397 DK_ALIGN,
398 DK_ALIGN32,
399 DK_BALIGN,
400 DK_BALIGNW,
401 DK_BALIGNL,
402 DK_P2ALIGN,
403 DK_P2ALIGNW,
404 DK_P2ALIGNL,
405 DK_ORG,
406 DK_FILL,
407 DK_ENDR,
408 DK_BUNDLE_ALIGN_MODE,
409 DK_BUNDLE_LOCK,
410 DK_BUNDLE_UNLOCK,
411 DK_ZERO,
412 DK_EXTERN,
413 DK_GLOBL,
414 DK_GLOBAL,
415 DK_LAZY_REFERENCE,
416 DK_NO_DEAD_STRIP,
417 DK_SYMBOL_RESOLVER,
418 DK_PRIVATE_EXTERN,
419 DK_REFERENCE,
420 DK_WEAK_DEFINITION,
421 DK_WEAK_REFERENCE,
422 DK_WEAK_DEF_CAN_BE_HIDDEN,
423 DK_COMM,
424 DK_COMMON,
425 DK_LCOMM,
426 DK_ABORT,
427 DK_INCLUDE,
428 DK_INCBIN,
429 DK_CODE16,
430 DK_CODE16GCC,
431 DK_REPT,
432 DK_IRP,
433 DK_IRPC,
434 DK_IF,
435 DK_IFEQ,
436 DK_IFGE,
437 DK_IFGT,
438 DK_IFLE,
439 DK_IFLT,
440 DK_IFNE,
441 DK_IFB,
442 DK_IFNB,
443 DK_IFC,
444 DK_IFEQS,
445 DK_IFNC,
446 DK_IFNES,
447 DK_IFDEF,
448 DK_IFNDEF,
449 DK_IFNOTDEF,
450 DK_ELSEIF,
451 DK_ELSE,
452 DK_ENDIF,
453 DK_SPACE,
454 DK_SKIP,
455 DK_FILE,
456 DK_LINE,
457 DK_LOC,
458 DK_STABS,
459 DK_CV_FILE,
460 DK_CV_FUNC_ID,
461 DK_CV_INLINE_SITE_ID,
462 DK_CV_LOC,
463 DK_CV_LINETABLE,
464 DK_CV_INLINE_LINETABLE,
465 DK_CV_DEF_RANGE,
466 DK_CV_STRINGTABLE,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000467 DK_CV_FILECHECKSUMS,
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000468 DK_CV_FILECHECKSUM_OFFSET,
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000469 DK_CV_FPO_DATA,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000470 DK_CFI_SECTIONS,
471 DK_CFI_STARTPROC,
472 DK_CFI_ENDPROC,
473 DK_CFI_DEF_CFA,
474 DK_CFI_DEF_CFA_OFFSET,
475 DK_CFI_ADJUST_CFA_OFFSET,
476 DK_CFI_DEF_CFA_REGISTER,
477 DK_CFI_OFFSET,
478 DK_CFI_REL_OFFSET,
479 DK_CFI_PERSONALITY,
480 DK_CFI_LSDA,
481 DK_CFI_REMEMBER_STATE,
482 DK_CFI_RESTORE_STATE,
483 DK_CFI_SAME_VALUE,
484 DK_CFI_RESTORE,
485 DK_CFI_ESCAPE,
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000486 DK_CFI_RETURN_COLUMN,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000487 DK_CFI_SIGNAL_FRAME,
488 DK_CFI_UNDEFINED,
489 DK_CFI_REGISTER,
490 DK_CFI_WINDOW_SAVE,
491 DK_MACROS_ON,
492 DK_MACROS_OFF,
493 DK_ALTMACRO,
494 DK_NOALTMACRO,
495 DK_MACRO,
496 DK_EXITM,
497 DK_ENDM,
498 DK_ENDMACRO,
499 DK_PURGEM,
500 DK_SLEB128,
501 DK_ULEB128,
502 DK_ERR,
503 DK_ERROR,
504 DK_WARNING,
Coby Tayree01e53202017-10-02 14:36:31 +0000505 DK_PRINT,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000506 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000507 };
508
Jim Grosbach4b905842013-09-20 23:08:21 +0000509 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000510 /// directives parsed by this class.
511 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000512
513 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000514 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000515 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Nirav Dave1a9044b2016-10-24 14:35:29 +0000516 bool parseDirectiveValue(StringRef IDVal,
517 unsigned Size); // ".byte", ".long", ...
518 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
519 bool parseDirectiveRealValue(StringRef IDVal,
520 const fltSemantics &); // ".single", ...
Jim Grosbach4b905842013-09-20 23:08:21 +0000521 bool parseDirectiveFill(); // ".fill"
522 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000523 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000524 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
525 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000526 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000527 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000528
Eli Bendersky17233942013-01-15 22:59:42 +0000529 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000530 bool parseDirectiveFile(SMLoc DirectiveLoc);
531 bool parseDirectiveLine();
532 bool parseDirectiveLoc();
533 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000534
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000535 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
536 // ".cv_inline_linetable", ".cv_def_range"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000537 bool parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000538 bool parseDirectiveCVFuncId();
539 bool parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000540 bool parseDirectiveCVLoc();
541 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000542 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000543 bool parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000544 bool parseDirectiveCVStringTable();
545 bool parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000546 bool parseDirectiveCVFileChecksumOffset();
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000547 bool parseDirectiveCVFPOData();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000548
Eli Bendersky17233942013-01-15 22:59:42 +0000549 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000550 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000551 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000552 bool parseDirectiveCFISections();
553 bool parseDirectiveCFIStartProc();
554 bool parseDirectiveCFIEndProc();
555 bool parseDirectiveCFIDefCfaOffset();
556 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
557 bool parseDirectiveCFIAdjustCfaOffset();
558 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
559 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
560 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
561 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
562 bool parseDirectiveCFIRememberState();
563 bool parseDirectiveCFIRestoreState();
564 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
565 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
566 bool parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000567 bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +0000568 bool parseDirectiveCFISignalFrame();
569 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000570
571 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000572 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000573 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000574 bool parseDirectiveEndMacro(StringRef Directive);
575 bool parseDirectiveMacro(SMLoc DirectiveLoc);
576 bool parseDirectiveMacrosOnOff(StringRef Directive);
Michael Zuckerman56704612017-05-01 13:20:12 +0000577 // alternate macro mode directives
578 bool parseDirectiveAltmacro(StringRef Directive);
Eli Benderskyf483ff92012-12-20 19:05:53 +0000579 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000580 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000581 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000582 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000583 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000584 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000585
Eli Bendersky17233942013-01-15 22:59:42 +0000586 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000587 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000588
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000589 // ".dcb"
590 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
591 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
Petr Hosek85b2f672016-09-23 21:53:36 +0000592 // ".ds"
593 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000594
Eli Bendersky17233942013-01-15 22:59:42 +0000595 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000596 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000597
Jim Grosbach4b905842013-09-20 23:08:21 +0000598 /// \brief Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000599 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000600 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000601
Jim Grosbach4b905842013-09-20 23:08:21 +0000602 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000603
Jim Grosbach4b905842013-09-20 23:08:21 +0000604 bool parseDirectiveAbort(); // ".abort"
605 bool parseDirectiveInclude(); // ".include"
606 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000607
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000608 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
609 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000610 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000611 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000612 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000613 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000614 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
615 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000616 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000617 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
618 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
619 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
620 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000621 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000622
Jim Grosbach4b905842013-09-20 23:08:21 +0000623 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000624 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000625
Rafael Espindola34b9c512012-06-03 23:57:14 +0000626 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000627 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
628 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000629 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000630 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000631 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
632 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
633 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000634
Chad Rosierc7f552c2013-02-12 21:33:51 +0000635 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000636 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000637 size_t Len);
638
639 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000640 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000641
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000642 // "end"
643 bool parseDirectiveEnd(SMLoc DirectiveLoc);
644
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000645 // ".err" or ".error"
646 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000647
Nico Weber404012b2014-07-24 16:26:06 +0000648 // ".warning"
649 bool parseDirectiveWarning(SMLoc DirectiveLoc);
650
Coby Tayree01e53202017-10-02 14:36:31 +0000651 // .print <double-quotes-string>
652 bool parseDirectivePrint(SMLoc DirectiveLoc);
653
Eli Bendersky17233942013-01-15 22:59:42 +0000654 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000655};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000656
657} // end anonymous namespace
Daniel Dunbar86033402010-07-12 17:54:38 +0000658
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000659namespace llvm {
660
661extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000662extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000663extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000664
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000665} // end namespace llvm
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000666
Chris Lattnerc35681b2010-01-19 19:46:13 +0000667enum { DEFAULT_ADDRSPACE = 0 };
668
David Blaikie9f380a32015-03-16 18:06:57 +0000669AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000670 const MCAsmInfo &MAI, unsigned CB = 0)
David Blaikie9f380a32015-03-16 18:06:57 +0000671 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000672 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
Nirav Dave2364748a2016-09-16 18:30:20 +0000673 HadError = false;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000674 // Save the old handler.
675 SavedDiagHandler = SrcMgr.getDiagHandler();
676 SavedDiagContext = SrcMgr.getDiagContext();
677 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000678 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000679 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000680
Daniel Dunbarc5011082010-07-12 18:12:02 +0000681 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000682 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
683 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000684 PlatformParser.reset(createCOFFAsmParser());
685 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000686 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000687 PlatformParser.reset(createDarwinAsmParser());
688 IsDarwin = true;
689 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000690 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000691 PlatformParser.reset(createELFAsmParser());
692 break;
Dan Gohman18eafb62017-02-22 01:23:18 +0000693 case MCObjectFileInfo::IsWasm:
694 llvm_unreachable("Wasm parsing not supported yet");
695 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000696 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000697
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000698 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000699 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000700
701 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000702}
703
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000704AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000705 assert((HadError || ActiveMacros.empty()) &&
706 "Unexpected active macro instantiation!");
Sanne Wouda29338752017-02-08 14:48:05 +0000707
708 // Restore the saved diagnostics handler and context for use during
709 // finalization.
710 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000711}
712
Jim Grosbach4b905842013-09-20 23:08:21 +0000713void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000714 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000715 for (std::vector<MacroInstantiation *>::const_reverse_iterator
716 it = ActiveMacros.rbegin(),
717 ie = ActiveMacros.rend();
718 it != ie; ++it)
719 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000720 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000721}
722
Nirav Dave2364748a2016-09-16 18:30:20 +0000723void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
724 printPendingErrors();
725 printMessage(L, SourceMgr::DK_Note, Msg, Range);
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000726 printMacroInstantiations();
727}
728
Nirav Dave2364748a2016-09-16 18:30:20 +0000729bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000730 if(getTargetParser().getTargetOptions().MCNoWarn)
731 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000732 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Nirav Dave2364748a2016-09-16 18:30:20 +0000733 return Error(L, Msg, Range);
734 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000735 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000736 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000737}
738
Nirav Dave2364748a2016-09-16 18:30:20 +0000739bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000740 HadError = true;
Nirav Dave2364748a2016-09-16 18:30:20 +0000741 printMessage(L, SourceMgr::DK_Error, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000742 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000743 return true;
744}
745
Jim Grosbach4b905842013-09-20 23:08:21 +0000746bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000747 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000748 unsigned NewBuf =
749 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
750 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000751 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000752
Sean Callanan7a77eae2010-01-21 00:19:58 +0000753 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000754 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000755 return false;
756}
Daniel Dunbar43235712010-07-18 18:54:11 +0000757
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000758/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000759/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000760/// returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000761bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
762 const MCExpr *Count, SMLoc Loc) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000763 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000764 unsigned NewBuf =
765 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
766 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000767 return true;
768
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000769 // Pick up the bytes from the file and emit them.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000770 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
771 Bytes = Bytes.drop_front(Skip);
772 if (Count) {
773 int64_t Res;
774 if (!Count->evaluateAsAbsolute(Res))
775 return Error(Loc, "expected absolute expression");
776 if (Res < 0)
777 return Warning(Loc, "negative count has no effect");
778 Bytes = Bytes.take_front(Res);
779 }
780 getStreamer().EmitBytes(Bytes);
Kevin Enderby109f25c2011-12-14 21:47:48 +0000781 return false;
782}
783
Alp Tokera55b95b2014-07-06 10:33:31 +0000784void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
785 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000786 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
787 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000788}
789
Sean Callanan7a77eae2010-01-21 00:19:58 +0000790const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000791 if (Lexer.getTok().is(AsmToken::Error))
792 Error(Lexer.getErrLoc(), Lexer.getErr());
793
Nirav Dave53a72f42016-07-11 12:42:14 +0000794 // if it's a end of statement with a comment in it
795 if (getTok().is(AsmToken::EndOfStatement)) {
796 // if this is a line comment output it.
Nirav Dave670109d2017-06-09 14:04:03 +0000797 if (!getTok().getString().empty() && getTok().getString().front() != '\n' &&
Nirav Dave53a72f42016-07-11 12:42:14 +0000798 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
799 Out.addExplicitComment(Twine(getTok().getString()));
800 }
801
Sean Callanan7a77eae2010-01-21 00:19:58 +0000802 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000803
804 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000805 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000806 if (MAI.preserveAsmComments())
807 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000808 tok = &Lexer.Lex();
809 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000810
Sean Callanan7a77eae2010-01-21 00:19:58 +0000811 if (tok->is(AsmToken::Eof)) {
812 // If this is the end of an included file, pop the parent file off the
813 // include stack.
814 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
815 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000816 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000817 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000818 }
819 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000820
Sean Callanan7a77eae2010-01-21 00:19:58 +0000821 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000822}
823
Paul Robinson938d9a02018-03-22 15:48:01 +0000824bool AsmParser::enabledGenDwarfForAssembly() {
825 // Check whether the user specified -g.
826 if (!getContext().getGenDwarfForAssembly())
827 return false;
828 // If we haven't encountered any .file directives (which would imply that
829 // the assembler source was produced with debug info already) then emit one
830 // describing the assembler source file itself.
831 if (getContext().getGenDwarfFileNumber() == 0)
832 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
833 0, StringRef(), getContext().getMainFileName()));
834 return true;
835}
836
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000837bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000838 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000839 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000840 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000841
Chris Lattner36e02122009-06-21 20:54:55 +0000842 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000843 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000844
845 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000846 AsmCond StartingCondState = TheCondState;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000847 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000848
Kevin Enderby6469fc22011-11-01 22:27:22 +0000849 // If we are generating dwarf for assembly source files save the initial text
Paul Robinson938d9a02018-03-22 15:48:01 +0000850 // section. (Don't use enabledGenDwarfForAssembly() here, as we aren't
851 // emitting any actual debug info yet and haven't had a chance to parse any
852 // embedded .file directives.)
Kevin Enderby6469fc22011-11-01 22:27:22 +0000853 if (getContext().getGenDwarfForAssembly()) {
Eric Christopher445c9522016-10-14 05:47:37 +0000854 MCSection *Sec = getStreamer().getCurrentSectionOnly();
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000855 if (!Sec->getBeginSymbol()) {
856 MCSymbol *SectionStartSym = getContext().createTempSymbol();
857 getStreamer().EmitLabel(SectionStartSym);
858 Sec->setBeginSymbol(SectionStartSym);
859 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000860 bool InsertResult = getContext().addGenDwarfSection(Sec);
861 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000862 (void)InsertResult;
Kevin Enderby6469fc22011-11-01 22:27:22 +0000863 }
864
Chris Lattner73f36112009-07-02 21:53:43 +0000865 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000866 while (Lexer.isNot(AsmToken::Eof)) {
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000867 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000868 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000869 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000870
Nirav Dave2364748a2016-09-16 18:30:20 +0000871 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
872 // for printing ErrMsg via Lex() only if no (presumably better) parser error
873 // exists.
874 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
Nirav Dave1180e6892016-06-02 17:15:05 +0000875 Lex();
876 }
877
Nirav Dave2364748a2016-09-16 18:30:20 +0000878 // parseStatement returned true so may need to emit an error.
879 printPendingErrors();
880
881 // Skipping to the next line if needed.
882 if (!getLexer().isAtStartOfStatement())
883 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000884 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000885
Nirav Dave2364748a2016-09-16 18:30:20 +0000886 // All errors should have been emitted.
887 assert(!hasPendingError() && "unexpected error from parseStatement");
888
Oliver Stannard21718282016-07-26 14:19:47 +0000889 getTargetParser().flushPendingInstructions(getStreamer());
890
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000891 if (TheCondState.TheCond != StartingCondState.TheCond ||
892 TheCondState.Ignore != StartingCondState.Ignore)
Nirav Dave2364748a2016-09-16 18:30:20 +0000893 printError(getTok().getLoc(), "unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000894 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000895 const auto &LineTables = getContext().getMCDwarfLineTables();
896 if (!LineTables.empty()) {
897 unsigned Index = 0;
898 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
899 if (File.Name.empty() && Index != 0)
Nirav Dave2364748a2016-09-16 18:30:20 +0000900 printError(getTok().getLoc(), "unassigned file number: " +
901 Twine(Index) +
902 " for .file directives");
David Blaikie8bf66c42014-04-01 07:35:52 +0000903 ++Index;
904 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000905 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000906
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000907 // Check to see that all assembler local symbols were actually defined.
908 // Targets that don't do subsections via symbols may not want this, though,
909 // so conservatively exclude them. Only do this if we're finalizing, though,
910 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000911 if (!NoFinalize) {
912 if (MAI.hasSubsectionsViaSymbols()) {
913 for (const auto &TableEntry : getContext().getSymbols()) {
914 MCSymbol *Sym = TableEntry.getValue();
915 // Variable symbols may not be marked as defined, so check those
916 // explicitly. If we know it's a variable, we have a definition for
917 // the purposes of this check.
918 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
919 // FIXME: We would really like to refer back to where the symbol was
920 // first referenced for a source location. We need to add something
921 // to track that. Currently, we just point to the end of the file.
Nirav Dave2364748a2016-09-16 18:30:20 +0000922 printError(getTok().getLoc(), "assembler local symbol '" +
923 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000924 }
925 }
926
927 // Temporary symbols like the ones for directional jumps don't go in the
928 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000929 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
930 if (std::get<2>(LocSym)->isUndefined()) {
931 // Reset the state of any "# line file" directives we've seen to the
932 // context as it was at the diagnostic site.
933 CppHashInfo = std::get<1>(LocSym);
Nirav Dave2364748a2016-09-16 18:30:20 +0000934 printError(std::get<0>(LocSym), "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000935 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000936 }
937 }
938
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000939 // Finalize the output stream if there are no errors and if the client wants
940 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000941 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000942 Out.Finish();
943
Oliver Stannard07b43d32015-11-17 09:58:07 +0000944 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000945}
946
Nirav Davef43cc9f2016-10-10 15:24:54 +0000947bool AsmParser::checkForValidSection() {
Eric Christopher445c9522016-10-14 05:47:37 +0000948 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000949 Out.InitSections(false);
Nirav Davef43cc9f2016-10-10 15:24:54 +0000950 return Error(getTok().getLoc(),
951 "expected section directive before assembly directive");
Daniel Dunbare5444a82010-09-09 22:42:59 +0000952 }
Nirav Davef43cc9f2016-10-10 15:24:54 +0000953 return false;
Daniel Dunbare5444a82010-09-09 22:42:59 +0000954}
955
Jim Grosbach4b905842013-09-20 23:08:21 +0000956/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000957void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000958 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000959 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000960
Chris Lattnere5074c42009-06-22 01:29:09 +0000961 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000962 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000963 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000964}
965
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000966StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000967 const char *Start = getTok().getLoc().getPointer();
968
Jim Grosbach4b905842013-09-20 23:08:21 +0000969 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000970 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000971
972 const char *End = getTok().getLoc().getPointer();
973 return StringRef(Start, End - Start);
974}
Chris Lattner78db3622009-06-22 05:51:26 +0000975
Jim Grosbach4b905842013-09-20 23:08:21 +0000976StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000977 const char *Start = getTok().getLoc().getPointer();
978
979 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000980 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000981 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000982
983 const char *End = getTok().getLoc().getPointer();
984 return StringRef(Start, End - Start);
985}
986
Jim Grosbach4b905842013-09-20 23:08:21 +0000987/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000988/// NOTE: This assumes the leading '(' has already been consumed.
989///
990/// parenexpr ::= expr)
991///
Jim Grosbach4b905842013-09-20 23:08:21 +0000992bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
993 if (parseExpression(Res))
994 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000995 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +0000996 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000997 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000998 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +0000999 return false;
1000}
Chris Lattner78db3622009-06-22 05:51:26 +00001001
Jim Grosbach4b905842013-09-20 23:08:21 +00001002/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001003/// NOTE: This assumes the leading '[' has already been consumed.
1004///
1005/// bracketexpr ::= expr]
1006///
Jim Grosbach4b905842013-09-20 23:08:21 +00001007bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1008 if (parseExpression(Res))
1009 return true;
Nirav Davea645433c2016-07-18 15:24:03 +00001010 EndLoc = getTok().getEndLoc();
1011 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
1012 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001013 return false;
1014}
1015
Jim Grosbach4b905842013-09-20 23:08:21 +00001016/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001017/// primaryexpr ::= (parenexpr
1018/// primaryexpr ::= symbol
1019/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +00001020/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +00001021/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +00001022bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001023 SMLoc FirstTokenLoc = getLexer().getLoc();
1024 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
1025 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +00001026 default:
1027 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +00001028 // If we have an error assume that we've already handled it.
1029 case AsmToken::Error:
1030 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001031 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001032 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001033 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001034 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001035 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001036 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +00001037 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +00001038 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00001039 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +00001040 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +00001041 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001042 if (parseIdentifier(Identifier)) {
Nirav Daved0463322016-10-12 13:58:07 +00001043 // We may have failed but $ may be a valid token.
1044 if (getTok().is(AsmToken::Dollar)) {
David Majnemer0c58bc62013-09-25 10:47:21 +00001045 if (Lexer.getMAI().getDollarIsPC()) {
Nirav Daved0463322016-10-12 13:58:07 +00001046 Lex();
David Majnemer0c58bc62013-09-25 10:47:21 +00001047 // This is a '$' reference, which references the current PC. Emit a
1048 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001049 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +00001050 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001051 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +00001052 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +00001053 EndLoc = FirstTokenLoc;
1054 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +00001055 }
1056 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +00001057 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001058 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001059 // Parse symbol variant
1060 std::pair<StringRef, StringRef> Split;
1061 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +00001062 if (FirstTokenKind == AsmToken::String) {
1063 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +00001064 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +00001065 SMLoc AtLoc = getLexer().getLoc();
1066 StringRef VName;
1067 if (parseIdentifier(VName))
1068 return Error(AtLoc, "expected symbol variant after '@'");
1069
1070 Split = std::make_pair(Identifier, VName);
1071 }
1072 } else {
1073 Split = Identifier.split('@');
1074 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001075 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +00001076 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +00001077 StringRef VName;
1078 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +00001079 // eat ')'.
1080 if (parseToken(AsmToken::RParen,
1081 "unexpected token in variant, expected ')'"))
1082 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +00001083 Split = std::make_pair(Identifier, VName);
1084 }
Daniel Dunbar24764322010-08-24 19:13:42 +00001085
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001086 EndLoc = SMLoc::getFromPointer(Identifier.end());
1087
Daniel Dunbard20cda02009-10-16 01:34:54 +00001088 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +00001089 StringRef SymbolName = Identifier;
Weiming Zhaocf26d562016-12-01 18:00:36 +00001090 if (SymbolName.empty())
1091 return true;
1092
Hans Wennborgce69d772013-10-18 20:46:28 +00001093 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +00001094
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001095 // Lookup the symbol variant if used.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001096 if (!Split.second.empty()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001097 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +00001098 if (Variant != MCSymbolRefExpr::VK_Invalid) {
1099 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +00001100 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +00001101 Variant = MCSymbolRefExpr::VK_None;
1102 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +00001103 return Error(SMLoc::getFromPointer(Split.second.begin()),
1104 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001105 }
1106 }
Daniel Dunbar55992562010-03-15 23:51:06 +00001107
Jim Grosbach6f482002015-05-18 18:43:14 +00001108 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +00001109
Daniel Dunbard20cda02009-10-16 01:34:54 +00001110 // If this is an absolute variable reference, substitute it now to preserve
1111 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +00001112 if (Sym->isVariable() &&
1113 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +00001114 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +00001115 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +00001116
Vedant Kumar86dbd922015-08-31 17:44:53 +00001117 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +00001118 return false;
1119 }
1120
1121 // Otherwise create a symbol ref.
Chad Rosier9245e122017-01-19 20:06:32 +00001122 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
Chris Lattner78db3622009-06-22 05:51:26 +00001123 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001124 }
David Woodhousef42a6662014-02-01 16:20:54 +00001125 case AsmToken::BigNum:
1126 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001127 case AsmToken::Integer: {
1128 SMLoc Loc = getTok().getLoc();
1129 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001130 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001131 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001132 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001133 // Look for 'b' or 'f' following an Integer as a directional label
1134 if (Lexer.getKind() == AsmToken::Identifier) {
1135 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001136 // Lookup the symbol variant if used.
1137 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1138 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1139 if (Split.first.size() != IDVal.size()) {
1140 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001141 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001142 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001143 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001144 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001145 if (IDVal == "f" || IDVal == "b") {
1146 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001147 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001148 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001149 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001150 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001151 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001152 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001153 Lex(); // Eat identifier.
1154 }
1155 }
Chris Lattner78db3622009-06-22 05:51:26 +00001156 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001157 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001158 case AsmToken::Real: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001159 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001160 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001161 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001162 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001163 Lex(); // Eat token.
1164 return false;
1165 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001166 case AsmToken::Dot: {
1167 // This is a '.' reference, which references the current PC. Emit a
1168 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001169 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001170 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001171 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001172 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001173 Lex(); // Eat identifier.
1174 return false;
1175 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001176 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001177 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001178 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001179 case AsmToken::LBrac:
1180 if (!PlatformParser->HasBracketExpressions())
1181 return TokError("brackets expression not supported on this target");
1182 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001183 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001184 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001185 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001186 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001187 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001188 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001189 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001190 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001191 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001192 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001193 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001194 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001195 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001196 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001197 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001198 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001199 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001200 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001201 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001202 // MIPS unary expression operators. The lexer won't generate these tokens if
1203 // MCAsmInfo::HasMipsExpressions is false for the target.
1204 case AsmToken::PercentCall16:
1205 case AsmToken::PercentCall_Hi:
1206 case AsmToken::PercentCall_Lo:
1207 case AsmToken::PercentDtprel_Hi:
1208 case AsmToken::PercentDtprel_Lo:
1209 case AsmToken::PercentGot:
1210 case AsmToken::PercentGot_Disp:
1211 case AsmToken::PercentGot_Hi:
1212 case AsmToken::PercentGot_Lo:
1213 case AsmToken::PercentGot_Ofst:
1214 case AsmToken::PercentGot_Page:
1215 case AsmToken::PercentGottprel:
1216 case AsmToken::PercentGp_Rel:
1217 case AsmToken::PercentHi:
1218 case AsmToken::PercentHigher:
1219 case AsmToken::PercentHighest:
1220 case AsmToken::PercentLo:
1221 case AsmToken::PercentNeg:
1222 case AsmToken::PercentPcrel_Hi:
1223 case AsmToken::PercentPcrel_Lo:
1224 case AsmToken::PercentTlsgd:
1225 case AsmToken::PercentTlsldm:
1226 case AsmToken::PercentTprel_Hi:
1227 case AsmToken::PercentTprel_Lo:
1228 Lex(); // Eat the operator.
1229 if (Lexer.isNot(AsmToken::LParen))
1230 return TokError("expected '(' after operator");
1231 Lex(); // Eat the operator.
1232 if (parseExpression(Res, EndLoc))
1233 return true;
1234 if (Lexer.isNot(AsmToken::RParen))
1235 return TokError("expected ')'");
1236 Lex(); // Eat the operator.
1237 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1238 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001239 }
1240}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001241
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001242bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001243 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001244 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001245}
1246
Daniel Dunbar55f16672010-09-17 02:47:07 +00001247const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001248AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001249 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001250 // Ask the target implementation about this expression first.
1251 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1252 if (NewE)
1253 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001254 // Recurse over the given expression, rebuilding it to apply the given variant
1255 // if there is exactly one symbol.
1256 switch (E->getKind()) {
1257 case MCExpr::Target:
1258 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001259 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001260
1261 case MCExpr::SymbolRef: {
1262 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1263
1264 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001265 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1266 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001267 return E;
1268 }
1269
Jim Grosbach13760bd2015-05-30 01:25:56 +00001270 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001271 }
1272
1273 case MCExpr::Unary: {
1274 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001275 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001276 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001277 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001278 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001279 }
1280
1281 case MCExpr::Binary: {
1282 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001283 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1284 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001285
1286 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001287 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001288
Jim Grosbach4b905842013-09-20 23:08:21 +00001289 if (!LHS)
1290 LHS = BE->getLHS();
1291 if (!RHS)
1292 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001293
Jim Grosbach13760bd2015-05-30 01:25:56 +00001294 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001295 }
1296 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001297
Craig Toppera2886c22012-02-07 05:05:23 +00001298 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001299}
1300
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001301/// This function checks if the next token is <string> type or arithmetic.
1302/// string that begin with character '<' must end with character '>'.
1303/// otherwise it is arithmetics.
1304/// If the function returns a 'true' value,
1305/// the End argument will be filled with the last location pointed to the '>'
1306/// character.
1307
1308/// There is a gap between the AltMacro's documentation and the single quote implementation.
1309/// GCC does not fully support this feature and so we will not support it.
1310/// TODO: Adding single quote as a string.
1311bool AsmParser::isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc) {
1312 assert((StrLoc.getPointer() != NULL) &&
1313 "Argument to the function cannot be a NULL value");
1314 const char *CharPtr = StrLoc.getPointer();
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001315 while ((*CharPtr != '>') && (*CharPtr != '\n') && (*CharPtr != '\r') &&
1316 (*CharPtr != '\0')) {
1317 if (*CharPtr == '!')
1318 CharPtr++;
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001319 CharPtr++;
1320 }
1321 if (*CharPtr == '>') {
1322 EndLoc = StrLoc.getFromPointer(CharPtr + 1);
1323 return true;
1324 }
1325 return false;
1326}
1327
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001328/// \brief creating a string without the escape characters '!'.
1329void AsmParser::altMacroString(StringRef AltMacroStr,std::string &Res) {
Michael Zuckermanff298792017-05-10 14:00:57 +00001330 for (size_t Pos = 0; Pos < AltMacroStr.size(); Pos++) {
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001331 if (AltMacroStr[Pos] == '!')
1332 Pos++;
1333 Res += AltMacroStr[Pos];
1334 }
1335}
1336
Jim Grosbach4b905842013-09-20 23:08:21 +00001337/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001338///
Jim Grosbachbd164242011-08-20 16:24:13 +00001339/// expr ::= expr &&,|| expr -> lowest.
1340/// expr ::= expr |,^,&,! expr
1341/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1342/// expr ::= expr <<,>> expr
1343/// expr ::= expr +,- expr
1344/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001345/// expr ::= primaryexpr
1346///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001347bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001348 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001349 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001350 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001351 return true;
1352
Daniel Dunbar55f16672010-09-17 02:47:07 +00001353 // As a special case, we support 'a op b @ modifier' by rewriting the
1354 // expression to include the modifier. This is inefficient, but in general we
1355 // expect users to use 'a@modifier op b'.
1356 if (Lexer.getKind() == AsmToken::At) {
1357 Lex();
1358
1359 if (Lexer.isNot(AsmToken::Identifier))
1360 return TokError("unexpected symbol modifier following '@'");
1361
1362 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001363 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001364 if (Variant == MCSymbolRefExpr::VK_Invalid)
1365 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1366
Jim Grosbach4b905842013-09-20 23:08:21 +00001367 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001368 if (!ModifiedRes) {
1369 return TokError("invalid modifier '" + getTok().getIdentifier() +
1370 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001371 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001372
Daniel Dunbar55f16672010-09-17 02:47:07 +00001373 Res = ModifiedRes;
1374 Lex();
1375 }
1376
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001377 // Try to constant fold it up front, if possible.
1378 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001379 if (Res->evaluateAsAbsolute(Value))
1380 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001381
1382 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001383}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001384
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001385bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001386 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001387 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001388}
1389
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001390bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1391 SMLoc &EndLoc) {
1392 if (parseParenExpr(Res, EndLoc))
1393 return true;
1394
1395 for (; ParenDepth > 0; --ParenDepth) {
1396 if (parseBinOpRHS(1, Res, EndLoc))
1397 return true;
1398
1399 // We don't Lex() the last RParen.
1400 // This is the same behavior as parseParenExpression().
1401 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001402 EndLoc = getTok().getEndLoc();
1403 if (parseToken(AsmToken::RParen,
1404 "expected ')' in parentheses expression"))
1405 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001406 }
1407 }
1408 return false;
1409}
1410
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001411bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001412 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001413
Daniel Dunbar75630b32009-06-30 02:10:03 +00001414 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001415 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001416 return true;
1417
Jim Grosbach13760bd2015-05-30 01:25:56 +00001418 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001419 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001420
1421 return false;
1422}
1423
David Majnemer0993e0b2015-10-26 03:15:34 +00001424static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1425 MCBinaryExpr::Opcode &Kind,
1426 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001427 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001428 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001429 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001430
Jim Grosbach4b905842013-09-20 23:08:21 +00001431 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001432 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001433 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001434 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001435 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001436 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001437 return 1;
1438
Jim Grosbach4b905842013-09-20 23:08:21 +00001439 // Low Precedence: |, &, ^
1440 //
1441 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001442 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001443 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001444 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001445 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001446 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001447 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001448 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001449 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001450 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001451
Jim Grosbach4b905842013-09-20 23:08:21 +00001452 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001453 case AsmToken::EqualEqual:
1454 Kind = MCBinaryExpr::EQ;
1455 return 3;
1456 case AsmToken::ExclaimEqual:
1457 case AsmToken::LessGreater:
1458 Kind = MCBinaryExpr::NE;
1459 return 3;
1460 case AsmToken::Less:
1461 Kind = MCBinaryExpr::LT;
1462 return 3;
1463 case AsmToken::LessEqual:
1464 Kind = MCBinaryExpr::LTE;
1465 return 3;
1466 case AsmToken::Greater:
1467 Kind = MCBinaryExpr::GT;
1468 return 3;
1469 case AsmToken::GreaterEqual:
1470 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001471 return 3;
1472
Jim Grosbach4b905842013-09-20 23:08:21 +00001473 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001474 case AsmToken::LessLess:
1475 Kind = MCBinaryExpr::Shl;
1476 return 4;
1477 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001478 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001479 return 4;
1480
Jim Grosbach4b905842013-09-20 23:08:21 +00001481 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001482 case AsmToken::Plus:
1483 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001484 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001485 case AsmToken::Minus:
1486 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001487 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001488
Jim Grosbach4b905842013-09-20 23:08:21 +00001489 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001490 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001491 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001492 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001493 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001494 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001495 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001496 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001497 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001498 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001499 }
1500}
1501
David Majnemer0993e0b2015-10-26 03:15:34 +00001502static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1503 MCBinaryExpr::Opcode &Kind,
1504 bool ShouldUseLogicalShr) {
1505 switch (K) {
1506 default:
1507 return 0; // not a binop.
1508
1509 // Lowest Precedence: &&, ||
1510 case AsmToken::AmpAmp:
1511 Kind = MCBinaryExpr::LAnd;
1512 return 2;
1513 case AsmToken::PipePipe:
1514 Kind = MCBinaryExpr::LOr;
1515 return 1;
1516
1517 // Low Precedence: ==, !=, <>, <, <=, >, >=
1518 case AsmToken::EqualEqual:
1519 Kind = MCBinaryExpr::EQ;
1520 return 3;
1521 case AsmToken::ExclaimEqual:
1522 case AsmToken::LessGreater:
1523 Kind = MCBinaryExpr::NE;
1524 return 3;
1525 case AsmToken::Less:
1526 Kind = MCBinaryExpr::LT;
1527 return 3;
1528 case AsmToken::LessEqual:
1529 Kind = MCBinaryExpr::LTE;
1530 return 3;
1531 case AsmToken::Greater:
1532 Kind = MCBinaryExpr::GT;
1533 return 3;
1534 case AsmToken::GreaterEqual:
1535 Kind = MCBinaryExpr::GTE;
1536 return 3;
1537
1538 // Low Intermediate Precedence: +, -
1539 case AsmToken::Plus:
1540 Kind = MCBinaryExpr::Add;
1541 return 4;
1542 case AsmToken::Minus:
1543 Kind = MCBinaryExpr::Sub;
1544 return 4;
1545
1546 // High Intermediate Precedence: |, &, ^
1547 //
1548 // FIXME: gas seems to support '!' as an infix operator?
1549 case AsmToken::Pipe:
1550 Kind = MCBinaryExpr::Or;
1551 return 5;
1552 case AsmToken::Caret:
1553 Kind = MCBinaryExpr::Xor;
1554 return 5;
1555 case AsmToken::Amp:
1556 Kind = MCBinaryExpr::And;
1557 return 5;
1558
1559 // Highest Precedence: *, /, %, <<, >>
1560 case AsmToken::Star:
1561 Kind = MCBinaryExpr::Mul;
1562 return 6;
1563 case AsmToken::Slash:
1564 Kind = MCBinaryExpr::Div;
1565 return 6;
1566 case AsmToken::Percent:
1567 Kind = MCBinaryExpr::Mod;
1568 return 6;
1569 case AsmToken::LessLess:
1570 Kind = MCBinaryExpr::Shl;
1571 return 6;
1572 case AsmToken::GreaterGreater:
1573 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1574 return 6;
1575 }
1576}
1577
1578unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1579 MCBinaryExpr::Opcode &Kind) {
1580 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1581 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1582 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1583}
1584
Jim Grosbach4b905842013-09-20 23:08:21 +00001585/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001586/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001587bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001588 SMLoc &EndLoc) {
Chad Rosier9245e122017-01-19 20:06:32 +00001589 SMLoc StartLoc = Lexer.getLoc();
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001590 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001591 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001592 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001593
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001594 // If the next token is lower precedence than we are allowed to eat, return
1595 // successfully with what we ate already.
1596 if (TokPrec < Precedence)
1597 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001598
Sean Callanan686ed8d2010-01-19 20:22:31 +00001599 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001600
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001601 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001602 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001603 if (parsePrimaryExpr(RHS, EndLoc))
1604 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001605
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001606 // If BinOp binds less tightly with RHS than the operator after RHS, let
1607 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001608 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001609 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001610 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1611 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001612
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001613 // Merge LHS and RHS according to operator.
Chad Rosier9245e122017-01-19 20:06:32 +00001614 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001615 }
1616}
1617
Chris Lattner36e02122009-06-21 20:54:55 +00001618/// ParseStatement:
1619/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001620/// ::= Label* Directive ...Operands... EndOfStatement
1621/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001622bool AsmParser::parseStatement(ParseStatementInfo &Info,
1623 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001624 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001625 // Eat initial spaces and comments
1626 while (Lexer.is(AsmToken::Space))
1627 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001628 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001629 // if this is a line comment we can drop it safely
Nirav Dave670109d2017-06-09 14:04:03 +00001630 if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
Nirav Davefd910412016-06-17 16:06:17 +00001631 getTok().getString().front() == '\n')
1632 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001633 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001634 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001635 }
Nirav Davefd910412016-06-17 16:06:17 +00001636 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001637 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001638 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001639 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001640 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001641 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001642 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001643 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001644 if (Lexer.is(AsmToken::Integer)) {
1645 LocalLabelVal = getTok().getIntVal();
1646 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001647 if (!TheCondState.Ignore) {
1648 Lex(); // always eat a token
1649 return Error(IDLoc, "unexpected token at start of statement");
1650 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001651 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001652 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001653 IDVal = getTok().getString();
1654 Lex(); // Consume the integer token to be used as an identifier token.
1655 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001656 if (!TheCondState.Ignore) {
1657 Lex(); // always eat a token
1658 return Error(IDLoc, "unexpected token at start of statement");
1659 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001660 }
1661 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001662 } else if (Lexer.is(AsmToken::Dot)) {
1663 // Treat '.' as a valid identifier in this context.
1664 Lex();
1665 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001666 } else if (Lexer.is(AsmToken::LCurly)) {
1667 // Treat '{' as a valid identifier in this context.
1668 Lex();
1669 IDVal = "{";
1670
1671 } else if (Lexer.is(AsmToken::RCurly)) {
1672 // Treat '}' as a valid identifier in this context.
1673 Lex();
1674 IDVal = "}";
Yonghong Song06ff6552017-09-12 17:55:23 +00001675 } else if (Lexer.is(AsmToken::Star) &&
1676 getTargetParser().starIsStartOfStatement()) {
1677 // Accept '*' as a valid start of statement.
1678 Lex();
1679 IDVal = "*";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001680 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001681 if (!TheCondState.Ignore) {
1682 Lex(); // always eat a token
1683 return Error(IDLoc, "unexpected token at start of statement");
1684 }
Chris Lattner926885c2010-04-17 18:14:27 +00001685 IDVal = "";
1686 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001687
Chris Lattner926885c2010-04-17 18:14:27 +00001688 // Handle conditional assembly here before checking for skipping. We
1689 // have to do this so that .endif isn't skipped in a ".if 0" block for
1690 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001691 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001692 DirectiveKindMap.find(IDVal);
1693 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1694 ? DK_NO_DIRECTIVE
1695 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001696 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001697 default:
1698 break;
1699 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001700 case DK_IFEQ:
1701 case DK_IFGE:
1702 case DK_IFGT:
1703 case DK_IFLE:
1704 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001705 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001706 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001707 case DK_IFB:
1708 return parseDirectiveIfb(IDLoc, true);
1709 case DK_IFNB:
1710 return parseDirectiveIfb(IDLoc, false);
1711 case DK_IFC:
1712 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001713 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001714 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001715 case DK_IFNC:
1716 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001717 case DK_IFNES:
1718 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001719 case DK_IFDEF:
1720 return parseDirectiveIfdef(IDLoc, true);
1721 case DK_IFNDEF:
1722 case DK_IFNOTDEF:
1723 return parseDirectiveIfdef(IDLoc, false);
1724 case DK_ELSEIF:
1725 return parseDirectiveElseIf(IDLoc);
1726 case DK_ELSE:
1727 return parseDirectiveElse(IDLoc);
1728 case DK_ENDIF:
1729 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001730 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001731
Eli Bendersky88024712013-01-16 19:32:36 +00001732 // Ignore the statement if in the middle of inactive conditional
1733 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001734 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001735 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001736 return false;
1737 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001738
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001739 // FIXME: Recurse on local labels?
1740
1741 // See what kind of statement we have.
1742 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001743 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001744 if (!getTargetParser().isLabel(ID))
1745 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001746 if (checkForValidSection())
1747 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001748
Chris Lattner36e02122009-06-21 20:54:55 +00001749 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001750 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001751
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001752 // Diagnose attempt to use '.' as a label.
1753 if (IDVal == ".")
1754 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1755
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001756 // Diagnose attempt to use a variable as a label.
1757 //
1758 // FIXME: Diagnostics. Note the location of the definition as a label.
1759 // FIXME: This doesn't diagnose assignment to a symbol which has been
1760 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001761 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001762 if (LocalLabelVal == -1) {
1763 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001764 StringRef RewrittenLabel =
1765 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001766 assert(!RewrittenLabel.empty() &&
Nico Weber67e715f2015-06-19 23:43:47 +00001767 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001768 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1769 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001770 IDVal = RewrittenLabel;
1771 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001772 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001773 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001774 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
Nirav Dave9263ae32016-08-02 19:17:54 +00001775 // End of Labels should be treated as end of line for lexing
1776 // purposes but that information is not available to the Lexer who
1777 // does not understand Labels. This may cause us to see a Hash
1778 // here instead of a preprocessor line comment.
1779 if (getTok().is(AsmToken::Hash)) {
1780 StringRef CommentStr = parseStringToEndOfStatement();
1781 Lexer.Lex();
1782 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1783 }
1784
Nirav Dave8ea792d2016-07-13 14:03:12 +00001785 // Consume any end of statement token, if present, to avoid spurious
1786 // AddBlankLine calls().
1787 if (getTok().is(AsmToken::EndOfStatement)) {
1788 Lex();
1789 }
1790
Daniel Dunbare73b2672009-08-26 22:13:22 +00001791 // Emit the label.
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00001792 if (!getTargetParser().isParsingInlineAsm())
Rafael Espindolabe991572017-02-10 15:13:12 +00001793 Out.EmitLabel(Sym, IDLoc);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001794
Kevin Enderbye7739d42011-12-09 18:09:40 +00001795 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001796 // info to make a dwarf label entry for this label if needed.
Paul Robinson938d9a02018-03-22 15:48:01 +00001797 if (enabledGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001798 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1799 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001800
Tim Northover1744d0a2013-10-25 12:49:50 +00001801 getTargetParser().onLabelParsed(Sym);
1802
Eli Friedman0f4871d2012-10-22 23:58:19 +00001803 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001804 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001805
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001806 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001807 if (!getTargetParser().equalIsAsmAssignment())
1808 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001809 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001810 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001811
Jim Grosbach4b905842013-09-20 23:08:21 +00001812 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001813
1814 default: // Normal instruction or directive.
1815 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001816 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001817
1818 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001819 if (areMacrosEnabled())
Rafael Espindola22c38a02018-02-14 16:34:27 +00001820 if (const MCAsmMacro *M = getContext().lookupMacro(IDVal)) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001821 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001822 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001823
Michael J. Spencer530ce852010-10-09 11:00:50 +00001824 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001825
Eli Bendersky17233942013-01-15 22:59:42 +00001826 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001827 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001828 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001829 //
Eli Bendersky17233942013-01-15 22:59:42 +00001830 // 1. The target-specific assembly parser. Some directives are target
1831 // specific or may potentially behave differently on certain targets.
1832 // 2. Asm parser extensions. For example, platform-specific parsers
1833 // (like the ELF parser) register themselves as extensions.
1834 // 3. The generic directive parser implemented by this class. These are
1835 // all the directives that behave in a target and platform independent
1836 // manner, or at least have a default behavior that's shared between
1837 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001838
Oliver Stannard21718282016-07-26 14:19:47 +00001839 getTargetParser().flushPendingInstructions(getStreamer());
1840
Nirav Dave2364748a2016-09-16 18:30:20 +00001841 SMLoc StartTokLoc = getTok().getLoc();
1842 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1843
1844 if (hasPendingError())
1845 return true;
1846 // Currently the return value should be true if we are
1847 // uninterested but as this is at odds with the standard parsing
1848 // convention (return true = error) we have instances of a parsed
1849 // directive that fails returning true as an error. Catch these
1850 // cases as best as possible errors here.
1851 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1852 return true;
1853 // Return if we did some parsing or believe we succeeded.
1854 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001855 return false;
1856
Alp Tokercb402912014-01-24 17:20:08 +00001857 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001858 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001859 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1860 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001861 if (Handler.first)
1862 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1863
1864 // Finally, if no one else is interested in this directive, it must be
1865 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001866 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001867 default:
1868 break;
1869 case DK_SET:
1870 case DK_EQU:
1871 return parseDirectiveSet(IDVal, true);
1872 case DK_EQUIV:
1873 return parseDirectiveSet(IDVal, false);
1874 case DK_ASCII:
1875 return parseDirectiveAscii(IDVal, false);
1876 case DK_ASCIZ:
1877 case DK_STRING:
1878 return parseDirectiveAscii(IDVal, true);
1879 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001880 case DK_DC_B:
1881 return parseDirectiveValue(IDVal, 1);
1882 case DK_DC:
1883 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001884 case DK_SHORT:
1885 case DK_VALUE:
1886 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001887 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001888 case DK_LONG:
1889 case DK_INT:
1890 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001891 case DK_DC_L:
1892 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001893 case DK_QUAD:
1894 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001895 return parseDirectiveValue(IDVal, 8);
1896 case DK_DC_A:
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001897 return parseDirectiveValue(
1898 IDVal, getContext().getAsmInfo()->getCodePointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001899 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001900 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001901 case DK_SINGLE:
1902 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001903 case DK_DC_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001904 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
Jim Grosbach4b905842013-09-20 23:08:21 +00001905 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001906 case DK_DC_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001907 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
Jim Grosbach4b905842013-09-20 23:08:21 +00001908 case DK_ALIGN: {
1909 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1910 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1911 }
1912 case DK_ALIGN32: {
1913 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1914 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1915 }
1916 case DK_BALIGN:
1917 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1918 case DK_BALIGNW:
1919 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1920 case DK_BALIGNL:
1921 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1922 case DK_P2ALIGN:
1923 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1924 case DK_P2ALIGNW:
1925 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1926 case DK_P2ALIGNL:
1927 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1928 case DK_ORG:
1929 return parseDirectiveOrg();
1930 case DK_FILL:
1931 return parseDirectiveFill();
1932 case DK_ZERO:
1933 return parseDirectiveZero();
1934 case DK_EXTERN:
1935 eatToEndOfStatement(); // .extern is the default, ignore it.
1936 return false;
1937 case DK_GLOBL:
1938 case DK_GLOBAL:
1939 return parseDirectiveSymbolAttribute(MCSA_Global);
1940 case DK_LAZY_REFERENCE:
1941 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1942 case DK_NO_DEAD_STRIP:
1943 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1944 case DK_SYMBOL_RESOLVER:
1945 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1946 case DK_PRIVATE_EXTERN:
1947 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1948 case DK_REFERENCE:
1949 return parseDirectiveSymbolAttribute(MCSA_Reference);
1950 case DK_WEAK_DEFINITION:
1951 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1952 case DK_WEAK_REFERENCE:
1953 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1954 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1955 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1956 case DK_COMM:
1957 case DK_COMMON:
1958 return parseDirectiveComm(/*IsLocal=*/false);
1959 case DK_LCOMM:
1960 return parseDirectiveComm(/*IsLocal=*/true);
1961 case DK_ABORT:
1962 return parseDirectiveAbort();
1963 case DK_INCLUDE:
1964 return parseDirectiveInclude();
1965 case DK_INCBIN:
1966 return parseDirectiveIncbin();
1967 case DK_CODE16:
1968 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001969 return TokError(Twine(IDVal) +
1970 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001971 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001972 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001973 case DK_IRP:
1974 return parseDirectiveIrp(IDLoc);
1975 case DK_IRPC:
1976 return parseDirectiveIrpc(IDLoc);
1977 case DK_ENDR:
1978 return parseDirectiveEndr(IDLoc);
1979 case DK_BUNDLE_ALIGN_MODE:
1980 return parseDirectiveBundleAlignMode();
1981 case DK_BUNDLE_LOCK:
1982 return parseDirectiveBundleLock();
1983 case DK_BUNDLE_UNLOCK:
1984 return parseDirectiveBundleUnlock();
1985 case DK_SLEB128:
1986 return parseDirectiveLEB128(true);
1987 case DK_ULEB128:
1988 return parseDirectiveLEB128(false);
1989 case DK_SPACE:
1990 case DK_SKIP:
1991 return parseDirectiveSpace(IDVal);
1992 case DK_FILE:
1993 return parseDirectiveFile(IDLoc);
1994 case DK_LINE:
1995 return parseDirectiveLine();
1996 case DK_LOC:
1997 return parseDirectiveLoc();
1998 case DK_STABS:
1999 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002000 case DK_CV_FILE:
2001 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00002002 case DK_CV_FUNC_ID:
2003 return parseDirectiveCVFuncId();
2004 case DK_CV_INLINE_SITE_ID:
2005 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002006 case DK_CV_LOC:
2007 return parseDirectiveCVLoc();
2008 case DK_CV_LINETABLE:
2009 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00002010 case DK_CV_INLINE_LINETABLE:
2011 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00002012 case DK_CV_DEF_RANGE:
2013 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002014 case DK_CV_STRINGTABLE:
2015 return parseDirectiveCVStringTable();
2016 case DK_CV_FILECHECKSUMS:
2017 return parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00002018 case DK_CV_FILECHECKSUM_OFFSET:
2019 return parseDirectiveCVFileChecksumOffset();
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00002020 case DK_CV_FPO_DATA:
2021 return parseDirectiveCVFPOData();
Jim Grosbach4b905842013-09-20 23:08:21 +00002022 case DK_CFI_SECTIONS:
2023 return parseDirectiveCFISections();
2024 case DK_CFI_STARTPROC:
2025 return parseDirectiveCFIStartProc();
2026 case DK_CFI_ENDPROC:
2027 return parseDirectiveCFIEndProc();
2028 case DK_CFI_DEF_CFA:
2029 return parseDirectiveCFIDefCfa(IDLoc);
2030 case DK_CFI_DEF_CFA_OFFSET:
2031 return parseDirectiveCFIDefCfaOffset();
2032 case DK_CFI_ADJUST_CFA_OFFSET:
2033 return parseDirectiveCFIAdjustCfaOffset();
2034 case DK_CFI_DEF_CFA_REGISTER:
2035 return parseDirectiveCFIDefCfaRegister(IDLoc);
2036 case DK_CFI_OFFSET:
2037 return parseDirectiveCFIOffset(IDLoc);
2038 case DK_CFI_REL_OFFSET:
2039 return parseDirectiveCFIRelOffset(IDLoc);
2040 case DK_CFI_PERSONALITY:
2041 return parseDirectiveCFIPersonalityOrLsda(true);
2042 case DK_CFI_LSDA:
2043 return parseDirectiveCFIPersonalityOrLsda(false);
2044 case DK_CFI_REMEMBER_STATE:
2045 return parseDirectiveCFIRememberState();
2046 case DK_CFI_RESTORE_STATE:
2047 return parseDirectiveCFIRestoreState();
2048 case DK_CFI_SAME_VALUE:
2049 return parseDirectiveCFISameValue(IDLoc);
2050 case DK_CFI_RESTORE:
2051 return parseDirectiveCFIRestore(IDLoc);
2052 case DK_CFI_ESCAPE:
2053 return parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00002054 case DK_CFI_RETURN_COLUMN:
2055 return parseDirectiveCFIReturnColumn(IDLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +00002056 case DK_CFI_SIGNAL_FRAME:
2057 return parseDirectiveCFISignalFrame();
2058 case DK_CFI_UNDEFINED:
2059 return parseDirectiveCFIUndefined(IDLoc);
2060 case DK_CFI_REGISTER:
2061 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00002062 case DK_CFI_WINDOW_SAVE:
2063 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00002064 case DK_MACROS_ON:
2065 case DK_MACROS_OFF:
2066 return parseDirectiveMacrosOnOff(IDVal);
2067 case DK_MACRO:
2068 return parseDirectiveMacro(IDLoc);
Michael Zuckerman56704612017-05-01 13:20:12 +00002069 case DK_ALTMACRO:
2070 case DK_NOALTMACRO:
2071 return parseDirectiveAltmacro(IDVal);
Nico Weber155dccd12014-07-24 17:08:39 +00002072 case DK_EXITM:
2073 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00002074 case DK_ENDM:
2075 case DK_ENDMACRO:
2076 return parseDirectiveEndMacro(IDVal);
2077 case DK_PURGEM:
2078 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00002079 case DK_END:
2080 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00002081 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00002082 return parseDirectiveError(IDLoc, false);
2083 case DK_ERROR:
2084 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00002085 case DK_WARNING:
2086 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002087 case DK_RELOC:
2088 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002089 case DK_DCB:
2090 case DK_DCB_W:
2091 return parseDirectiveDCB(IDVal, 2);
2092 case DK_DCB_B:
2093 return parseDirectiveDCB(IDVal, 1);
2094 case DK_DCB_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002095 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002096 case DK_DCB_L:
2097 return parseDirectiveDCB(IDVal, 4);
2098 case DK_DCB_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002099 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
Petr Hosek731bb9c2016-08-23 21:34:53 +00002100 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002101 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00002102 return TokError(Twine(IDVal) +
2103 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00002104 case DK_DS:
2105 case DK_DS_W:
2106 return parseDirectiveDS(IDVal, 2);
2107 case DK_DS_B:
2108 return parseDirectiveDS(IDVal, 1);
2109 case DK_DS_D:
2110 return parseDirectiveDS(IDVal, 8);
2111 case DK_DS_L:
2112 case DK_DS_S:
2113 return parseDirectiveDS(IDVal, 4);
2114 case DK_DS_P:
2115 case DK_DS_X:
2116 return parseDirectiveDS(IDVal, 12);
Coby Tayree01e53202017-10-02 14:36:31 +00002117 case DK_PRINT:
2118 return parseDirectivePrint(IDLoc);
Eli Friedman20b02642010-07-19 04:17:25 +00002119 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002120
Jim Grosbach758e0cc2012-05-01 18:38:27 +00002121 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00002122 }
Chris Lattner36e02122009-06-21 20:54:55 +00002123
Chad Rosierc7f552c2013-02-12 21:33:51 +00002124 // __asm _emit or __asm __emit
2125 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
2126 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002127 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00002128
2129 // __asm align
2130 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002131 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00002132
Coby Tayree3847be92017-04-04 17:57:23 +00002133 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
Michael Zuckerman02ecd432015-12-13 17:07:23 +00002134 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00002135 if (checkForValidSection())
2136 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00002137
Chris Lattner7cbfa442010-05-19 23:34:33 +00002138 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00002139 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00002140 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00002141 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
2142 Info.ParsedOperands);
2143 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00002144
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002145 // Dump the parsed representation, if requested.
2146 if (getShowParsedOperands()) {
2147 SmallString<256> Str;
2148 raw_svector_ostream OS(Str);
2149 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002150 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002151 if (i != 0)
2152 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002153 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002154 }
2155 OS << "]";
2156
Jim Grosbach4b905842013-09-20 23:08:21 +00002157 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002158 }
2159
Nirav Dave2364748a2016-09-16 18:30:20 +00002160 // Fail even if ParseInstruction erroneously returns false.
2161 if (hasPendingError() || ParseHadError)
2162 return true;
2163
Oliver Stannard8b273082014-06-19 15:52:37 +00002164 // If we are generating dwarf for the current section then generate a .loc
2165 // directive for the instruction.
Paul Robinson938d9a02018-03-22 15:48:01 +00002166 if (!ParseHadError && enabledGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002167 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002168 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002169 unsigned Line;
2170 if (ActiveMacros.empty())
2171 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2172 else
Frederic Riss16238d92015-06-25 21:57:33 +00002173 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2174 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002175
Eli Bendersky88024712013-01-16 19:32:36 +00002176 // If we previously parsed a cpp hash file line comment then make sure the
2177 // current Dwarf File is for the CppHashFilename if not then emit the
2178 // Dwarf File table for it and adjust the line number for the .loc.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00002179 if (!CppHashInfo.Filename.empty()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002180 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002181 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002182 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002183
Graydon Hoare54fe2082018-04-07 00:44:02 +00002184 unsigned CppHashLocLineNo =
2185 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Tim Northoverc0bef992016-04-13 19:46:54 +00002186 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002187 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002188
Jim Grosbach4b905842013-09-20 23:08:21 +00002189 getStreamer().EmitDwarfLocDirective(
2190 getContext().getGenDwarfFileNumber(), Line, 0,
2191 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2192 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002193 }
2194
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002195 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002196 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002197 uint64_t ErrorInfo;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00002198 if (getTargetParser().MatchAndEmitInstruction(
2199 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2200 getTargetParser().isParsingInlineAsm()))
Nirav Dave2364748a2016-09-16 18:30:20 +00002201 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002202 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002203 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002204}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002205
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002206// Parse and erase curly braces marking block start/end
2207bool
2208AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2209 // Identify curly brace marking block start/end
2210 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2211 return false;
2212
2213 SMLoc StartLoc = Lexer.getLoc();
2214 Lex(); // Eat the brace
2215 if (Lexer.is(AsmToken::EndOfStatement))
2216 Lex(); // Eat EndOfStatement following the brace
2217
2218 // Erase the block start/end brace from the output asm string
2219 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2220 StartLoc.getPointer());
2221 return true;
2222}
2223
Jim Grosbach4b905842013-09-20 23:08:21 +00002224/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002225/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002226bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002227 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002228 // Lexer only ever emits HashDirective if it fully formed if it's
2229 // done the checking already so this is an internal error.
2230 assert(getTok().is(AsmToken::Integer) &&
2231 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002232 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002233 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002234 assert(getTok().is(AsmToken::String) &&
2235 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002236 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002237 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002238
Kevin Enderby72553612011-09-13 23:45:18 +00002239 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002240 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002241
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002242 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002243 CppHashInfo.Loc = L;
2244 CppHashInfo.Filename = Filename;
2245 CppHashInfo.LineNumber = LineNumber;
2246 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002247 return false;
2248}
2249
Jim Grosbach4b905842013-09-20 23:08:21 +00002250/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002251/// for the Filename and LineNo if any in the diagnostic.
2252void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002253 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002254 raw_ostream &OS = errs();
2255
2256 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002257 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002258 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2259 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002260 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002261
Jim Grosbach4b905842013-09-20 23:08:21 +00002262 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002263 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002264 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2265 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2266 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002267 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2268 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002269 }
2270
Eric Christophera7c32732012-12-18 00:30:54 +00002271 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002272 // manager changed or buffer changed (like in a nested include) then just
2273 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002274 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002275 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002276 if (Parser->SavedDiagHandler)
2277 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2278 else
Craig Topper353eda42014-04-24 06:44:33 +00002279 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002280 return;
2281 }
2282
Eric Christophera7c32732012-12-18 00:30:54 +00002283 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002284 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2285 // for the diagnostic.
2286 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002287
2288 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2289 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002290 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002291 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002292 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002293
Jim Grosbach4b905842013-09-20 23:08:21 +00002294 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2295 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002296 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002297
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002298 if (Parser->SavedDiagHandler)
2299 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2300 else
Craig Topper353eda42014-04-24 06:44:33 +00002301 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002302}
2303
Rafael Espindola2c064482012-08-21 18:29:30 +00002304// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2305// difference being that that function accepts '@' as part of identifiers and
2306// we can't do that. AsmLexer.cpp should probably be changed to handle
2307// '@' as a special case when needed.
2308static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002309 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2310 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002311}
2312
Rafael Espindola34b9c512012-06-03 23:57:14 +00002313bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002314 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002315 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002316 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002317 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002318 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002319 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002320 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002321
Preston Gurd05500642012-09-19 20:36:12 +00002322 // A macro without parameters is handled differently on Darwin:
2323 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002324 while (!Body.empty()) {
2325 // Scan for the next substitution.
2326 std::size_t End = Body.size(), Pos = 0;
2327 for (; Pos != End; ++Pos) {
2328 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002329 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002330 // This macro has no parameters, look for $0, $1, etc.
2331 if (Body[Pos] != '$' || Pos + 1 == End)
2332 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002333
Rafael Espindola1134ab232011-06-05 02:43:45 +00002334 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002335 if (Next == '$' || Next == 'n' ||
2336 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002337 break;
2338 } else {
2339 // This macro has parameters, look for \foo, \bar, etc.
2340 if (Body[Pos] == '\\' && Pos + 1 != End)
2341 break;
2342 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002343 }
2344
2345 // Add the prefix.
2346 OS << Body.slice(0, Pos);
2347
2348 // Check if we reached the end.
2349 if (Pos == End)
2350 break;
2351
Benjamin Kramer513e7442014-02-20 13:36:32 +00002352 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002353 switch (Body[Pos + 1]) {
2354 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002355 case '$':
2356 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002357 break;
2358
Jim Grosbach4b905842013-09-20 23:08:21 +00002359 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002360 case 'n':
2361 OS << A.size();
2362 break;
2363
Jim Grosbach4b905842013-09-20 23:08:21 +00002364 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002365 default: {
2366 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002367 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002368 if (Index >= A.size())
2369 break;
2370
2371 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002372 for (const AsmToken &Token : A[Index])
2373 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002374 break;
2375 }
2376 }
2377 Pos += 2;
2378 } else {
2379 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002380
2381 // Check for the \@ pseudo-variable.
2382 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002383 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002384 else
2385 while (isIdentifierChar(Body[I]) && I + 1 != End)
2386 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002387
Jim Grosbach4b905842013-09-20 23:08:21 +00002388 const char *Begin = Body.data() + Pos + 1;
2389 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002390 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002391
Toma Tabacu217116e2015-04-27 10:50:29 +00002392 if (Argument == "@") {
2393 OS << NumOfMacroInstantiations;
2394 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002395 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002396 for (; Index < NParameters; ++Index)
2397 if (Parameters[Index].Name == Argument)
2398 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002399
Toma Tabacu217116e2015-04-27 10:50:29 +00002400 if (Index == NParameters) {
2401 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2402 Pos += 3;
2403 else {
2404 OS << '\\' << Argument;
2405 Pos = I;
2406 }
2407 } else {
2408 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002409 for (const AsmToken &Token : A[Index])
Michael Zuckerman56704612017-05-01 13:20:12 +00002410 // For altmacro mode, you can write '%expr'.
2411 // The prefix '%' evaluates the expression 'expr'
2412 // and uses the result as a string (e.g. replace %(1+2) with the string "3").
2413 // Here, we identify the integer token which is the result of the
2414 // absolute expression evaluation and replace it with its string representation.
2415 if ((Lexer.IsaAltMacroMode()) &&
2416 (*(Token.getString().begin()) == '%') && Token.is(AsmToken::Integer))
2417 // Emit an integer value to the buffer.
2418 OS << Token.getIntVal();
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002419 // Only Token that was validated as a string and begins with '<'
2420 // is considered altMacroString!!!
2421 else if ((Lexer.IsaAltMacroMode()) &&
2422 (*(Token.getString().begin()) == '<') &&
2423 Token.is(AsmToken::String)) {
2424 std::string Res;
2425 altMacroString(Token.getStringContents(), Res);
2426 OS << Res;
2427 }
Toma Tabacu217116e2015-04-27 10:50:29 +00002428 // We expect no quotes around the string's contents when
2429 // parsing for varargs.
Michael Zuckerman56704612017-05-01 13:20:12 +00002430 else if (Token.isNot(AsmToken::String) || VarargParameter)
Craig Topper84008482015-10-10 05:38:14 +00002431 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002432 else
Craig Topper84008482015-10-10 05:38:14 +00002433 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002434
2435 Pos += 1 + Argument.size();
2436 }
Preston Gurd05500642012-09-19 20:36:12 +00002437 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002438 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002439 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002440 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002441 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002442
Rafael Espindola1134ab232011-06-05 02:43:45 +00002443 return false;
2444}
Daniel Dunbar43235712010-07-18 18:54:11 +00002445
Nico Weber2a8f9222014-07-24 16:29:04 +00002446MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002447 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002448 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002449 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002450
Jim Grosbach4b905842013-09-20 23:08:21 +00002451static bool isOperator(AsmToken::TokenKind kind) {
2452 switch (kind) {
2453 default:
2454 return false;
2455 case AsmToken::Plus:
2456 case AsmToken::Minus:
2457 case AsmToken::Tilde:
2458 case AsmToken::Slash:
2459 case AsmToken::Star:
2460 case AsmToken::Dot:
2461 case AsmToken::Equal:
2462 case AsmToken::EqualEqual:
2463 case AsmToken::Pipe:
2464 case AsmToken::PipePipe:
2465 case AsmToken::Caret:
2466 case AsmToken::Amp:
2467 case AsmToken::AmpAmp:
2468 case AsmToken::Exclaim:
2469 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002470 case AsmToken::Less:
2471 case AsmToken::LessEqual:
2472 case AsmToken::LessLess:
2473 case AsmToken::LessGreater:
2474 case AsmToken::Greater:
2475 case AsmToken::GreaterEqual:
2476 case AsmToken::GreaterGreater:
2477 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002478 }
2479}
2480
David Majnemer16252452014-01-29 00:07:39 +00002481namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002482
David Majnemer16252452014-01-29 00:07:39 +00002483class AsmLexerSkipSpaceRAII {
2484public:
2485 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2486 Lexer.setSkipSpace(SkipSpace);
2487 }
2488
2489 ~AsmLexerSkipSpaceRAII() {
2490 Lexer.setSkipSpace(true);
2491 }
2492
2493private:
2494 AsmLexer &Lexer;
2495};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002496
2497} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002498
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002499bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2500
2501 if (Vararg) {
2502 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2503 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002504 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002505 }
2506 return false;
2507 }
2508
Rafael Espindola768b41c2012-06-15 14:02:34 +00002509 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002510
David Majnemer16252452014-01-29 00:07:39 +00002511 // Darwin doesn't use spaces to delmit arguments.
2512 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002513
Scott Egertona1fa68a2016-02-11 13:48:49 +00002514 bool SpaceEaten;
2515
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002516 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002517 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002518 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002519 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002520
Scott Egertona1fa68a2016-02-11 13:48:49 +00002521 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002522
Scott Egertona1fa68a2016-02-11 13:48:49 +00002523 if (Lexer.is(AsmToken::Comma))
2524 break;
2525
2526 if (Lexer.is(AsmToken::Space)) {
2527 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002528 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002529 }
Preston Gurd05500642012-09-19 20:36:12 +00002530
2531 // Spaces can delimit parameters, but could also be part an expression.
2532 // If the token after a space is an operator, add the token and the next
2533 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002534 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002535 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002536 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002537 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002538
Scott Egertona1fa68a2016-02-11 13:48:49 +00002539 // Whitespace after an operator can be ignored.
2540 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002541 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002542
2543 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002544 }
2545 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002546 if (SpaceEaten)
2547 break;
Preston Gurd05500642012-09-19 20:36:12 +00002548 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002549
Jim Grosbach4b905842013-09-20 23:08:21 +00002550 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002551 // to be able to fill in the remaining default parameter values
2552 if (Lexer.is(AsmToken::EndOfStatement))
2553 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002554
2555 // Adjust the current parentheses level.
2556 if (Lexer.is(AsmToken::LParen))
2557 ++ParenLevel;
2558 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2559 --ParenLevel;
2560
2561 // Append the token to the current argument list.
2562 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002563 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002564 }
Preston Gurd05500642012-09-19 20:36:12 +00002565
Rafael Espindola768b41c2012-06-15 14:02:34 +00002566 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002567 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002568 return false;
2569}
2570
2571// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002572bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002573 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002574 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002575 bool NamedParametersFound = false;
2576 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002577
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002578 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002579 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002580
Rafael Espindola768b41c2012-06-15 14:02:34 +00002581 // Parse two kinds of macro invocations:
2582 // - macros defined without any parameters accept an arbitrary number of them
2583 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002584 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002585 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2586 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002587 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002588 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002589
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002590 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002591 if (parseIdentifier(FA.Name))
2592 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002593
Nirav Dave2364748a2016-09-16 18:30:20 +00002594 if (Lexer.isNot(AsmToken::Equal))
2595 return TokError("expected '=' after formal parameter identifier");
2596
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002597 Lex();
2598
2599 NamedParametersFound = true;
2600 }
Michael Zuckerman56704612017-05-01 13:20:12 +00002601 bool Vararg = HasVararg && Parameter == (NParameters - 1);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002602
Nirav Dave2364748a2016-09-16 18:30:20 +00002603 if (NamedParametersFound && FA.Name.empty())
2604 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002605
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002606 SMLoc StrLoc = Lexer.getLoc();
2607 SMLoc EndLoc;
Michael Zuckerman56704612017-05-01 13:20:12 +00002608 if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Percent)) {
Michael Zuckerman56704612017-05-01 13:20:12 +00002609 const MCExpr *AbsoluteExp;
2610 int64_t Value;
2611 /// Eat '%'
2612 Lex();
2613 if (parseExpression(AbsoluteExp, EndLoc))
2614 return false;
2615 if (!AbsoluteExp->evaluateAsAbsolute(Value))
2616 return Error(StrLoc, "expected absolute expression");
2617 const char *StrChar = StrLoc.getPointer();
2618 const char *EndChar = EndLoc.getPointer();
2619 AsmToken newToken(AsmToken::Integer, StringRef(StrChar , EndChar - StrChar), Value);
2620 FA.Value.push_back(newToken);
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002621 } else if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Less) &&
2622 isAltmacroString(StrLoc, EndLoc)) {
2623 const char *StrChar = StrLoc.getPointer();
2624 const char *EndChar = EndLoc.getPointer();
2625 jumpToLoc(EndLoc, CurBuffer);
2626 /// Eat from '<' to '>'
2627 Lex();
2628 AsmToken newToken(AsmToken::String, StringRef(StrChar, EndChar - StrChar));
2629 FA.Value.push_back(newToken);
2630 } else if(parseMacroArgument(FA.Value, Vararg))
Michael Zuckerman56704612017-05-01 13:20:12 +00002631 return true;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002632
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002633 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002634 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002635 unsigned FAI = 0;
2636 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002637 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002638 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002639
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002640 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002641 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002642 return Error(IDLoc, "parameter named '" + FA.Name +
2643 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002644 }
2645 PI = FAI;
2646 }
2647
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002648 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002649 if (A.size() <= PI)
2650 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002651 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002652
2653 if (FALocs.size() <= PI)
2654 FALocs.resize(PI + 1);
2655
2656 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002657 }
Jim Grosbach206661622012-07-30 22:44:17 +00002658
Preston Gurd242ed3152012-09-19 20:29:04 +00002659 // At the end of the statement, fill in remaining arguments that have
2660 // default values. If there aren't any, then the next argument is
2661 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002662 if (Lexer.is(AsmToken::EndOfStatement)) {
2663 bool Failure = false;
2664 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2665 if (A[FAI].empty()) {
2666 if (M->Parameters[FAI].Required) {
2667 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2668 "missing value for required parameter "
2669 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2670 Failure = true;
2671 }
2672
2673 if (!M->Parameters[FAI].Value.empty())
2674 A[FAI] = M->Parameters[FAI].Value;
2675 }
2676 }
2677 return Failure;
2678 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002679
2680 if (Lexer.is(AsmToken::Comma))
2681 Lex();
2682 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002683
2684 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002685}
2686
Jim Grosbach4b905842013-09-20 23:08:21 +00002687bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002688 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2689 // eliminate this, although we should protect against infinite loops.
2690 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2691 if (ActiveMacros.size() == MaxNestingDepth) {
2692 std::ostringstream MaxNestingDepthError;
2693 MaxNestingDepthError << "macros cannot be nested more than "
2694 << MaxNestingDepth << " levels deep."
2695 << " Use -asm-macro-max-nesting-depth to increase "
2696 "this limit.";
2697 return TokError(MaxNestingDepthError.str());
2698 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002699
Eli Bendersky38274122013-01-14 23:22:36 +00002700 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002701 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002702 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002703
Rafael Espindola1134ab232011-06-05 02:43:45 +00002704 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2705 // to hold the macro body with substitutions.
2706 SmallString<256> Buf;
2707 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002708 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002709
Toma Tabacu217116e2015-04-27 10:50:29 +00002710 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002711 return true;
2712
Eli Bendersky38274122013-01-14 23:22:36 +00002713 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002714 // instantiation.
2715 OS << ".endmacro\n";
2716
Rafael Espindola3560ff22014-08-27 20:03:13 +00002717 std::unique_ptr<MemoryBuffer> Instantiation =
2718 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002719
Daniel Dunbar43235712010-07-18 18:54:11 +00002720 // Create the macro instantiation object and add to the current macro
2721 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002722 MacroInstantiation *MI = new MacroInstantiation(
2723 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002724 ActiveMacros.push_back(MI);
2725
Toma Tabacu217116e2015-04-27 10:50:29 +00002726 ++NumOfMacroInstantiations;
2727
Daniel Dunbar43235712010-07-18 18:54:11 +00002728 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002729 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002730 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002731 Lex();
2732
2733 return false;
2734}
2735
Jim Grosbach4b905842013-09-20 23:08:21 +00002736void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002737 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002738 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002739 Lex();
2740
2741 // Pop the instantiation entry.
2742 delete ActiveMacros.back();
2743 ActiveMacros.pop_back();
2744}
2745
Jim Grosbach4b905842013-09-20 23:08:21 +00002746bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002747 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002748 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002749 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002750 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2751 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002752 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002753
Pete Cooper80d21cb2015-06-22 19:35:57 +00002754 if (!Sym) {
2755 // In the case where we parse an expression starting with a '.', we will
2756 // not generate an error, nor will we create a symbol. In this case we
2757 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002758 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002759 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002760
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002761 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002762 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002763 if (NoDeadStrip)
2764 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2765
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002766 return false;
2767}
2768
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002769/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002770/// ::= identifier
2771/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002772bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002773 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002774 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2775 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002776 // handle this as a context dependent token, instead we detect adjacent tokens
2777 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002778 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2779 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002780
Hans Wennborgce69d772013-10-18 20:46:28 +00002781 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002782
2783 AsmToken Buf[1];
2784 Lexer.peekTokens(Buf, false);
2785
2786 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002787 return true;
2788
Hans Wennborgce69d772013-10-18 20:46:28 +00002789 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002790 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002791 return true;
2792
Nirav Daved0463322016-10-12 13:58:07 +00002793 // eat $ or @
2794 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002795 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002796 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002797 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002798 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002799 return false;
2800 }
2801
Jim Grosbach4b905842013-09-20 23:08:21 +00002802 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002803 return true;
2804
Sean Callanan936b0d32010-01-19 21:44:56 +00002805 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002806
Sean Callanan686ed8d2010-01-19 20:22:31 +00002807 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002808
2809 return false;
2810}
2811
Jim Grosbach4b905842013-09-20 23:08:21 +00002812/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002813/// ::= .equ identifier ',' expression
2814/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002815/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002816bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002817 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002818 if (check(parseIdentifier(Name), "expected identifier") ||
2819 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2820 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2821 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002822}
2823
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002824bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002825 if (check(getTok().isNot(AsmToken::String), "expected string"))
2826 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002827
2828 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002829 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002830 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2831 if (Str[i] != '\\') {
2832 Data += Str[i];
2833 continue;
2834 }
2835
2836 // Recognize escaped characters. Note that this escape semantics currently
2837 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2838 ++i;
2839 if (i == e)
2840 return TokError("unexpected backslash at end of string");
2841
2842 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002843 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002844 // Consume up to three octal characters.
2845 unsigned Value = Str[i] - '0';
2846
Jim Grosbach4b905842013-09-20 23:08:21 +00002847 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002848 ++i;
2849 Value = Value * 8 + (Str[i] - '0');
2850
Jim Grosbach4b905842013-09-20 23:08:21 +00002851 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002852 ++i;
2853 Value = Value * 8 + (Str[i] - '0');
2854 }
2855 }
2856
2857 if (Value > 255)
2858 return TokError("invalid octal escape sequence (out of range)");
2859
Jim Grosbach4b905842013-09-20 23:08:21 +00002860 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002861 continue;
2862 }
2863
2864 // Otherwise recognize individual escapes.
2865 switch (Str[i]) {
2866 default:
2867 // Just reject invalid escape sequences for now.
2868 return TokError("invalid escape sequence (unrecognized character)");
2869
2870 case 'b': Data += '\b'; break;
2871 case 'f': Data += '\f'; break;
2872 case 'n': Data += '\n'; break;
2873 case 'r': Data += '\r'; break;
2874 case 't': Data += '\t'; break;
2875 case '"': Data += '"'; break;
2876 case '\\': Data += '\\'; break;
2877 }
2878 }
2879
Nirav Davea645433c2016-07-18 15:24:03 +00002880 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002881 return false;
2882}
2883
Jim Grosbach4b905842013-09-20 23:08:21 +00002884/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002885/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002886bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002887 auto parseOp = [&]() -> bool {
2888 std::string Data;
2889 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002890 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002891 getStreamer().EmitBytes(Data);
2892 if (ZeroTerminated)
2893 getStreamer().EmitBytes(StringRef("\0", 1));
2894 return false;
2895 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002896
Nirav Dave1a9044b2016-10-24 14:35:29 +00002897 if (parseMany(parseOp))
2898 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002899 return false;
2900}
2901
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002902/// parseDirectiveReloc
2903/// ::= .reloc expression , identifier [ , expression ]
2904bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2905 const MCExpr *Offset;
2906 const MCExpr *Expr = nullptr;
2907
2908 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00002909 int64_t OffsetValue;
2910 // We can only deal with constant expressions at the moment.
2911
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002912 if (parseExpression(Offset))
2913 return true;
2914
Nirav Davea645433c2016-07-18 15:24:03 +00002915 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2916 "expression is not a constant value") ||
2917 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2918 parseToken(AsmToken::Comma, "expected comma") ||
2919 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2920 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002921
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002922 SMLoc NameLoc = Lexer.getTok().getLoc();
2923 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002924 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002925
2926 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002927 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002928 SMLoc ExprLoc = Lexer.getLoc();
2929 if (parseExpression(Expr))
2930 return true;
2931
2932 MCValue Value;
2933 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2934 return Error(ExprLoc, "expression must be relocatable");
2935 }
2936
Nirav Davea645433c2016-07-18 15:24:03 +00002937 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002938 "unexpected token in .reloc directive"))
2939 return true;
2940
2941 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2942 return Error(NameLoc, "unknown relocation name");
2943
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002944 return false;
2945}
2946
Jim Grosbach4b905842013-09-20 23:08:21 +00002947/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002948/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002949bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2950 auto parseOp = [&]() -> bool {
2951 const MCExpr *Value;
2952 SMLoc ExprLoc = getLexer().getLoc();
2953 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002954 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002955 // Special case constant expressions to match code generator.
2956 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2957 assert(Size <= 8 && "Invalid size");
2958 uint64_t IntValue = MCE->getValue();
2959 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2960 return Error(ExprLoc, "out of range literal value");
2961 getStreamer().EmitIntValue(IntValue, Size);
2962 } else
2963 getStreamer().EmitValue(Value, Size, ExprLoc);
2964 return false;
2965 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002966
Nirav Dave1a9044b2016-10-24 14:35:29 +00002967 if (parseMany(parseOp))
2968 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002969 return false;
2970}
2971
Paul Robinson01954692018-04-11 15:14:05 +00002972static bool parseHexOcta(AsmParser &Asm, uint64_t &hi, uint64_t &lo) {
2973 if (Asm.getTok().isNot(AsmToken::Integer) &&
2974 Asm.getTok().isNot(AsmToken::BigNum))
2975 return Asm.TokError("unknown token in expression");
2976 SMLoc ExprLoc = Asm.getTok().getLoc();
2977 APInt IntValue = Asm.getTok().getAPIntVal();
2978 Asm.Lex();
2979 if (!IntValue.isIntN(128))
2980 return Asm.Error(ExprLoc, "out of range literal value");
2981 if (!IntValue.isIntN(64)) {
2982 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2983 lo = IntValue.getLoBits(64).getZExtValue();
2984 } else {
2985 hi = 0;
2986 lo = IntValue.getZExtValue();
2987 }
2988 return false;
2989}
2990
David Woodhoused6de0d92014-02-01 16:20:59 +00002991/// ParseDirectiveOctaValue
2992/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002993
2994bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
2995 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00002996 if (checkForValidSection())
2997 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002998 uint64_t hi, lo;
Paul Robinson01954692018-04-11 15:14:05 +00002999 if (parseHexOcta(*this, hi, lo))
3000 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003001 if (MAI.isLittleEndian()) {
3002 getStreamer().EmitIntValue(lo, 8);
3003 getStreamer().EmitIntValue(hi, 8);
3004 } else {
3005 getStreamer().EmitIntValue(hi, 8);
3006 getStreamer().EmitIntValue(lo, 8);
3007 }
3008 return false;
3009 };
David Woodhoused6de0d92014-02-01 16:20:59 +00003010
Nirav Dave1a9044b2016-10-24 14:35:29 +00003011 if (parseMany(parseOp))
3012 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00003013 return false;
3014}
3015
Petr Hosek4cb08ce2016-09-23 19:25:15 +00003016bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
3017 // We don't truly support arithmetic on floating point expressions, so we
3018 // have to manually parse unary prefixes.
3019 bool IsNeg = false;
3020 if (getLexer().is(AsmToken::Minus)) {
3021 Lexer.Lex();
3022 IsNeg = true;
3023 } else if (getLexer().is(AsmToken::Plus))
3024 Lexer.Lex();
3025
3026 if (Lexer.is(AsmToken::Error))
3027 return TokError(Lexer.getErr());
3028 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
3029 Lexer.isNot(AsmToken::Identifier))
3030 return TokError("unexpected token in directive");
3031
3032 // Convert to an APFloat.
3033 APFloat Value(Semantics);
3034 StringRef IDVal = getTok().getString();
3035 if (getLexer().is(AsmToken::Identifier)) {
3036 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
3037 Value = APFloat::getInf(Semantics);
3038 else if (!IDVal.compare_lower("nan"))
3039 Value = APFloat::getNaN(Semantics, false, ~0);
3040 else
3041 return TokError("invalid floating point literal");
3042 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
3043 APFloat::opInvalidOp)
3044 return TokError("invalid floating point literal");
3045 if (IsNeg)
3046 Value.changeSign();
3047
3048 // Consume the numeric token.
3049 Lex();
3050
3051 Res = Value.bitcastToAPInt();
3052
3053 return false;
3054}
3055
Jim Grosbach4b905842013-09-20 23:08:21 +00003056/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00003057/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003058bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
3059 const fltSemantics &Semantics) {
3060 auto parseOp = [&]() -> bool {
3061 APInt AsInt;
3062 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00003063 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003064 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
3065 AsInt.getBitWidth() / 8);
3066 return false;
3067 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00003068
Nirav Dave1a9044b2016-10-24 14:35:29 +00003069 if (parseMany(parseOp))
3070 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00003071 return false;
3072}
3073
Jim Grosbach4b905842013-09-20 23:08:21 +00003074/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00003075/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003076bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003077 SMLoc NumBytesLoc = Lexer.getLoc();
3078 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003079 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00003080 return true;
3081
Rafael Espindolab91bac62010-10-05 19:42:57 +00003082 int64_t Val = 0;
3083 if (getLexer().is(AsmToken::Comma)) {
3084 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003085 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00003086 return true;
3087 }
3088
Nirav Davea645433c2016-07-18 15:24:03 +00003089 if (parseToken(AsmToken::EndOfStatement,
3090 "unexpected token in '.zero' directive"))
3091 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00003092 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00003093
3094 return false;
3095}
3096
Jim Grosbach4b905842013-09-20 23:08:21 +00003097/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00003098/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003099bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003100 SMLoc NumValuesLoc = Lexer.getLoc();
3101 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003102 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00003103 return true;
3104
Roman Divackye33098f2013-09-24 17:44:41 +00003105 int64_t FillSize = 1;
3106 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00003107
David Majnemer522d3db2014-02-01 07:19:38 +00003108 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003109
Nirav Dave1a9044b2016-10-24 14:35:29 +00003110 if (parseOptionalToken(AsmToken::Comma)) {
3111 SizeLoc = getTok().getLoc();
3112 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00003113 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003114 if (parseOptionalToken(AsmToken::Comma)) {
3115 ExprLoc = getTok().getLoc();
3116 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00003117 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00003118 }
3119 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003120 if (parseToken(AsmToken::EndOfStatement,
3121 "unexpected token in '.fill' directive"))
3122 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003123
David Majnemer522d3db2014-02-01 07:19:38 +00003124 if (FillSize < 0) {
3125 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00003126 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00003127 }
3128 if (FillSize > 8) {
3129 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
3130 FillSize = 8;
3131 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00003132
David Majnemer522d3db2014-02-01 07:19:38 +00003133 if (!isUInt<32>(FillExpr) && FillSize > 4)
3134 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
3135
Petr Hosek67a94a72016-05-28 05:57:48 +00003136 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00003137
3138 return false;
3139}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003140
Jim Grosbach4b905842013-09-20 23:08:21 +00003141/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003142/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003143bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00003144 const MCExpr *Offset;
Oliver Stannard268f42f2016-12-14 10:43:58 +00003145 SMLoc OffsetLoc = Lexer.getLoc();
Nirav Davef43cc9f2016-10-10 15:24:54 +00003146 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003147 return true;
3148
3149 // Parse optional fill expression.
3150 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003151 if (parseOptionalToken(AsmToken::Comma))
3152 if (parseAbsoluteExpression(FillExpr))
3153 return addErrorSuffix(" in '.org' directive");
3154 if (parseToken(AsmToken::EndOfStatement))
3155 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00003156
Oliver Stannard268f42f2016-12-14 10:43:58 +00003157 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003158 return false;
3159}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003160
Jim Grosbach4b905842013-09-20 23:08:21 +00003161/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003162/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00003163bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003164 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003165 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003166 SMLoc MaxBytesLoc;
3167 bool HasFillExpr = false;
3168 int64_t FillExpr = 0;
3169 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003170
3171 auto parseAlign = [&]() -> bool {
Coby Tayreed483a102017-08-02 17:36:10 +00003172 if (parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00003173 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003174 if (parseOptionalToken(AsmToken::Comma)) {
3175 // The fill expression can be omitted while specifying a maximum number of
3176 // alignment bytes, e.g:
3177 // .align 3,,4
3178 if (getTok().isNot(AsmToken::Comma)) {
3179 HasFillExpr = true;
3180 if (parseAbsoluteExpression(FillExpr))
3181 return true;
3182 }
3183 if (parseOptionalToken(AsmToken::Comma))
3184 if (parseTokenLoc(MaxBytesLoc) ||
3185 parseAbsoluteExpression(MaxBytesToFill))
3186 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003187 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003188 return parseToken(AsmToken::EndOfStatement);
3189 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003190
Coby Tayreed483a102017-08-02 17:36:10 +00003191 if (checkForValidSection())
3192 return addErrorSuffix(" in directive");
3193 // Ignore empty '.p2align' directives for GNU-as compatibility
3194 if (IsPow2 && (ValueSize == 1) && getTok().is(AsmToken::EndOfStatement)) {
3195 Warning(AlignmentLoc, "p2align directive with no operand(s) is ignored");
3196 return parseToken(AsmToken::EndOfStatement);
3197 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003198 if (parseAlign())
3199 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003200
Nirav Dave2364748a2016-09-16 18:30:20 +00003201 // Always emit an alignment here even if we thrown an error.
3202 bool ReturnVal = false;
3203
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003204 // Compute alignment in bytes.
3205 if (IsPow2) {
3206 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003207 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003208 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003209 Alignment = 31;
3210 }
3211
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003212 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003213 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003214 // Reject alignments that aren't either a power of two or zero,
3215 // for gas compatibility. Alignment of zero is silently rounded
3216 // up to one.
3217 if (Alignment == 0)
3218 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003219 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003220 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003221 }
3222
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003223 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003224 if (MaxBytesLoc.isValid()) {
3225 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003226 ReturnVal |= Error(MaxBytesLoc,
3227 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003228 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003229 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003230 }
3231
3232 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003233 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003234 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003235 MaxBytesToFill = 0;
3236 }
3237 }
3238
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003239 // Check whether we should use optimal code alignment for this .align
3240 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003241 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003242 assert(Section && "must have section to emit alignment");
3243 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003244 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3245 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003246 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003247 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003248 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003249 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3250 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003251 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003252
Nirav Dave2364748a2016-09-16 18:30:20 +00003253 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003254}
3255
Jim Grosbach4b905842013-09-20 23:08:21 +00003256/// parseDirectiveFile
Paul Robinson29f5f982018-01-09 23:31:48 +00003257/// ::= .file filename
Scott Linder16c7bda2018-02-23 23:01:06 +00003258/// ::= .file number [directory] filename [md5 checksum] [source source-text]
Jim Grosbach4b905842013-09-20 23:08:21 +00003259bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003260 // FIXME: I'm not sure what this is.
3261 int64_t FileNumber = -1;
Eli Bendersky17233942013-01-15 22:59:42 +00003262 if (getLexer().is(AsmToken::Integer)) {
3263 FileNumber = getTok().getIntVal();
3264 Lex();
3265
Paul Robinsonb271f312018-03-29 17:16:41 +00003266 if (FileNumber < 0)
3267 return TokError("negative file number");
Eli Bendersky17233942013-01-15 22:59:42 +00003268 }
3269
Nirav Davea645433c2016-07-18 15:24:03 +00003270 std::string Path = getTok().getString();
Eli Bendersky17233942013-01-15 22:59:42 +00003271
3272 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003273 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003274 if (check(getTok().isNot(AsmToken::String),
3275 "unexpected token in '.file' directive") ||
3276 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003277 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003278
3279 StringRef Directory;
3280 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003281 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003282 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003283 if (check(FileNumber == -1,
3284 "explicit path specified, but no file number") ||
3285 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003286 return true;
3287 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003288 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003289 } else {
3290 Filename = Path;
3291 }
3292
Paul Robinson01954692018-04-11 15:14:05 +00003293 uint64_t MD5Hi, MD5Lo;
3294 bool HasMD5 = false;
Scott Linder16c7bda2018-02-23 23:01:06 +00003295
3296 Optional<StringRef> Source;
3297 bool HasSource = false;
3298 std::string SourceString;
3299
3300 while (!parseOptionalToken(AsmToken::EndOfStatement)) {
Paul Robinson29f5f982018-01-09 23:31:48 +00003301 StringRef Keyword;
3302 if (check(getTok().isNot(AsmToken::Identifier),
3303 "unexpected token in '.file' directive") ||
Scott Linder16c7bda2018-02-23 23:01:06 +00003304 parseIdentifier(Keyword))
Paul Robinson29f5f982018-01-09 23:31:48 +00003305 return true;
Scott Linder16c7bda2018-02-23 23:01:06 +00003306 if (Keyword == "md5") {
Paul Robinson01954692018-04-11 15:14:05 +00003307 HasMD5 = true;
Scott Linder16c7bda2018-02-23 23:01:06 +00003308 if (check(FileNumber == -1,
3309 "MD5 checksum specified, but no file number") ||
Paul Robinson01954692018-04-11 15:14:05 +00003310 parseHexOcta(*this, MD5Hi, MD5Lo))
Scott Linder16c7bda2018-02-23 23:01:06 +00003311 return true;
3312 } else if (Keyword == "source") {
3313 HasSource = true;
3314 if (check(FileNumber == -1,
3315 "source specified, but no file number") ||
3316 check(getTok().isNot(AsmToken::String),
3317 "unexpected token in '.file' directive") ||
3318 parseEscapedString(SourceString))
3319 return true;
3320 } else {
3321 return TokError("unexpected token in '.file' directive");
3322 }
Paul Robinson29f5f982018-01-09 23:31:48 +00003323 }
Eli Bendersky17233942013-01-15 22:59:42 +00003324
Paul Robinson938d9a02018-03-22 15:48:01 +00003325 // In case there is a -g option as well as debug info from directive .file,
3326 // we turn off the -g option, directly use the existing debug info instead.
3327 getContext().setGenDwarfForAssembly(false);
3328
Eli Bendersky17233942013-01-15 22:59:42 +00003329 if (FileNumber == -1)
3330 getStreamer().EmitFileDirective(Filename);
3331 else {
Paul Robinson29f5f982018-01-09 23:31:48 +00003332 MD5::MD5Result *CKMem = nullptr;
Paul Robinson01954692018-04-11 15:14:05 +00003333 if (HasMD5) {
Paul Robinson29f5f982018-01-09 23:31:48 +00003334 CKMem = (MD5::MD5Result *)Ctx.allocate(sizeof(MD5::MD5Result), 1);
Paul Robinson01954692018-04-11 15:14:05 +00003335 for (unsigned i = 0; i != 8; ++i) {
3336 CKMem->Bytes[i] = uint8_t(MD5Hi >> ((7 - i) * 8));
3337 CKMem->Bytes[i + 8] = uint8_t(MD5Lo >> ((7 - i) * 8));
3338 }
Paul Robinson29f5f982018-01-09 23:31:48 +00003339 }
Scott Linder16c7bda2018-02-23 23:01:06 +00003340 if (HasSource) {
3341 char *SourceBuf = static_cast<char *>(Ctx.allocate(SourceString.size()));
3342 memcpy(SourceBuf, SourceString.data(), SourceString.size());
3343 Source = StringRef(SourceBuf, SourceString.size());
3344 }
Paul Robinsonb271f312018-03-29 17:16:41 +00003345 if (FileNumber == 0)
3346 getStreamer().emitDwarfFile0Directive(Directory, Filename, CKMem, Source);
3347 else {
3348 Expected<unsigned> FileNumOrErr = getStreamer().tryEmitDwarfFileDirective(
3349 FileNumber, Directory, Filename, CKMem, Source);
3350 if (!FileNumOrErr)
3351 return Error(DirectiveLoc, toString(FileNumOrErr.takeError()));
3352 FileNumber = FileNumOrErr.get();
3353 }
Eli Bendersky17233942013-01-15 22:59:42 +00003354 }
3355
3356 return false;
3357}
3358
Jim Grosbach4b905842013-09-20 23:08:21 +00003359/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003360/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003361bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003362 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003363 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003364 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3365 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003366 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003367 // FIXME: Do something with the .line.
3368 }
Nirav Davea645433c2016-07-18 15:24:03 +00003369 if (parseToken(AsmToken::EndOfStatement,
3370 "unexpected token in '.line' directive"))
3371 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003372
3373 return false;
3374}
3375
Jim Grosbach4b905842013-09-20 23:08:21 +00003376/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003377/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3378/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3379/// The first number is a file number, must have been previously assigned with
3380/// a .file directive, the second number is the line number and optionally the
3381/// third number is a column position (zero if not specified). The remaining
3382/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003383bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003384 int64_t FileNumber = 0, LineNumber = 0;
3385 SMLoc Loc = getTok().getLoc();
3386 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3387 check(FileNumber < 1, Loc,
3388 "file number less than one in '.loc' directive") ||
3389 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3390 "unassigned file number in '.loc' directive"))
3391 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003392
Nirav Davea645433c2016-07-18 15:24:03 +00003393 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003394 if (getLexer().is(AsmToken::Integer)) {
3395 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003396 if (LineNumber < 0)
3397 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003398 Lex();
3399 }
3400
3401 int64_t ColumnPos = 0;
3402 if (getLexer().is(AsmToken::Integer)) {
3403 ColumnPos = getTok().getIntVal();
3404 if (ColumnPos < 0)
3405 return TokError("column position less than zero in '.loc' directive");
3406 Lex();
3407 }
3408
3409 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3410 unsigned Isa = 0;
3411 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003412
Nirav Dave1a9044b2016-10-24 14:35:29 +00003413 auto parseLocOp = [&]() -> bool {
3414 StringRef Name;
3415 SMLoc Loc = getTok().getLoc();
3416 if (parseIdentifier(Name))
3417 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003418
Nirav Dave1a9044b2016-10-24 14:35:29 +00003419 if (Name == "basic_block")
3420 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3421 else if (Name == "prologue_end")
3422 Flags |= DWARF2_FLAG_PROLOGUE_END;
3423 else if (Name == "epilogue_begin")
3424 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3425 else if (Name == "is_stmt") {
3426 Loc = getTok().getLoc();
3427 const MCExpr *Value;
3428 if (parseExpression(Value))
3429 return true;
3430 // The expression must be the constant 0 or 1.
3431 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3432 int Value = MCE->getValue();
3433 if (Value == 0)
3434 Flags &= ~DWARF2_FLAG_IS_STMT;
3435 else if (Value == 1)
3436 Flags |= DWARF2_FLAG_IS_STMT;
3437 else
3438 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003439 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003440 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003441 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003442 } else if (Name == "isa") {
3443 Loc = getTok().getLoc();
3444 const MCExpr *Value;
3445 if (parseExpression(Value))
3446 return true;
3447 // The expression must be a constant greater or equal to 0.
3448 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3449 int Value = MCE->getValue();
3450 if (Value < 0)
3451 return Error(Loc, "isa number less than zero");
3452 Isa = Value;
3453 } else {
3454 return Error(Loc, "isa number not a constant value");
3455 }
3456 } else if (Name == "discriminator") {
3457 if (parseAbsoluteExpression(Discriminator))
3458 return true;
3459 } else {
3460 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003461 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003462 return false;
3463 };
3464
Nirav Davee2369aa2016-10-26 17:28:58 +00003465 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003466 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003467
3468 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3469 Isa, Discriminator, StringRef());
3470
3471 return false;
3472}
3473
Jim Grosbach4b905842013-09-20 23:08:21 +00003474/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003475/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003476bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003477 return TokError("unsupported directive '.stabs'");
3478}
3479
Reid Kleckner2214ed82016-01-29 00:49:42 +00003480/// parseDirectiveCVFile
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003481/// ::= .cv_file number filename [checksum] [checksumkind]
Reid Kleckner2214ed82016-01-29 00:49:42 +00003482bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003483 SMLoc FileNumberLoc = getTok().getLoc();
3484 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003485 std::string Filename;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003486 std::string Checksum;
3487 int64_t ChecksumKind = 0;
Nirav Davea645433c2016-07-18 15:24:03 +00003488
3489 if (parseIntToken(FileNumber,
3490 "expected file number in '.cv_file' directive") ||
3491 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3492 check(getTok().isNot(AsmToken::String),
3493 "unexpected token in '.cv_file' directive") ||
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003494 parseEscapedString(Filename))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003495 return true;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003496 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3497 if (check(getTok().isNot(AsmToken::String),
3498 "unexpected token in '.cv_file' directive") ||
3499 parseEscapedString(Checksum) ||
3500 parseIntToken(ChecksumKind,
3501 "expected checksum kind in '.cv_file' directive") ||
3502 parseToken(AsmToken::EndOfStatement,
3503 "unexpected token in '.cv_file' directive"))
3504 return true;
3505 }
Nirav Dave1ab71992016-07-18 19:35:21 +00003506
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003507 Checksum = fromHex(Checksum);
3508 void *CKMem = Ctx.allocate(Checksum.size(), 1);
3509 memcpy(CKMem, Checksum.data(), Checksum.size());
3510 ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem),
3511 Checksum.size());
3512
3513 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename, ChecksumAsBytes,
3514 static_cast<uint8_t>(ChecksumKind)))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003515 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003516
3517 return false;
3518}
3519
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003520bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3521 StringRef DirectiveName) {
3522 SMLoc Loc;
3523 return parseTokenLoc(Loc) ||
3524 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3525 "' directive") ||
3526 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3527 "expected function id within range [0, UINT_MAX)");
3528}
3529
3530bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3531 SMLoc Loc;
3532 return parseTokenLoc(Loc) ||
3533 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3534 "' directive") ||
3535 check(FileNumber < 1, Loc, "file number less than one in '" +
3536 DirectiveName + "' directive") ||
3537 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3538 "unassigned file number in '" + DirectiveName + "' directive");
3539}
3540
3541/// parseDirectiveCVFuncId
3542/// ::= .cv_func_id FunctionId
3543///
3544/// Introduces a function ID that can be used with .cv_loc.
3545bool AsmParser::parseDirectiveCVFuncId() {
3546 SMLoc FunctionIdLoc = getTok().getLoc();
3547 int64_t FunctionId;
3548
3549 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3550 parseToken(AsmToken::EndOfStatement,
3551 "unexpected token in '.cv_func_id' directive"))
3552 return true;
3553
3554 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003555 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003556
3557 return false;
3558}
3559
3560/// parseDirectiveCVInlineSiteId
3561/// ::= .cv_inline_site_id FunctionId
3562/// "within" IAFunc
3563/// "inlined_at" IAFile IALine [IACol]
3564///
3565/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3566/// at" source location information for use in the line table of the caller,
3567/// whether the caller is a real function or another inlined call site.
3568bool AsmParser::parseDirectiveCVInlineSiteId() {
3569 SMLoc FunctionIdLoc = getTok().getLoc();
3570 int64_t FunctionId;
3571 int64_t IAFunc;
3572 int64_t IAFile;
3573 int64_t IALine;
3574 int64_t IACol = 0;
3575
3576 // FunctionId
3577 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3578 return true;
3579
3580 // "within"
3581 if (check((getLexer().isNot(AsmToken::Identifier) ||
3582 getTok().getIdentifier() != "within"),
3583 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3584 return true;
3585 Lex();
3586
3587 // IAFunc
3588 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3589 return true;
3590
3591 // "inlined_at"
3592 if (check((getLexer().isNot(AsmToken::Identifier) ||
3593 getTok().getIdentifier() != "inlined_at"),
3594 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3595 "directive") )
3596 return true;
3597 Lex();
3598
3599 // IAFile IALine
3600 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3601 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3602 return true;
3603
3604 // [IACol]
3605 if (getLexer().is(AsmToken::Integer)) {
3606 IACol = getTok().getIntVal();
3607 Lex();
3608 }
3609
3610 if (parseToken(AsmToken::EndOfStatement,
3611 "unexpected token in '.cv_inline_site_id' directive"))
3612 return true;
3613
3614 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3615 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003616 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003617
3618 return false;
3619}
3620
Reid Kleckner2214ed82016-01-29 00:49:42 +00003621/// parseDirectiveCVLoc
3622/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3623/// [is_stmt VALUE]
3624/// The first number is a file number, must have been previously assigned with
3625/// a .file directive, the second number is the line number and optionally the
3626/// third number is a column position (zero if not specified). The remaining
3627/// optional items are .loc sub-directives.
3628bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003629 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003630 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003631 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3632 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003633 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003634
3635 int64_t LineNumber = 0;
3636 if (getLexer().is(AsmToken::Integer)) {
3637 LineNumber = getTok().getIntVal();
3638 if (LineNumber < 0)
3639 return TokError("line number less than zero in '.cv_loc' directive");
3640 Lex();
3641 }
3642
3643 int64_t ColumnPos = 0;
3644 if (getLexer().is(AsmToken::Integer)) {
3645 ColumnPos = getTok().getIntVal();
3646 if (ColumnPos < 0)
3647 return TokError("column position less than zero in '.cv_loc' directive");
3648 Lex();
3649 }
3650
3651 bool PrologueEnd = false;
3652 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003653
3654 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003655 StringRef Name;
3656 SMLoc Loc = getTok().getLoc();
3657 if (parseIdentifier(Name))
3658 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003659 if (Name == "prologue_end")
3660 PrologueEnd = true;
3661 else if (Name == "is_stmt") {
3662 Loc = getTok().getLoc();
3663 const MCExpr *Value;
3664 if (parseExpression(Value))
3665 return true;
3666 // The expression must be the constant 0 or 1.
3667 IsStmt = ~0ULL;
3668 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3669 IsStmt = MCE->getValue();
3670
3671 if (IsStmt > 1)
3672 return Error(Loc, "is_stmt value not 0 or 1");
3673 } else {
3674 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3675 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003676 return false;
3677 };
3678
3679 if (parseMany(parseOp, false /*hasComma*/))
3680 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003681
3682 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003683 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3684 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003685 return false;
3686}
3687
3688/// parseDirectiveCVLinetable
3689/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3690bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003691 int64_t FunctionId;
3692 StringRef FnStartName, FnEndName;
3693 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003694 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003695 parseToken(AsmToken::Comma,
3696 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003697 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3698 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003699 parseToken(AsmToken::Comma,
3700 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003701 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3702 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003703 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003704
3705 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3706 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3707
3708 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3709 return false;
3710}
3711
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003712/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003713/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003714bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003715 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3716 StringRef FnStartName, FnEndName;
3717 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003718 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003719 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003720 parseIntToken(
3721 SourceFileId,
3722 "expected SourceField in '.cv_inline_linetable' directive") ||
3723 check(SourceFileId <= 0, Loc,
3724 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003725 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003726 parseIntToken(
3727 SourceLineNum,
3728 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3729 check(SourceLineNum < 0, Loc,
3730 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003731 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3732 "expected identifier in directive") ||
3733 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3734 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003735 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003736
Nirav Davea645433c2016-07-18 15:24:03 +00003737 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3738 return true;
3739
3740 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3741 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003742 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3743 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003744 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003745 return false;
3746}
3747
David Majnemer408b5e62016-02-05 01:55:49 +00003748/// parseDirectiveCVDefRange
3749/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3750bool AsmParser::parseDirectiveCVDefRange() {
3751 SMLoc Loc;
3752 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3753 while (getLexer().is(AsmToken::Identifier)) {
3754 Loc = getLexer().getLoc();
3755 StringRef GapStartName;
3756 if (parseIdentifier(GapStartName))
3757 return Error(Loc, "expected identifier in directive");
3758 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3759
3760 Loc = getLexer().getLoc();
3761 StringRef GapEndName;
3762 if (parseIdentifier(GapEndName))
3763 return Error(Loc, "expected identifier in directive");
3764 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3765
3766 Ranges.push_back({GapStartSym, GapEndSym});
3767 }
3768
David Majnemer408b5e62016-02-05 01:55:49 +00003769 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003770 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3771 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003772 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003773
3774 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3775 return false;
3776}
3777
Reid Kleckner2214ed82016-01-29 00:49:42 +00003778/// parseDirectiveCVStringTable
3779/// ::= .cv_stringtable
3780bool AsmParser::parseDirectiveCVStringTable() {
3781 getStreamer().EmitCVStringTableDirective();
3782 return false;
3783}
3784
3785/// parseDirectiveCVFileChecksums
3786/// ::= .cv_filechecksums
3787bool AsmParser::parseDirectiveCVFileChecksums() {
3788 getStreamer().EmitCVFileChecksumsDirective();
3789 return false;
3790}
3791
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003792/// parseDirectiveCVFileChecksumOffset
3793/// ::= .cv_filechecksumoffset fileno
3794bool AsmParser::parseDirectiveCVFileChecksumOffset() {
3795 int64_t FileNo;
3796 if (parseIntToken(FileNo, "expected identifier in directive"))
3797 return true;
3798 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3799 return true;
3800 getStreamer().EmitCVFileChecksumOffsetDirective(FileNo);
3801 return false;
3802}
3803
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00003804/// parseDirectiveCVFPOData
3805/// ::= .cv_fpo_data procsym
3806bool AsmParser::parseDirectiveCVFPOData() {
3807 SMLoc DirLoc = getLexer().getLoc();
3808 StringRef ProcName;
3809 if (parseIdentifier(ProcName))
3810 return TokError("expected symbol name");
3811 if (parseEOL("unexpected tokens"))
3812 return addErrorSuffix(" in '.cv_fpo_data' directive");
3813 MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName);
3814 getStreamer().EmitCVFPOData(ProcSym, DirLoc);
3815 return false;
3816}
3817
Jim Grosbach4b905842013-09-20 23:08:21 +00003818/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003819/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003820bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003821 StringRef Name;
3822 bool EH = false;
3823 bool Debug = false;
3824
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003825 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003826 return TokError("Expected an identifier");
3827
3828 if (Name == ".eh_frame")
3829 EH = true;
3830 else if (Name == ".debug_frame")
3831 Debug = true;
3832
3833 if (getLexer().is(AsmToken::Comma)) {
3834 Lex();
3835
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003836 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003837 return TokError("Expected an identifier");
3838
3839 if (Name == ".eh_frame")
3840 EH = true;
3841 else if (Name == ".debug_frame")
3842 Debug = true;
3843 }
3844
3845 getStreamer().EmitCFISections(EH, Debug);
3846 return false;
3847}
3848
Jim Grosbach4b905842013-09-20 23:08:21 +00003849/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003850/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003851bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003852 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003853 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3854 if (check(parseIdentifier(Simple) || Simple != "simple",
3855 "unexpected token") ||
3856 parseToken(AsmToken::EndOfStatement))
3857 return addErrorSuffix(" in '.cfi_startproc' directive");
3858 }
Nirav Davea645433c2016-07-18 15:24:03 +00003859
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003860 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003861 return false;
3862}
3863
Jim Grosbach4b905842013-09-20 23:08:21 +00003864/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003865/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003866bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003867 getStreamer().EmitCFIEndProc();
3868 return false;
3869}
3870
Jim Grosbach4b905842013-09-20 23:08:21 +00003871/// \brief parse register name or number.
3872bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003873 SMLoc DirectiveLoc) {
3874 unsigned RegNo;
3875
3876 if (getLexer().isNot(AsmToken::Integer)) {
3877 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3878 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003879 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003880 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003881 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003882
3883 return false;
3884}
3885
Jim Grosbach4b905842013-09-20 23:08:21 +00003886/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003887/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003888bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003889 int64_t Register = 0, Offset = 0;
3890 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3891 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3892 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003893 return true;
3894
3895 getStreamer().EmitCFIDefCfa(Register, Offset);
3896 return false;
3897}
3898
Jim Grosbach4b905842013-09-20 23:08:21 +00003899/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003900/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003901bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003902 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003903 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003904 return true;
3905
3906 getStreamer().EmitCFIDefCfaOffset(Offset);
3907 return false;
3908}
3909
Jim Grosbach4b905842013-09-20 23:08:21 +00003910/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003911/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003912bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003913 int64_t Register1 = 0, Register2 = 0;
3914 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3915 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3916 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003917 return true;
3918
3919 getStreamer().EmitCFIRegister(Register1, Register2);
3920 return false;
3921}
3922
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003923/// parseDirectiveCFIWindowSave
3924/// ::= .cfi_window_save
3925bool AsmParser::parseDirectiveCFIWindowSave() {
3926 getStreamer().EmitCFIWindowSave();
3927 return false;
3928}
3929
Jim Grosbach4b905842013-09-20 23:08:21 +00003930/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003931/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003932bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003933 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003934 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003935 return true;
3936
3937 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3938 return false;
3939}
3940
Jim Grosbach4b905842013-09-20 23:08:21 +00003941/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003942/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003943bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003944 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003945 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003946 return true;
3947
3948 getStreamer().EmitCFIDefCfaRegister(Register);
3949 return false;
3950}
3951
Jim Grosbach4b905842013-09-20 23:08:21 +00003952/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003953/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003954bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003955 int64_t Register = 0;
3956 int64_t Offset = 0;
3957
Nirav Davea645433c2016-07-18 15:24:03 +00003958 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3959 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3960 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003961 return true;
3962
3963 getStreamer().EmitCFIOffset(Register, Offset);
3964 return false;
3965}
3966
Jim Grosbach4b905842013-09-20 23:08:21 +00003967/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003968/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003969bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003970 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003971
Nirav Davea645433c2016-07-18 15:24:03 +00003972 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3973 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3974 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003975 return true;
3976
3977 getStreamer().EmitCFIRelOffset(Register, Offset);
3978 return false;
3979}
3980
3981static bool isValidEncoding(int64_t Encoding) {
3982 if (Encoding & ~0xff)
3983 return false;
3984
3985 if (Encoding == dwarf::DW_EH_PE_omit)
3986 return true;
3987
3988 const unsigned Format = Encoding & 0xf;
3989 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3990 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3991 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3992 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3993 return false;
3994
3995 const unsigned Application = Encoding & 0x70;
3996 if (Application != dwarf::DW_EH_PE_absptr &&
3997 Application != dwarf::DW_EH_PE_pcrel)
3998 return false;
3999
4000 return true;
4001}
4002
Jim Grosbach4b905842013-09-20 23:08:21 +00004003/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00004004/// IsPersonality true for cfi_personality, false for cfi_lsda
4005/// ::= .cfi_personality encoding, [symbol_name]
4006/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00004007bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00004008 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004009 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00004010 return true;
4011 if (Encoding == dwarf::DW_EH_PE_omit)
4012 return false;
4013
Eli Bendersky17233942013-01-15 22:59:42 +00004014 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004015 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
4016 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4017 check(parseIdentifier(Name), "expected identifier in directive"))
4018 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004019
Jim Grosbach6f482002015-05-18 18:43:14 +00004020 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004021
4022 if (IsPersonality)
4023 getStreamer().EmitCFIPersonality(Sym, Encoding);
4024 else
4025 getStreamer().EmitCFILsda(Sym, Encoding);
4026 return false;
4027}
4028
Jim Grosbach4b905842013-09-20 23:08:21 +00004029/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00004030/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004031bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004032 getStreamer().EmitCFIRememberState();
4033 return false;
4034}
4035
Jim Grosbach4b905842013-09-20 23:08:21 +00004036/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00004037/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004038bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004039 getStreamer().EmitCFIRestoreState();
4040 return false;
4041}
4042
Jim Grosbach4b905842013-09-20 23:08:21 +00004043/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00004044/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00004045bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004046 int64_t Register = 0;
4047
Jim Grosbach4b905842013-09-20 23:08:21 +00004048 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004049 return true;
4050
4051 getStreamer().EmitCFISameValue(Register);
4052 return false;
4053}
4054
Jim Grosbach4b905842013-09-20 23:08:21 +00004055/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00004056/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00004057bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004058 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00004059 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004060 return true;
4061
4062 getStreamer().EmitCFIRestore(Register);
4063 return false;
4064}
4065
Jim Grosbach4b905842013-09-20 23:08:21 +00004066/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00004067/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004068bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00004069 std::string Values;
4070 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004071 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004072 return true;
4073
4074 Values.push_back((uint8_t)CurrValue);
4075
4076 while (getLexer().is(AsmToken::Comma)) {
4077 Lex();
4078
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004079 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004080 return true;
4081
4082 Values.push_back((uint8_t)CurrValue);
4083 }
4084
4085 getStreamer().EmitCFIEscape(Values);
4086 return false;
4087}
4088
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00004089/// parseDirectiveCFIReturnColumn
4090/// ::= .cfi_return_column register
4091bool AsmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc) {
4092 int64_t Register = 0;
4093 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4094 return true;
4095 getStreamer().EmitCFIReturnColumn(Register);
4096 return false;
4097}
4098
Jim Grosbach4b905842013-09-20 23:08:21 +00004099/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00004100/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00004101bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00004102 if (parseToken(AsmToken::EndOfStatement,
4103 "unexpected token in '.cfi_signal_frame'"))
4104 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004105
4106 getStreamer().EmitCFISignalFrame();
4107 return false;
4108}
4109
Jim Grosbach4b905842013-09-20 23:08:21 +00004110/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00004111/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00004112bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004113 int64_t Register = 0;
4114
Jim Grosbach4b905842013-09-20 23:08:21 +00004115 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004116 return true;
4117
4118 getStreamer().EmitCFIUndefined(Register);
4119 return false;
4120}
4121
Michael Zuckerman56704612017-05-01 13:20:12 +00004122/// parseDirectiveAltmacro
4123/// ::= .altmacro
4124/// ::= .noaltmacro
4125bool AsmParser::parseDirectiveAltmacro(StringRef Directive) {
4126 if (getLexer().isNot(AsmToken::EndOfStatement))
4127 return TokError("unexpected token in '" + Directive + "' directive");
4128 if (Directive == ".altmacro")
4129 getLexer().SetAltMacroMode(true);
4130 else
4131 getLexer().SetAltMacroMode(false);
4132 return false;
4133}
4134
Jim Grosbach4b905842013-09-20 23:08:21 +00004135/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00004136/// ::= .macros_on
4137/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00004138bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004139 if (parseToken(AsmToken::EndOfStatement,
4140 "unexpected token in '" + Directive + "' directive"))
4141 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004142
Jim Grosbach4b905842013-09-20 23:08:21 +00004143 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00004144 return false;
4145}
4146
Jim Grosbach4b905842013-09-20 23:08:21 +00004147/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004148/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00004149bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004150 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004151 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00004152 return TokError("expected identifier in '.macro' directive");
4153
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004154 if (getLexer().is(AsmToken::Comma))
4155 Lex();
4156
Eli Bendersky17233942013-01-15 22:59:42 +00004157 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00004158 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004159
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00004160 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004161 return Error(Lexer.getLoc(),
4162 "Vararg parameter '" + Parameters.back().Name +
4163 "' should be last one in the list of parameters.");
4164
David Majnemer91fc4c22014-01-29 18:57:46 +00004165 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004166 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00004167 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004168
Coby Tayreebedaae02017-04-08 20:29:03 +00004169 // Emit an error if two (or more) named parameters share the same name
4170 for (const MCAsmMacroParameter& CurrParam : Parameters)
4171 if (CurrParam.Name.equals(Parameter.Name))
4172 return TokError("macro '" + Name + "' has multiple parameters"
4173 " named '" + Parameter.Name + "'");
4174
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004175 if (Lexer.is(AsmToken::Colon)) {
4176 Lex(); // consume ':'
4177
4178 SMLoc QualLoc;
4179 StringRef Qualifier;
4180
4181 QualLoc = Lexer.getLoc();
4182 if (parseIdentifier(Qualifier))
4183 return Error(QualLoc, "missing parameter qualifier for "
4184 "'" + Parameter.Name + "' in macro '" + Name + "'");
4185
4186 if (Qualifier == "req")
4187 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00004188 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004189 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004190 else
4191 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
4192 "for '" + Parameter.Name + "' in macro '" + Name + "'");
4193 }
4194
David Majnemer91fc4c22014-01-29 18:57:46 +00004195 if (getLexer().is(AsmToken::Equal)) {
4196 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004197
4198 SMLoc ParamLoc;
4199
4200 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004201 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00004202 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004203
4204 if (Parameter.Required)
4205 Warning(ParamLoc, "pointless default value for required parameter "
4206 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00004207 }
David Majnemer91fc4c22014-01-29 18:57:46 +00004208
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00004209 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00004210
4211 if (getLexer().is(AsmToken::Comma))
4212 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004213 }
4214
Nirav Dave1180e6892016-06-02 17:15:05 +00004215 // Eat just the end of statement.
4216 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004217
Nirav Dave1180e6892016-06-02 17:15:05 +00004218 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00004219 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004220 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00004221 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004222 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00004223 // Ignore Lexing errors in macros.
4224 while (Lexer.is(AsmToken::Error)) {
4225 Lexer.Lex();
4226 }
4227
Eli Bendersky17233942013-01-15 22:59:42 +00004228 // Check whether we have reached the end of the file.
4229 if (getLexer().is(AsmToken::Eof))
4230 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
4231
4232 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004233 if (getLexer().is(AsmToken::Identifier)) {
4234 if (getTok().getIdentifier() == ".endm" ||
4235 getTok().getIdentifier() == ".endmacro") {
4236 if (MacroDepth == 0) { // Outermost macro.
4237 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00004238 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004239 if (getLexer().isNot(AsmToken::EndOfStatement))
4240 return TokError("unexpected token in '" + EndToken.getIdentifier() +
4241 "' directive");
4242 break;
4243 } else {
4244 // Otherwise we just found the end of an inner macro.
4245 --MacroDepth;
4246 }
4247 } else if (getTok().getIdentifier() == ".macro") {
4248 // We allow nested macros. Those aren't instantiated until the outermost
4249 // macro is expanded so just ignore them for now.
4250 ++MacroDepth;
4251 }
Eli Bendersky17233942013-01-15 22:59:42 +00004252 }
4253
4254 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004255 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00004256 }
4257
Rafael Espindola22c38a02018-02-14 16:34:27 +00004258 if (getContext().lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00004259 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
4260 }
4261
4262 const char *BodyStart = StartToken.getLoc().getPointer();
4263 const char *BodyEnd = EndToken.getLoc().getPointer();
4264 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00004265 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Oliver Stannardc3e7c6d2018-03-06 15:32:34 +00004266 MCAsmMacro Macro(Name, Body, std::move(Parameters));
4267 DEBUG_WITH_TYPE("asm-macros", dbgs() << "Defining new macro:\n";
4268 Macro.dump());
4269 getContext().defineMacro(Name, std::move(Macro));
Eli Bendersky17233942013-01-15 22:59:42 +00004270 return false;
4271}
4272
Jim Grosbach4b905842013-09-20 23:08:21 +00004273/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00004274///
4275/// With the support added for named parameters there may be code out there that
4276/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00004277/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00004278/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00004279/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00004280/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4281/// warning that the positional parameter found in body which have no effect.
4282/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00004283/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00004284/// intended or change the macro to use the named parameters. It is possible
4285/// this warning will trigger when the none of the named parameters are used
4286/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00004287void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00004288 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004289 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00004290 // If this macro is not defined with named parameters the warning we are
4291 // checking for here doesn't apply.
4292 unsigned NParameters = Parameters.size();
4293 if (NParameters == 0)
4294 return;
4295
4296 bool NamedParametersFound = false;
4297 bool PositionalParametersFound = false;
4298
4299 // Look at the body of the macro for use of both the named parameters and what
4300 // are likely to be positional parameters. This is what expandMacro() is
4301 // doing when it finds the parameters in the body.
4302 while (!Body.empty()) {
4303 // Scan for the next possible parameter.
4304 std::size_t End = Body.size(), Pos = 0;
4305 for (; Pos != End; ++Pos) {
4306 // Check for a substitution or escape.
4307 // This macro is defined with parameters, look for \foo, \bar, etc.
4308 if (Body[Pos] == '\\' && Pos + 1 != End)
4309 break;
4310
4311 // This macro should have parameters, but look for $0, $1, ..., $n too.
4312 if (Body[Pos] != '$' || Pos + 1 == End)
4313 continue;
4314 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004315 if (Next == '$' || Next == 'n' ||
4316 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004317 break;
4318 }
4319
4320 // Check if we reached the end.
4321 if (Pos == End)
4322 break;
4323
4324 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004325 switch (Body[Pos + 1]) {
4326 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004327 case '$':
4328 break;
4329
Jim Grosbach4b905842013-09-20 23:08:21 +00004330 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004331 case 'n':
4332 PositionalParametersFound = true;
4333 break;
4334
Jim Grosbach4b905842013-09-20 23:08:21 +00004335 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004336 default: {
4337 PositionalParametersFound = true;
4338 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004339 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004340 }
4341 Pos += 2;
4342 } else {
4343 unsigned I = Pos + 1;
4344 while (isIdentifierChar(Body[I]) && I + 1 != End)
4345 ++I;
4346
Jim Grosbach4b905842013-09-20 23:08:21 +00004347 const char *Begin = Body.data() + Pos + 1;
4348 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004349 unsigned Index = 0;
4350 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004351 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004352 break;
4353
4354 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004355 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4356 Pos += 3;
4357 else {
4358 Pos = I;
4359 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004360 } else {
4361 NamedParametersFound = true;
4362 Pos += 1 + Argument.size();
4363 }
4364 }
4365 // Update the scan point.
4366 Body = Body.substr(Pos);
4367 }
4368
4369 if (!NamedParametersFound && PositionalParametersFound)
4370 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4371 "used in macro body, possible positional parameter "
4372 "found in body which will have no effect");
4373}
4374
Nico Weber155dccd12014-07-24 17:08:39 +00004375/// parseDirectiveExitMacro
4376/// ::= .exitm
4377bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004378 if (parseToken(AsmToken::EndOfStatement,
4379 "unexpected token in '" + Directive + "' directive"))
4380 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004381
4382 if (!isInsideMacroInstantiation())
4383 return TokError("unexpected '" + Directive + "' in file, "
4384 "no current macro definition");
4385
4386 // Exit all conditionals that are active in the current macro.
4387 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4388 TheCondState = TheCondStack.back();
4389 TheCondStack.pop_back();
4390 }
4391
4392 handleMacroExit();
4393 return false;
4394}
4395
Jim Grosbach4b905842013-09-20 23:08:21 +00004396/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004397/// ::= .endm
4398/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004399bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004400 if (getLexer().isNot(AsmToken::EndOfStatement))
4401 return TokError("unexpected token in '" + Directive + "' directive");
4402
4403 // If we are inside a macro instantiation, terminate the current
4404 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004405 if (isInsideMacroInstantiation()) {
4406 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004407 return false;
4408 }
4409
4410 // Otherwise, this .endmacro is a stray entry in the file; well formed
4411 // .endmacro directives are handled during the macro definition parsing.
4412 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004413 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004414}
4415
Jim Grosbach4b905842013-09-20 23:08:21 +00004416/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004417/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004418bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004419 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004420 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004421 if (parseTokenLoc(Loc) ||
4422 check(parseIdentifier(Name), Loc,
4423 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004424 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004425 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004426 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004427
Rafael Espindola22c38a02018-02-14 16:34:27 +00004428 if (!getContext().lookupMacro(Name))
Nirav Dave1ab71992016-07-18 19:35:21 +00004429 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4430
Rafael Espindola22c38a02018-02-14 16:34:27 +00004431 getContext().undefineMacro(Name);
Oliver Stannardc3e7c6d2018-03-06 15:32:34 +00004432 DEBUG_WITH_TYPE("asm-macros", dbgs()
4433 << "Un-defining macro: " << Name << "\n");
Eli Bendersky17233942013-01-15 22:59:42 +00004434 return false;
4435}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004436
Jim Grosbach4b905842013-09-20 23:08:21 +00004437/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004438/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004439bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004440 // Expect a single argument: an expression that evaluates to a constant
4441 // in the inclusive range 0-30.
4442 SMLoc ExprLoc = getLexer().getLoc();
4443 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004444 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004445 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4446 "in '.bundle_align_mode' "
4447 "directive") ||
4448 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4449 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004450 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004451
4452 // Because of AlignSizePow2's verified range we can safely truncate it to
4453 // unsigned.
4454 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4455 return false;
4456}
4457
Jim Grosbach4b905842013-09-20 23:08:21 +00004458/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004459/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004460bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004461 if (checkForValidSection())
4462 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004463 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004464
Nirav Dave1a9044b2016-10-24 14:35:29 +00004465 StringRef Option;
4466 SMLoc Loc = getTok().getLoc();
4467 const char *kInvalidOptionError =
4468 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004469
Nirav Dave1a9044b2016-10-24 14:35:29 +00004470 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004471 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4472 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004473 parseToken(AsmToken::EndOfStatement,
4474 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004475 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004476 AlignToEnd = true;
4477 }
4478
Eli Bendersky802b6282013-01-07 21:51:08 +00004479 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004480 return false;
4481}
4482
Jim Grosbach4b905842013-09-20 23:08:21 +00004483/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004484/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004485bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004486 if (checkForValidSection() ||
4487 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004488 "unexpected token in '.bundle_unlock' directive"))
4489 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004490
4491 getStreamer().EmitBundleUnlock();
4492 return false;
4493}
4494
Jim Grosbach4b905842013-09-20 23:08:21 +00004495/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004496/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004497bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Petr Hosek67a94a72016-05-28 05:57:48 +00004498 SMLoc NumBytesLoc = Lexer.getLoc();
4499 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004500 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004501 return true;
4502
4503 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004504 if (parseOptionalToken(AsmToken::Comma))
4505 if (parseAbsoluteExpression(FillExpr))
4506 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4507 if (parseToken(AsmToken::EndOfStatement))
4508 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004509
Eli Bendersky17233942013-01-15 22:59:42 +00004510 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004511 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004512
4513 return false;
4514}
4515
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004516/// parseDirectiveDCB
4517/// ::= .dcb.{b, l, w} expression, expression
4518bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004519 SMLoc NumValuesLoc = Lexer.getLoc();
4520 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004521 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004522 return true;
4523
4524 if (NumValues < 0) {
4525 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4526 return false;
4527 }
4528
4529 if (parseToken(AsmToken::Comma,
4530 "unexpected token in '" + Twine(IDVal) + "' directive"))
4531 return true;
4532
4533 const MCExpr *Value;
4534 SMLoc ExprLoc = getLexer().getLoc();
4535 if (parseExpression(Value))
4536 return true;
4537
4538 // Special case constant expressions to match code generator.
4539 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4540 assert(Size <= 8 && "Invalid size");
4541 uint64_t IntValue = MCE->getValue();
4542 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4543 return Error(ExprLoc, "literal value out of range for directive");
4544 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4545 getStreamer().EmitIntValue(IntValue, Size);
4546 } else {
4547 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4548 getStreamer().EmitValue(Value, Size, ExprLoc);
4549 }
4550
4551 if (parseToken(AsmToken::EndOfStatement,
4552 "unexpected token in '" + Twine(IDVal) + "' directive"))
4553 return true;
4554
4555 return false;
4556}
4557
4558/// parseDirectiveRealDCB
4559/// ::= .dcb.{d, s} expression, expression
4560bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004561 SMLoc NumValuesLoc = Lexer.getLoc();
4562 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004563 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004564 return true;
4565
4566 if (NumValues < 0) {
4567 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4568 return false;
4569 }
4570
4571 if (parseToken(AsmToken::Comma,
4572 "unexpected token in '" + Twine(IDVal) + "' directive"))
4573 return true;
4574
4575 APInt AsInt;
4576 if (parseRealValue(Semantics, AsInt))
4577 return true;
4578
4579 if (parseToken(AsmToken::EndOfStatement,
4580 "unexpected token in '" + Twine(IDVal) + "' directive"))
4581 return true;
4582
4583 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4584 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4585 AsInt.getBitWidth() / 8);
4586
4587 return false;
4588}
4589
Petr Hosek85b2f672016-09-23 21:53:36 +00004590/// parseDirectiveDS
4591/// ::= .ds.{b, d, l, p, s, w, x} expression
4592bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004593 SMLoc NumValuesLoc = Lexer.getLoc();
4594 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004595 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004596 return true;
4597
4598 if (NumValues < 0) {
4599 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4600 return false;
4601 }
4602
4603 if (parseToken(AsmToken::EndOfStatement,
4604 "unexpected token in '" + Twine(IDVal) + "' directive"))
4605 return true;
4606
4607 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4608 getStreamer().emitFill(Size, 0);
4609
4610 return false;
4611}
4612
Jim Grosbach4b905842013-09-20 23:08:21 +00004613/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004614/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004615bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004616 if (checkForValidSection())
4617 return true;
4618
Nirav Dave1a9044b2016-10-24 14:35:29 +00004619 auto parseOp = [&]() -> bool {
4620 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004621 if (parseExpression(Value))
4622 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004623 if (Signed)
4624 getStreamer().EmitSLEB128Value(Value);
4625 else
4626 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004627 return false;
4628 };
Eli Bendersky17233942013-01-15 22:59:42 +00004629
Nirav Dave1a9044b2016-10-24 14:35:29 +00004630 if (parseMany(parseOp))
4631 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004632
4633 return false;
4634}
4635
Jim Grosbach4b905842013-09-20 23:08:21 +00004636/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004637/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004638bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004639 auto parseOp = [&]() -> bool {
4640 StringRef Name;
4641 SMLoc Loc = getTok().getLoc();
4642 if (parseIdentifier(Name))
4643 return Error(Loc, "expected identifier");
4644 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004645
Nirav Dave1a9044b2016-10-24 14:35:29 +00004646 // Assembler local symbols don't make any sense here. Complain loudly.
4647 if (Sym->isTemporary())
4648 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004649
Nirav Dave1a9044b2016-10-24 14:35:29 +00004650 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4651 return Error(Loc, "unable to emit symbol attribute");
4652 return false;
4653 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004654
Nirav Dave1a9044b2016-10-24 14:35:29 +00004655 if (parseMany(parseOp))
4656 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004657 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004658}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004659
Jim Grosbach4b905842013-09-20 23:08:21 +00004660/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004661/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004662bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004663 if (checkForValidSection())
4664 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004665
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004666 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004667 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004668 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004669 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004670
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004671 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004672 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004673
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004674 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004675 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004676 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004677
4678 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004679 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004680 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004681 return true;
4682
4683 int64_t Pow2Alignment = 0;
4684 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004685 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004686 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004687 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004688 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004689 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004690
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004691 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4692 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004693 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4694
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004695 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004696 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4697 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004698 if (!isPowerOf2_64(Pow2Alignment))
4699 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4700 Pow2Alignment = Log2_64(Pow2Alignment);
4701 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004702 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004703
Nirav Dave1a9044b2016-10-24 14:35:29 +00004704 if (parseToken(AsmToken::EndOfStatement,
4705 "unexpected token in '.comm' or '.lcomm' directive"))
4706 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004707
Chris Lattner28ad7542009-07-09 17:25:12 +00004708 // NOTE: a size of zero for a .comm should create a undefined symbol
4709 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004710 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004711 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004712 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004713
Eric Christopherbc818852010-05-14 01:38:54 +00004714 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004715 // may internally end up wanting an alignment in bytes.
4716 // FIXME: Diagnose overflow.
4717 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004718 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004719 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004720
Rafael Espindola13a79bb2017-02-02 21:26:06 +00004721 Sym->redefineIfPossible();
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004722 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004723 return Error(IDLoc, "invalid symbol redefinition");
4724
Chris Lattner28ad7542009-07-09 17:25:12 +00004725 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004726 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004727 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004728 return false;
4729 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004730
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004731 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004732 return false;
4733}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004734
Jim Grosbach4b905842013-09-20 23:08:21 +00004735/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004736/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004737bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004738 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004739 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004740
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004741 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004742 if (parseToken(AsmToken::EndOfStatement,
4743 "unexpected token in '.abort' directive"))
4744 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004745
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004746 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004747 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004748 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004749 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004750 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004751
4752 return false;
4753}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004754
Jim Grosbach4b905842013-09-20 23:08:21 +00004755/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004756/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004757bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004758 // Allow the strings to have escaped octal character sequence.
4759 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004760 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004761
Nirav Davea645433c2016-07-18 15:24:03 +00004762 if (check(getTok().isNot(AsmToken::String),
4763 "expected string in '.include' directive") ||
4764 parseEscapedString(Filename) ||
4765 check(getTok().isNot(AsmToken::EndOfStatement),
4766 "unexpected token in '.include' directive") ||
4767 // Attempt to switch the lexer to the included file before consuming the
4768 // end of statement to avoid losing it when we switch.
4769 check(enterIncludeFile(Filename), IncludeLoc,
4770 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004771 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004772
4773 return false;
4774}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004775
Jim Grosbach4b905842013-09-20 23:08:21 +00004776/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004777/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004778bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004779 // Allow the strings to have escaped octal character sequence.
4780 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004781 SMLoc IncbinLoc = getTok().getLoc();
4782 if (check(getTok().isNot(AsmToken::String),
4783 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00004784 parseEscapedString(Filename))
4785 return true;
4786
4787 int64_t Skip = 0;
4788 const MCExpr *Count = nullptr;
4789 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004790 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00004791 // The skip expression can be omitted while specifying the count, e.g:
4792 // .incbin "filename",,4
4793 if (getTok().isNot(AsmToken::Comma)) {
4794 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4795 return true;
4796 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00004797 if (parseOptionalToken(AsmToken::Comma)) {
4798 CountLoc = getTok().getLoc();
4799 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00004800 return true;
4801 }
4802 }
4803
4804 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004805 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004806 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004807
Petr Hosek2f4ac442016-09-23 00:41:06 +00004808 if (check(Skip < 0, SkipLoc, "skip is negative"))
4809 return true;
4810
Nirav Dave1ab71992016-07-18 19:35:21 +00004811 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00004812 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00004813 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004814 return false;
4815}
4816
Jim Grosbach4b905842013-09-20 23:08:21 +00004817/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004818/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4819bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004820 TheCondStack.push_back(TheCondState);
4821 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004822 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004823 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004824 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004825 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004826 if (parseAbsoluteExpression(ExprValue) ||
4827 parseToken(AsmToken::EndOfStatement,
4828 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004829 return true;
4830
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004831 switch (DirKind) {
4832 default:
4833 llvm_unreachable("unsupported directive");
4834 case DK_IF:
4835 case DK_IFNE:
4836 break;
4837 case DK_IFEQ:
4838 ExprValue = ExprValue == 0;
4839 break;
4840 case DK_IFGE:
4841 ExprValue = ExprValue >= 0;
4842 break;
4843 case DK_IFGT:
4844 ExprValue = ExprValue > 0;
4845 break;
4846 case DK_IFLE:
4847 ExprValue = ExprValue <= 0;
4848 break;
4849 case DK_IFLT:
4850 ExprValue = ExprValue < 0;
4851 break;
4852 }
4853
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004854 TheCondState.CondMet = ExprValue;
4855 TheCondState.Ignore = !TheCondState.CondMet;
4856 }
4857
4858 return false;
4859}
4860
Jim Grosbach4b905842013-09-20 23:08:21 +00004861/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004862/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004863bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004864 TheCondStack.push_back(TheCondState);
4865 TheCondState.TheCond = AsmCond::IfCond;
4866
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004867 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004868 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004869 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004870 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004871
Nirav Davea645433c2016-07-18 15:24:03 +00004872 if (parseToken(AsmToken::EndOfStatement,
4873 "unexpected token in '.ifb' directive"))
4874 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004875
4876 TheCondState.CondMet = ExpectBlank == Str.empty();
4877 TheCondState.Ignore = !TheCondState.CondMet;
4878 }
4879
4880 return false;
4881}
4882
Jim Grosbach4b905842013-09-20 23:08:21 +00004883/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004884/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004885/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004886bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004887 TheCondStack.push_back(TheCondState);
4888 TheCondState.TheCond = AsmCond::IfCond;
4889
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004890 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004891 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004892 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004893 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004894
Nirav Davea645433c2016-07-18 15:24:03 +00004895 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4896 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004897
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004898 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004899
Nirav Davea645433c2016-07-18 15:24:03 +00004900 if (parseToken(AsmToken::EndOfStatement,
4901 "unexpected token in '.ifc' directive"))
4902 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004903
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004904 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004905 TheCondState.Ignore = !TheCondState.CondMet;
4906 }
4907
4908 return false;
4909}
4910
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004911/// parseDirectiveIfeqs
4912/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004913bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004914 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004915 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004916 return TokError("expected string parameter for '.ifeqs' directive");
4917 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004918 }
4919
4920 StringRef String1 = getTok().getStringContents();
4921 Lex();
4922
4923 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004924 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004925 return TokError(
4926 "expected comma after first string for '.ifeqs' directive");
4927 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004928 }
4929
4930 Lex();
4931
4932 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004933 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004934 return TokError("expected string parameter for '.ifeqs' directive");
4935 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004936 }
4937
4938 StringRef String2 = getTok().getStringContents();
4939 Lex();
4940
4941 TheCondStack.push_back(TheCondState);
4942 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004943 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004944 TheCondState.Ignore = !TheCondState.CondMet;
4945
4946 return false;
4947}
4948
Jim Grosbach4b905842013-09-20 23:08:21 +00004949/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004950/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004951bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004952 StringRef Name;
4953 TheCondStack.push_back(TheCondState);
4954 TheCondState.TheCond = AsmCond::IfCond;
4955
4956 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004957 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004958 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00004959 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4960 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4961 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004962
Jim Grosbach6f482002015-05-18 18:43:14 +00004963 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004964
4965 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004966 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004967 else
Craig Topper353eda42014-04-24 06:44:33 +00004968 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004969 TheCondState.Ignore = !TheCondState.CondMet;
4970 }
4971
4972 return false;
4973}
4974
Jim Grosbach4b905842013-09-20 23:08:21 +00004975/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004976/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004977bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004978 if (TheCondState.TheCond != AsmCond::IfCond &&
4979 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004980 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
4981 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004982 TheCondState.TheCond = AsmCond::ElseIfCond;
4983
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004984 bool LastIgnoreState = false;
4985 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004986 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004987 if (LastIgnoreState || TheCondState.CondMet) {
4988 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004989 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004990 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004991 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004992 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004993 return true;
4994
Nirav Dave1a9044b2016-10-24 14:35:29 +00004995 if (parseToken(AsmToken::EndOfStatement,
4996 "unexpected token in '.elseif' directive"))
4997 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004998
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004999 TheCondState.CondMet = ExprValue;
5000 TheCondState.Ignore = !TheCondState.CondMet;
5001 }
5002
5003 return false;
5004}
5005
Jim Grosbach4b905842013-09-20 23:08:21 +00005006/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005007/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00005008bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005009 if (parseToken(AsmToken::EndOfStatement,
5010 "unexpected token in '.else' directive"))
5011 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005012
5013 if (TheCondState.TheCond != AsmCond::IfCond &&
5014 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00005015 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
5016 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005017 TheCondState.TheCond = AsmCond::ElseCond;
5018 bool LastIgnoreState = false;
5019 if (!TheCondStack.empty())
5020 LastIgnoreState = TheCondStack.back().Ignore;
5021 if (LastIgnoreState || TheCondState.CondMet)
5022 TheCondState.Ignore = true;
5023 else
5024 TheCondState.Ignore = false;
5025
5026 return false;
5027}
5028
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005029/// parseDirectiveEnd
5030/// ::= .end
5031bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005032 if (parseToken(AsmToken::EndOfStatement,
5033 "unexpected token in '.end' directive"))
5034 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005035
5036 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00005037 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005038
5039 return false;
5040}
5041
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005042/// parseDirectiveError
5043/// ::= .err
5044/// ::= .error [string]
5045bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
5046 if (!TheCondStack.empty()) {
5047 if (TheCondStack.back().Ignore) {
5048 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005049 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005050 }
5051 }
5052
5053 if (!WithMessage)
5054 return Error(L, ".err encountered");
5055
5056 StringRef Message = ".error directive invoked in source file";
5057 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005058 if (Lexer.isNot(AsmToken::String))
5059 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005060
5061 Message = getTok().getStringContents();
5062 Lex();
5063 }
5064
Nirav Dave2364748a2016-09-16 18:30:20 +00005065 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005066}
5067
Nico Weber404012b2014-07-24 16:26:06 +00005068/// parseDirectiveWarning
5069/// ::= .warning [string]
5070bool AsmParser::parseDirectiveWarning(SMLoc L) {
5071 if (!TheCondStack.empty()) {
5072 if (TheCondStack.back().Ignore) {
5073 eatToEndOfStatement();
5074 return false;
5075 }
5076 }
5077
5078 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00005079
5080 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005081 if (Lexer.isNot(AsmToken::String))
5082 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00005083
5084 Message = getTok().getStringContents();
5085 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00005086 if (parseToken(AsmToken::EndOfStatement,
5087 "expected end of statement in '.warning' directive"))
5088 return true;
Nico Weber404012b2014-07-24 16:26:06 +00005089 }
5090
Nirav Dave2364748a2016-09-16 18:30:20 +00005091 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00005092}
5093
Jim Grosbach4b905842013-09-20 23:08:21 +00005094/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005095/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00005096bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005097 if (parseToken(AsmToken::EndOfStatement,
5098 "unexpected token in '.endif' directive"))
5099 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005100
Jim Grosbach4b905842013-09-20 23:08:21 +00005101 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00005102 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
5103 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005104 if (!TheCondStack.empty()) {
5105 TheCondState = TheCondStack.back();
5106 TheCondStack.pop_back();
5107 }
5108
5109 return false;
5110}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00005111
Eli Bendersky17233942013-01-15 22:59:42 +00005112void AsmParser::initializeDirectiveKindMap() {
5113 DirectiveKindMap[".set"] = DK_SET;
5114 DirectiveKindMap[".equ"] = DK_EQU;
5115 DirectiveKindMap[".equiv"] = DK_EQUIV;
5116 DirectiveKindMap[".ascii"] = DK_ASCII;
5117 DirectiveKindMap[".asciz"] = DK_ASCIZ;
5118 DirectiveKindMap[".string"] = DK_STRING;
5119 DirectiveKindMap[".byte"] = DK_BYTE;
5120 DirectiveKindMap[".short"] = DK_SHORT;
5121 DirectiveKindMap[".value"] = DK_VALUE;
5122 DirectiveKindMap[".2byte"] = DK_2BYTE;
5123 DirectiveKindMap[".long"] = DK_LONG;
5124 DirectiveKindMap[".int"] = DK_INT;
5125 DirectiveKindMap[".4byte"] = DK_4BYTE;
5126 DirectiveKindMap[".quad"] = DK_QUAD;
5127 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00005128 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00005129 DirectiveKindMap[".single"] = DK_SINGLE;
5130 DirectiveKindMap[".float"] = DK_FLOAT;
5131 DirectiveKindMap[".double"] = DK_DOUBLE;
5132 DirectiveKindMap[".align"] = DK_ALIGN;
5133 DirectiveKindMap[".align32"] = DK_ALIGN32;
5134 DirectiveKindMap[".balign"] = DK_BALIGN;
5135 DirectiveKindMap[".balignw"] = DK_BALIGNW;
5136 DirectiveKindMap[".balignl"] = DK_BALIGNL;
5137 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
5138 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
5139 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
5140 DirectiveKindMap[".org"] = DK_ORG;
5141 DirectiveKindMap[".fill"] = DK_FILL;
5142 DirectiveKindMap[".zero"] = DK_ZERO;
5143 DirectiveKindMap[".extern"] = DK_EXTERN;
5144 DirectiveKindMap[".globl"] = DK_GLOBL;
5145 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00005146 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
5147 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
5148 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
5149 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
5150 DirectiveKindMap[".reference"] = DK_REFERENCE;
5151 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
5152 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
5153 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
5154 DirectiveKindMap[".comm"] = DK_COMM;
5155 DirectiveKindMap[".common"] = DK_COMMON;
5156 DirectiveKindMap[".lcomm"] = DK_LCOMM;
5157 DirectiveKindMap[".abort"] = DK_ABORT;
5158 DirectiveKindMap[".include"] = DK_INCLUDE;
5159 DirectiveKindMap[".incbin"] = DK_INCBIN;
5160 DirectiveKindMap[".code16"] = DK_CODE16;
5161 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
5162 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005163 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00005164 DirectiveKindMap[".irp"] = DK_IRP;
5165 DirectiveKindMap[".irpc"] = DK_IRPC;
5166 DirectiveKindMap[".endr"] = DK_ENDR;
5167 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
5168 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
5169 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
5170 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00005171 DirectiveKindMap[".ifeq"] = DK_IFEQ;
5172 DirectiveKindMap[".ifge"] = DK_IFGE;
5173 DirectiveKindMap[".ifgt"] = DK_IFGT;
5174 DirectiveKindMap[".ifle"] = DK_IFLE;
5175 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00005176 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00005177 DirectiveKindMap[".ifb"] = DK_IFB;
5178 DirectiveKindMap[".ifnb"] = DK_IFNB;
5179 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005180 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00005181 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00005182 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00005183 DirectiveKindMap[".ifdef"] = DK_IFDEF;
5184 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
5185 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
5186 DirectiveKindMap[".elseif"] = DK_ELSEIF;
5187 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005188 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00005189 DirectiveKindMap[".endif"] = DK_ENDIF;
5190 DirectiveKindMap[".skip"] = DK_SKIP;
5191 DirectiveKindMap[".space"] = DK_SPACE;
5192 DirectiveKindMap[".file"] = DK_FILE;
5193 DirectiveKindMap[".line"] = DK_LINE;
5194 DirectiveKindMap[".loc"] = DK_LOC;
5195 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005196 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005197 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005198 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
5199 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00005200 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005201 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00005202 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005203 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
5204 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00005205 DirectiveKindMap[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET;
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00005206 DirectiveKindMap[".cv_fpo_data"] = DK_CV_FPO_DATA;
Eli Bendersky17233942013-01-15 22:59:42 +00005207 DirectiveKindMap[".sleb128"] = DK_SLEB128;
5208 DirectiveKindMap[".uleb128"] = DK_ULEB128;
5209 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
5210 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
5211 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
5212 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
5213 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
5214 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
5215 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
5216 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
5217 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
5218 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
5219 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
5220 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
5221 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
5222 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
5223 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
5224 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00005225 DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN;
Eli Bendersky17233942013-01-15 22:59:42 +00005226 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
5227 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
5228 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00005229 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00005230 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
5231 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
5232 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00005233 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00005234 DirectiveKindMap[".endm"] = DK_ENDM;
5235 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
5236 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005237 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005238 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00005239 DirectiveKindMap[".warning"] = DK_WARNING;
Michael Zuckerman56704612017-05-01 13:20:12 +00005240 DirectiveKindMap[".altmacro"] = DK_ALTMACRO;
5241 DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00005242 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00005243 DirectiveKindMap[".dc"] = DK_DC;
5244 DirectiveKindMap[".dc.a"] = DK_DC_A;
5245 DirectiveKindMap[".dc.b"] = DK_DC_B;
5246 DirectiveKindMap[".dc.d"] = DK_DC_D;
5247 DirectiveKindMap[".dc.l"] = DK_DC_L;
5248 DirectiveKindMap[".dc.s"] = DK_DC_S;
5249 DirectiveKindMap[".dc.w"] = DK_DC_W;
5250 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00005251 DirectiveKindMap[".dcb"] = DK_DCB;
5252 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
5253 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
5254 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
5255 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
5256 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
5257 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00005258 DirectiveKindMap[".ds"] = DK_DS;
5259 DirectiveKindMap[".ds.b"] = DK_DS_B;
5260 DirectiveKindMap[".ds.d"] = DK_DS_D;
5261 DirectiveKindMap[".ds.l"] = DK_DS_L;
5262 DirectiveKindMap[".ds.p"] = DK_DS_P;
5263 DirectiveKindMap[".ds.s"] = DK_DS_S;
5264 DirectiveKindMap[".ds.w"] = DK_DS_W;
5265 DirectiveKindMap[".ds.x"] = DK_DS_X;
Coby Tayree01e53202017-10-02 14:36:31 +00005266 DirectiveKindMap[".print"] = DK_PRINT;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00005267}
5268
Jim Grosbach4b905842013-09-20 23:08:21 +00005269MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005270 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005271
Rafael Espindola34b9c512012-06-03 23:57:14 +00005272 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005273 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005274 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00005275 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005276 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00005277 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005278 }
5279
Rafael Espindola34b9c512012-06-03 23:57:14 +00005280 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00005281 (getTok().getIdentifier() == ".rept" ||
5282 getTok().getIdentifier() == ".irp" ||
5283 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005284 ++NestLevel;
5285 }
5286
5287 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00005288 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005289 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005290 EndToken = getTok();
5291 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005292 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005293 printError(getTok().getLoc(),
5294 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00005295 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005296 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005297 break;
5298 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005299 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005300 }
5301
Rafael Espindola34b9c512012-06-03 23:57:14 +00005302 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005303 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005304 }
5305
5306 const char *BodyStart = StartToken.getLoc().getPointer();
5307 const char *BodyEnd = EndToken.getLoc().getPointer();
5308 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5309
Rafael Espindola34b9c512012-06-03 23:57:14 +00005310 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005311 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00005312 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005313}
5314
Jim Grosbach4b905842013-09-20 23:08:21 +00005315void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005316 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005317 OS << ".endr\n";
5318
Rafael Espindola3560ff22014-08-27 20:03:13 +00005319 std::unique_ptr<MemoryBuffer> Instantiation =
5320 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005321
Rafael Espindola34b9c512012-06-03 23:57:14 +00005322 // Create the macro instantiation object and add to the current macro
5323 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005324 MacroInstantiation *MI = new MacroInstantiation(
5325 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005326 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005327
Rafael Espindola34b9c512012-06-03 23:57:14 +00005328 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005329 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005330 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005331 Lex();
5332}
5333
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005334/// parseDirectiveRept
5335/// ::= .rep | .rept count
5336bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005337 const MCExpr *CountExpr;
5338 SMLoc CountLoc = getTok().getLoc();
5339 if (parseExpression(CountExpr))
5340 return true;
5341
Rafael Espindola34b9c512012-06-03 23:57:14 +00005342 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00005343 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005344 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5345 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005346
Nirav Davea645433c2016-07-18 15:24:03 +00005347 if (check(Count < 0, CountLoc, "Count is negative") ||
5348 parseToken(AsmToken::EndOfStatement,
5349 "unexpected token in '" + Dir + "' directive"))
5350 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005351
5352 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005353 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005354 if (!M)
5355 return true;
5356
5357 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5358 // to hold the macro body with substitutions.
5359 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005360 raw_svector_ostream OS(Buf);
5361 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005362 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5363 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005364 return true;
5365 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005366 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005367
5368 return false;
5369}
5370
Jim Grosbach4b905842013-09-20 23:08:21 +00005371/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005372/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005373bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005374 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005375 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005376 if (check(parseIdentifier(Parameter.Name),
5377 "expected identifier in '.irp' directive") ||
5378 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5379 parseMacroArguments(nullptr, A) ||
5380 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005381 return true;
5382
Rafael Espindola768b41c2012-06-15 14:02:34 +00005383 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005384 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005385 if (!M)
5386 return true;
5387
5388 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5389 // to hold the macro body with substitutions.
5390 SmallString<256> Buf;
5391 raw_svector_ostream OS(Buf);
5392
Craig Topper84008482015-10-10 05:38:14 +00005393 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005394 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5395 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005396 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005397 return true;
5398 }
5399
Jim Grosbach4b905842013-09-20 23:08:21 +00005400 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005401
5402 return false;
5403}
5404
Jim Grosbach4b905842013-09-20 23:08:21 +00005405/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005406/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005407bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005408 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005409 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005410
5411 if (check(parseIdentifier(Parameter.Name),
5412 "expected identifier in '.irpc' directive") ||
5413 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5414 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005415 return true;
5416
5417 if (A.size() != 1 || A.front().size() != 1)
5418 return TokError("unexpected token in '.irpc' directive");
5419
5420 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005421 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5422 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005423
5424 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005425 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005426 if (!M)
5427 return true;
5428
5429 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5430 // to hold the macro body with substitutions.
5431 SmallString<256> Buf;
5432 raw_svector_ostream OS(Buf);
5433
5434 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005435 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005436 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005437 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005438
Toma Tabacu217116e2015-04-27 10:50:29 +00005439 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5440 // This is undocumented, but GAS seems to support it.
5441 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005442 return true;
5443 }
5444
Jim Grosbach4b905842013-09-20 23:08:21 +00005445 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005446
5447 return false;
5448}
5449
Jim Grosbach4b905842013-09-20 23:08:21 +00005450bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005451 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005452 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005453
5454 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005455 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005456 assert(getLexer().is(AsmToken::EndOfStatement));
5457
Jim Grosbach4b905842013-09-20 23:08:21 +00005458 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005459 return false;
5460}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005461
Jim Grosbach4b905842013-09-20 23:08:21 +00005462bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005463 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005464 const MCExpr *Value;
5465 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005466 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005467 return true;
5468 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5469 if (!MCE)
5470 return Error(ExprLoc, "unexpected expression in _emit");
5471 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005472 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005473 return Error(ExprLoc, "literal value out of range for directive");
5474
Craig Topper7d5b2312015-10-10 05:25:02 +00005475 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005476 return false;
5477}
5478
Jim Grosbach4b905842013-09-20 23:08:21 +00005479bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005480 const MCExpr *Value;
5481 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005482 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005483 return true;
5484 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5485 if (!MCE)
5486 return Error(ExprLoc, "unexpected expression in align");
5487 uint64_t IntValue = MCE->getValue();
5488 if (!isPowerOf2_64(IntValue))
5489 return Error(ExprLoc, "literal value not a power of two greater then zero");
5490
Craig Topper7d5b2312015-10-10 05:25:02 +00005491 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005492 return false;
5493}
5494
Coby Tayree01e53202017-10-02 14:36:31 +00005495bool AsmParser::parseDirectivePrint(SMLoc DirectiveLoc) {
5496 const AsmToken StrTok = getTok();
5497 Lex();
5498 if (StrTok.isNot(AsmToken::String) || StrTok.getString().front() != '"')
5499 return Error(DirectiveLoc, "expected double quoted string after .print");
5500 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5501 return true;
5502 llvm::outs() << StrTok.getStringContents() << '\n';
5503 return false;
5504}
5505
Chad Rosierf43fcf52013-02-13 21:27:17 +00005506// We are comparing pointers, but the pointers are relative to a single string.
5507// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005508static int rewritesSort(const AsmRewrite *AsmRewriteA,
5509 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005510 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5511 return -1;
5512 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5513 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005514
Chad Rosierfce4fab2013-04-08 17:43:47 +00005515 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5516 // rewrite to the same location. Make sure the SizeDirective rewrite is
5517 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5518 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005519 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5520 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005521 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005522
Jim Grosbach4b905842013-09-20 23:08:21 +00005523 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5524 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005525 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005526 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005527}
5528
Jim Grosbach4b905842013-09-20 23:08:21 +00005529bool AsmParser::parseMSInlineAsm(
5530 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00005531 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
Jim Grosbach4b905842013-09-20 23:08:21 +00005532 SmallVectorImpl<std::string> &Constraints,
5533 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5534 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005535 SmallVector<void *, 4> InputDecls;
5536 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005537 SmallVector<bool, 4> InputDeclsAddressOf;
5538 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005539 SmallVector<std::string, 4> InputConstraints;
5540 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005541 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005542
Benjamin Kramer1a136112013-02-15 20:37:21 +00005543 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005544
5545 // Prime the lexer.
5546 Lex();
5547
5548 // While we have input, parse each statement.
5549 unsigned InputIdx = 0;
5550 unsigned OutputIdx = 0;
5551 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005552 // Parse curly braces marking block start/end
5553 if (parseCurlyBlockScope(AsmStrRewrites))
5554 continue;
5555
Eli Friedman0f4871d2012-10-22 23:58:19 +00005556 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005557 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005558
Nirav Dave2364748a2016-09-16 18:30:20 +00005559 if (StatementErr || Info.ParseError) {
5560 // Emit pending errors if any exist.
5561 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005562 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005563 }
5564
5565 // No pending error should exist here.
5566 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005567
Benjamin Kramer1a136112013-02-15 20:37:21 +00005568 if (Info.Opcode == ~0U)
5569 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005570
Benjamin Kramer1a136112013-02-15 20:37:21 +00005571 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005572
Benjamin Kramer1a136112013-02-15 20:37:21 +00005573 // Build the list of clobbers, outputs and inputs.
5574 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005575 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005576
Benjamin Kramer1a136112013-02-15 20:37:21 +00005577 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005578 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005579 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005580
Benjamin Kramer1a136112013-02-15 20:37:21 +00005581 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005582 if (Operand.isReg() && !Operand.needAddressOf() &&
5583 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005584 unsigned NumDefs = Desc.getNumDefs();
5585 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005586 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5587 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005588 continue;
5589 }
5590
5591 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005592 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005593 if (SymName.empty())
5594 continue;
5595
David Blaikie960ea3f2014-06-08 16:18:35 +00005596 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005597 if (!OpDecl)
5598 continue;
5599
5600 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005601 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005602 if (isOutput) {
5603 ++InputIdx;
5604 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005605 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005606 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005607 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005608 } else {
5609 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005610 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5611 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005612 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005613 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005614 }
Reid Kleckneree088972013-12-10 18:27:32 +00005615
5616 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005617 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5618 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005619 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005620 }
5621
5622 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005623 NumOutputs = OutputDecls.size();
5624 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005625
5626 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005627 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5628 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5629 ClobberRegs.end());
5630 Clobbers.assign(ClobberRegs.size(), std::string());
5631 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5632 raw_string_ostream OS(Clobbers[I]);
5633 IP->printRegName(OS, ClobberRegs[I]);
5634 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005635
5636 // Merge the various outputs and inputs. Output are expected first.
5637 if (NumOutputs || NumInputs) {
5638 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005639 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005640 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005641 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005642 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005643 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005644 }
5645 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005646 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005647 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005648 }
5649 }
5650
5651 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005652 std::string AsmStringIR;
5653 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005654 StringRef ASMString =
5655 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5656 const char *AsmStart = ASMString.begin();
5657 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005658 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005659 for (const AsmRewrite &AR : AsmStrRewrites) {
5660 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005661
David Majnemer8114c1a2014-06-23 02:17:16 +00005662 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005663 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005664
Chad Rosier120eefd2013-03-19 17:32:17 +00005665 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005666 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005667 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005668
Chad Rosier37e755c2012-10-23 17:43:43 +00005669 // Skip the original expression.
5670 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005671 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005672 continue;
5673 }
5674
Chad Rosierff10ed12013-04-12 16:26:42 +00005675 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005676 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005677 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005678 default:
5679 break;
Coby Tayreed8912892017-08-24 08:46:25 +00005680 case AOK_IntelExpr:
5681 assert(AR.IntelExp.isValid() && "cannot write invalid intel expression");
5682 if (AR.IntelExp.NeedBracs)
5683 OS << "[";
5684 if (AR.IntelExp.hasBaseReg())
5685 OS << AR.IntelExp.BaseReg;
5686 if (AR.IntelExp.hasIndexReg())
5687 OS << (AR.IntelExp.hasBaseReg() ? " + " : "")
5688 << AR.IntelExp.IndexReg;
5689 if (AR.IntelExp.Scale > 1)
5690 OS << " * $$" << AR.IntelExp.Scale;
5691 if (AR.IntelExp.Imm || !AR.IntelExp.hasRegs())
5692 OS << (AR.IntelExp.hasRegs() ? " + $$" : "$$") << AR.IntelExp.Imm;
5693 if (AR.IntelExp.NeedBracs)
5694 OS << "]";
Chad Rosier8bce6642012-10-18 15:49:34 +00005695 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005696 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005697 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005698 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005699 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005700 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005701 break;
5702 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005703 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005704 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005705 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005706 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005707 default: break;
5708 case 8: OS << "byte ptr "; break;
5709 case 16: OS << "word ptr "; break;
5710 case 32: OS << "dword ptr "; break;
5711 case 64: OS << "qword ptr "; break;
5712 case 80: OS << "xword ptr "; break;
5713 case 128: OS << "xmmword ptr "; break;
5714 case 256: OS << "ymmword ptr "; break;
5715 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005716 break;
5717 case AOK_Emit:
5718 OS << ".byte";
5719 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005720 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005721 // MS alignment directives are measured in bytes. If the native assembler
5722 // measures alignment in bytes, we can pass it straight through.
5723 OS << ".align";
5724 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5725 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005726
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005727 // Alignment is in log2 form, so print that instead and skip the original
5728 // immediate.
5729 unsigned Val = AR.Val;
5730 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005731 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005732 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5733 break;
5734 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005735 case AOK_EVEN:
5736 OS << ".even";
5737 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005738 case AOK_EndOfStatement:
5739 OS << "\n\t";
5740 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005741 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005742
Chad Rosier8bce6642012-10-18 15:49:34 +00005743 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005744 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005745 }
5746
5747 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005748 if (AsmStart != AsmEnd)
5749 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005750
5751 AsmString = OS.str();
5752 return false;
5753}
5754
Pete Cooper80d21cb2015-06-22 19:35:57 +00005755namespace llvm {
5756namespace MCParserUtils {
5757
5758/// Returns whether the given symbol is used anywhere in the given expression,
5759/// or subexpressions.
5760static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5761 switch (Value->getKind()) {
5762 case MCExpr::Binary: {
5763 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5764 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5765 isSymbolUsedInExpression(Sym, BE->getRHS());
5766 }
5767 case MCExpr::Target:
5768 case MCExpr::Constant:
5769 return false;
5770 case MCExpr::SymbolRef: {
5771 const MCSymbol &S =
5772 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5773 if (S.isVariable())
5774 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5775 return &S == Sym;
5776 }
5777 case MCExpr::Unary:
5778 return isSymbolUsedInExpression(
5779 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5780 }
5781
5782 llvm_unreachable("Unknown expr kind!");
5783}
5784
5785bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5786 MCAsmParser &Parser, MCSymbol *&Sym,
5787 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005788
5789 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005790 SMLoc EqualLoc = Parser.getTok().getLoc();
Pete Cooper80d21cb2015-06-22 19:35:57 +00005791
5792 if (Parser.parseExpression(Value)) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00005793 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005794 }
5795
5796 // Note: we don't count b as used in "a = b". This is to allow
5797 // a = b
5798 // b = c
5799
Nirav Dave1a9044b2016-10-24 14:35:29 +00005800 if (Parser.parseToken(AsmToken::EndOfStatement))
5801 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00005802
5803 // Validate that the LHS is allowed to be a variable (either it has not been
5804 // used as a symbol, or it is an absolute symbol).
5805 Sym = Parser.getContext().lookupSymbol(Name);
5806 if (Sym) {
5807 // Diagnose assignment to a label.
5808 //
5809 // FIXME: Diagnostics. Note the location of the definition as a label.
5810 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5811 if (isSymbolUsedInExpression(Sym, Value))
5812 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005813 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5814 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005815 ; // Allow redefinitions of undefined symbols only used in directives.
5816 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5817 ; // Allow redefinitions of variables that haven't yet been used.
5818 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5819 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5820 else if (!Sym->isVariable())
5821 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5822 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5823 return Parser.Error(EqualLoc,
5824 "invalid reassignment of non-absolute variable '" +
5825 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005826 } else if (Name == ".") {
Oliver Stannard268f42f2016-12-14 10:43:58 +00005827 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005828 return false;
5829 } else
5830 Sym = Parser.getContext().getOrCreateSymbol(Name);
5831
5832 Sym->setRedefinable(allow_redef);
5833
5834 return false;
5835}
5836
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005837} // end namespace MCParserUtils
5838} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005839
Daniel Dunbar01e36072010-07-17 02:26:10 +00005840/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005841MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
Sanne Wouda29338752017-02-08 14:48:05 +00005842 MCStreamer &Out, const MCAsmInfo &MAI,
5843 unsigned CB) {
5844 return new AsmParser(SM, C, Out, MAI, CB);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005845}