blob: d213bf3fa3aef81239842af264be4e4a2665473d [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 Carruth8a8cd2b2014-01-07 11:48:04 +000018#include "llvm/ADT/SmallString.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000019#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/STLExtras.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000021#include "llvm/ADT/StringMap.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000022#include "llvm/ADT/StringRef.h"
Daniel Dunbareb6bb322009-07-27 23:20:52 +000023#include "llvm/ADT/Twine.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000024#include "llvm/MC/MCAsmInfo.h"
Reid Klecknera5b1eef2016-08-26 17:58:37 +000025#include "llvm/MC/MCCodeView.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000026#include "llvm/MC/MCContext.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000027#include "llvm/MC/MCDirectives.h"
Evan Cheng11424442011-07-26 00:24:13 +000028#include "llvm/MC/MCDwarf.h"
Daniel Dunbar115e4d62009-08-31 08:06:59 +000029#include "llvm/MC/MCExpr.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000030#include "llvm/MC/MCInstPrinter.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000031#include "llvm/MC/MCInstrDesc.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000032#include "llvm/MC/MCInstrInfo.h"
Rafael Espindolae28610d2013-12-09 20:26:40 +000033#include "llvm/MC/MCObjectFileInfo.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000034#include "llvm/MC/MCParser/AsmCond.h"
35#include "llvm/MC/MCParser/AsmLexer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000036#include "llvm/MC/MCParser/MCAsmLexer.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000037#include "llvm/MC/MCParser/MCAsmParser.h"
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000038#include "llvm/MC/MCParser/MCAsmParserExtension.h"
Pete Cooper80d21cb2015-06-22 19:35:57 +000039#include "llvm/MC/MCParser/MCAsmParserUtils.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000040#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000041#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Cheng76792992011-07-20 05:58:47 +000042#include "llvm/MC/MCRegisterInfo.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000043#include "llvm/MC/MCSection.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000044#include "llvm/MC/MCStreamer.h"
Daniel Dunbarae7ac012009-06-29 23:43:14 +000045#include "llvm/MC/MCSymbol.h"
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000046#include "llvm/MC/MCTargetOptions.h"
Daniel Sanders9f6ad492015-11-12 13:33:00 +000047#include "llvm/MC/MCValue.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000048#include "llvm/Support/Casting.h"
Davide Italiano7c9fc732016-07-27 05:51:56 +000049#include "llvm/Support/CommandLine.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000050#include "llvm/Support/Dwarf.h"
Benjamin Kramer4efe5062012-01-28 15:28:41 +000051#include "llvm/Support/ErrorHandling.h"
Jim Grosbach76346c32011-06-29 16:05:14 +000052#include "llvm/Support/MathExtras.h"
Kevin Enderbye233dda2010-06-28 21:45:58 +000053#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000054#include "llvm/Support/SMLoc.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000055#include "llvm/Support/SourceMgr.h"
Chris Lattner36e02122009-06-21 20:54:55 +000056#include "llvm/Support/raw_ostream.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000057#include <algorithm>
58#include <cassert>
Nick Lewycky0de20af2010-12-19 20:43:38 +000059#include <cctype>
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000060#include <climits>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000061#include <cstddef>
62#include <cstdint>
Benjamin Kramerd59664f2014-04-29 23:26:49 +000063#include <deque>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000064#include <memory>
Davide Italiano7c9fc732016-07-27 05:51:56 +000065#include <sstream>
Chad Rosier8bce6642012-10-18 15:49:34 +000066#include <string>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000067#include <tuple>
68#include <utility>
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000069#include <vector>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000070
Chris Lattnerb0133452009-06-21 20:16:42 +000071using namespace llvm;
72
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000073MCAsmParserSemaCallback::~MCAsmParserSemaCallback() = default;
Nick Lewyckyac612272012-10-19 07:00:09 +000074
Davide Italiano7c9fc732016-07-27 05:51:56 +000075static cl::opt<unsigned> AsmMacroMaxNestingDepth(
76 "asm-macro-max-nesting-depth", cl::init(20), cl::Hidden,
77 cl::desc("The maximum nesting depth allowed for assembly macros."));
78
Daniel Dunbar86033402010-07-12 17:54:38 +000079namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +000080
Eli Benderskya313ae62013-01-16 18:56:50 +000081/// \brief Helper types for tracking macro definitions.
82typedef std::vector<AsmToken> MCAsmMacroArgument;
83typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000084
85struct MCAsmMacroParameter {
86 StringRef Name;
87 MCAsmMacroArgument Value;
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000088 bool Required = false;
89 bool Vararg = false;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000090
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000091 MCAsmMacroParameter() = default;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000092};
93
Eli Benderskya313ae62013-01-16 18:56:50 +000094typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
95
96struct MCAsmMacro {
97 StringRef Name;
98 StringRef Body;
99 MCAsmMacroParameters Parameters;
100
101public:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000102 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
103 : Name(N), Body(B), Parameters(std::move(P)) {}
Eli Benderskya313ae62013-01-16 18:56:50 +0000104};
105
Daniel Dunbar43235712010-07-18 18:54:11 +0000106/// \brief Helper class for storing information about an active macro
107/// instantiation.
108struct MacroInstantiation {
Daniel Dunbar43235712010-07-18 18:54:11 +0000109 /// The location of the instantiation.
110 SMLoc InstantiationLoc;
111
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000112 /// The buffer where parsing should resume upon instantiation completion.
113 int ExitBuffer;
114
Daniel Dunbar43235712010-07-18 18:54:11 +0000115 /// The location where parsing should resume upon instantiation completion.
116 SMLoc ExitLoc;
117
Nico Weber155dccd12014-07-24 17:08:39 +0000118 /// The depth of TheCondStack at the start of the instantiation.
119 size_t CondStackDepth;
120
Daniel Dunbar43235712010-07-18 18:54:11 +0000121public:
Rafael Espindola9eef18c2014-08-27 19:49:03 +0000122 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
Daniel Dunbar43235712010-07-18 18:54:11 +0000123};
124
Eli Friedman0f4871d2012-10-22 23:58:19 +0000125struct ParseStatementInfo {
Jim Grosbach4b905842013-09-20 23:08:21 +0000126 /// \brief The parsed operands from the last parsed statement.
David Blaikie960ea3f2014-06-08 16:18:35 +0000127 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000128
Jim Grosbach4b905842013-09-20 23:08:21 +0000129 /// \brief The opcode from the last parsed instruction.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000130 unsigned Opcode = ~0U;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000131
Jim Grosbach4b905842013-09-20 23:08:21 +0000132 /// \brief Was there an error parsing the inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000133 bool ParseError = false;
Chad Rosier149e8e02012-12-12 22:45:52 +0000134
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000135 SmallVectorImpl<AsmRewrite> *AsmRewrites = nullptr;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000136
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000137 ParseStatementInfo() = delete;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000138 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000139 : AsmRewrites(rewrites) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000140};
141
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000142/// \brief The concrete assembly parser instance.
143class AsmParser : public MCAsmParser {
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000144private:
145 AsmLexer Lexer;
146 MCContext &Ctx;
147 MCStreamer &Out;
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000148 const MCAsmInfo &MAI;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000149 SourceMgr &SrcMgr;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000150 SourceMgr::DiagHandlerTy SavedDiagHandler;
151 void *SavedDiagContext;
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000152 std::unique_ptr<MCAsmParserExtension> PlatformParser;
Rafael Espindola82065cb2011-04-11 21:49:50 +0000153
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000154 /// This is the current buffer index we're lexing from as managed by the
155 /// SourceMgr object.
Alp Tokera55b95b2014-07-06 10:33:31 +0000156 unsigned CurBuffer;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000157
158 AsmCond TheCondState;
159 std::vector<AsmCond> TheCondStack;
160
Jim Grosbach4b905842013-09-20 23:08:21 +0000161 /// \brief maps directive names to handler methods in parser
Eli Bendersky17233942013-01-15 22:59:42 +0000162 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000163 /// addDirectiveHandler.
Eli Bendersky17233942013-01-15 22:59:42 +0000164 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000165
Jim Grosbach4b905842013-09-20 23:08:21 +0000166 /// \brief Map of currently defined macros.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000167 StringMap<MCAsmMacro> MacroMap;
Daniel Dunbarc1f58ec2010-07-18 18:47:21 +0000168
Jim Grosbach4b905842013-09-20 23:08:21 +0000169 /// \brief Stack of active macro instantiations.
Daniel Dunbar43235712010-07-18 18:54:11 +0000170 std::vector<MacroInstantiation*> ActiveMacros;
171
Jim Grosbach4b905842013-09-20 23:08:21 +0000172 /// \brief List of bodies of anonymous macros.
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +0000173 std::deque<MCAsmMacro> MacroLikeBodies;
174
Daniel Dunbar828984f2010-07-18 18:38:02 +0000175 /// Boolean tracking whether macro substitution is enabled.
Eli Benderskyc2f6f922013-01-14 18:08:41 +0000176 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000177
Toma Tabacu217116e2015-04-27 10:50:29 +0000178 /// \brief Keeps track of how many .macro's have been instantiated.
179 unsigned NumOfMacroInstantiations;
180
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000181 /// The values from the last parsed cpp hash file line comment if any.
Tim Northoverc0bef992016-04-13 19:46:54 +0000182 struct CppHashInfoTy {
183 StringRef Filename;
Andrew Kaylorca196472016-04-21 20:09:35 +0000184 int64_t LineNumber = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000185 SMLoc Loc;
Andrew Kaylorca196472016-04-21 20:09:35 +0000186 unsigned Buf = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000187 };
188 CppHashInfoTy CppHashInfo;
189
190 /// \brief List of forward directional labels for diagnosis at the end.
191 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
192
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000193 /// When generating dwarf for assembly source files we need to calculate the
194 /// logical line number based on the last parsed cpp hash file line comment
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000195 /// and current line. Since this is slow and messes up the SourceMgr's
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000196 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
197 SMLoc LastQueryIDLoc;
Alp Tokera55b95b2014-07-06 10:33:31 +0000198 unsigned LastQueryBuffer;
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000199 unsigned LastQueryLine;
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000200
Devang Patela173ee52012-01-31 18:14:05 +0000201 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000202 unsigned AssemblerDialect = ~0U;
Devang Patela173ee52012-01-31 18:14:05 +0000203
Jim Grosbach4b905842013-09-20 23:08:21 +0000204 /// \brief is Darwin compatibility enabled?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000205 bool IsDarwin = false;
Preston Gurd05500642012-09-19 20:36:12 +0000206
Jim Grosbach4b905842013-09-20 23:08:21 +0000207 /// \brief Are we parsing ms-style inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000208 bool ParsingInlineAsm = false;
Chad Rosier49963552012-10-13 00:26:04 +0000209
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000210public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000211 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000212 const MCAsmInfo &MAI, unsigned CB);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000213 AsmParser(const AsmParser &) = delete;
214 AsmParser &operator=(const AsmParser &) = delete;
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000215 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000216
Craig Topper59be68f2014-03-08 07:14:16 +0000217 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000218
Craig Topper59be68f2014-03-08 07:14:16 +0000219 void addDirectiveHandler(StringRef Directive,
220 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000221 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000222 }
223
Toma Tabacu11e14a92015-04-21 11:50:52 +0000224 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
225 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
226 }
227
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000228 /// @name MCAsmParser Interface
229 /// {
230
Craig Topper59be68f2014-03-08 07:14:16 +0000231 SourceMgr &getSourceManager() override { return SrcMgr; }
232 MCAsmLexer &getLexer() override { return Lexer; }
233 MCContext &getContext() override { return Ctx; }
234 MCStreamer &getStreamer() override { return Out; }
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000235
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000236 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
237
Craig Topper59be68f2014-03-08 07:14:16 +0000238 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000239 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000240 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000241 else
242 return AssemblerDialect;
243 }
Craig Topper59be68f2014-03-08 07:14:16 +0000244 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000245 AssemblerDialect = i;
246 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000247
Nirav Dave2364748a2016-09-16 18:30:20 +0000248 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
249 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
250 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000251
Craig Topper59be68f2014-03-08 07:14:16 +0000252 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000253
Yunzhong Gao27ea29b2016-09-02 23:15:29 +0000254 void setParsingInlineAsm(bool V) override {
255 ParsingInlineAsm = V;
256 Lexer.setParsingMSInlineAsm(V);
257 }
Craig Topper59be68f2014-03-08 07:14:16 +0000258 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000259
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000260 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000261 unsigned &NumOutputs, unsigned &NumInputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000262 SmallVectorImpl<std::pair<void *,bool>> &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000263 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000264 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000265 const MCInstrInfo *MII, const MCInstPrinter *IP,
266 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000267
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000268 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000269 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
270 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
271 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000272 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
273 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000274 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000275
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000276 /// \brief Parse a floating point expression using the float \p Semantics
277 /// and set \p Res to the value.
278 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
279
Jim Grosbach4b905842013-09-20 23:08:21 +0000280 /// \brief Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000281 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000282 bool parseIdentifier(StringRef &Res) override;
283 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000284
Nirav Davef43cc9f2016-10-10 15:24:54 +0000285 bool checkForValidSection() override;
Nirav Davea645433c2016-07-18 15:24:03 +0000286
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000287 /// }
288
289private:
Michael Zuckerman763e60e2017-05-04 10:37:00 +0000290 bool isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc);
Michael Zuckerman1f1a9122017-05-10 13:08:11 +0000291 void altMacroString(StringRef AltMacroStr, std::string &Res);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000292 bool parseStatement(ParseStatementInfo &Info,
293 MCAsmParserSemaCallback *SI);
Marina Yatsina5f5de9f2016-03-07 18:11:16 +0000294 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
Craig Topper3c76c522015-09-20 23:35:59 +0000295 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000296
Jim Grosbach4b905842013-09-20 23:08:21 +0000297 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000298 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000299 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000300 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000301 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000302 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000303
Eli Benderskya313ae62013-01-16 18:56:50 +0000304 /// \brief Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000305 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000306
307 /// \brief Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000308 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000309
310 /// \brief Lookup a previously defined macro.
311 /// \param Name Macro name.
312 /// \returns Pointer to macro. NULL if no such macro was defined.
Jim Grosbach4b905842013-09-20 23:08:21 +0000313 const MCAsmMacro* lookupMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000314
315 /// \brief Define a new macro with the given name and information.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000316 void defineMacro(StringRef Name, MCAsmMacro Macro);
Eli Benderskya313ae62013-01-16 18:56:50 +0000317
318 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
Jim Grosbach4b905842013-09-20 23:08:21 +0000319 void undefineMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000320
321 /// \brief Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000322 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000323
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000324 /// \brief Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000325 ///
326 /// \param M The macro.
327 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000328 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000329
330 /// \brief Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000331 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000332
David Majnemer91fc4c22014-01-29 18:57:46 +0000333 /// \brief Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000334 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000335
336 /// \brief Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000337 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000338
Jim Grosbach4b905842013-09-20 23:08:21 +0000339 void printMacroInstantiations();
340 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Nirav Dave2364748a2016-09-16 18:30:20 +0000341 SMRange Range = None) const {
342 ArrayRef<SMRange> Ranges(Range);
Chris Lattner72845262011-10-16 05:47:55 +0000343 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000344 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000345 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000346
Jim Grosbach4b905842013-09-20 23:08:21 +0000347 /// \brief Enter the specified file. This returns true on failure.
348 bool enterIncludeFile(const std::string &Filename);
349
350 /// \brief Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000351 /// This returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000352 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
353 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
Daniel Dunbar43235712010-07-18 18:54:11 +0000354
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000355 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000356 /// current token is not set; clients should ensure Lex() is called
357 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000358 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000359 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000360 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000361 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000362
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000363 /// \brief Parse up to the end of statement and a return the contents from the
364 /// current token until the end of the statement; the current token on exit
365 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000366 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000367
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000368 /// \brief Parse until the end of a statement or a comma is encountered,
369 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000370 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000371
Jim Grosbach4b905842013-09-20 23:08:21 +0000372 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +0000373 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000374
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000375 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
376 MCBinaryExpr::Opcode &Kind);
377
Jim Grosbach4b905842013-09-20 23:08:21 +0000378 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
379 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
380 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000381
Jim Grosbach4b905842013-09-20 23:08:21 +0000382 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000383
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000384 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
385 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
386
Eli Bendersky17233942013-01-15 22:59:42 +0000387 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000388 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000389 DK_NO_DIRECTIVE, // Placeholder
390 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000391 DK_RELOC,
David Woodhoused6de0d92014-02-01 16:20:59 +0000392 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
Petr Hosek731bb9c2016-08-23 21:34:53 +0000393 DK_DC, DK_DC_A, DK_DC_B, DK_DC_D, DK_DC_L, DK_DC_S, DK_DC_W, DK_DC_X,
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000394 DK_DCB, DK_DCB_B, DK_DCB_D, DK_DCB_L, DK_DCB_S, DK_DCB_W, DK_DCB_X,
Petr Hosek85b2f672016-09-23 21:53:36 +0000395 DK_DS, DK_DS_B, DK_DS_D, DK_DS_L, DK_DS_P, DK_DS_S, DK_DS_W, DK_DS_X,
David Woodhoused6de0d92014-02-01 16:20:59 +0000396 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky96522722013-01-11 22:55:28 +0000397 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000398 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
Kevin Enderby3aeada22013-08-28 17:50:59 +0000399 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
Lang Hamesf9033bb2016-04-11 18:33:45 +0000400 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER,
Lang Hames1b640e02016-03-15 01:43:05 +0000401 DK_PRIVATE_EXTERN, DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000402 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
403 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000404 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
Sid Manning51c35602015-03-18 14:20:54 +0000405 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
406 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
Eli Bendersky17233942013-01-15 22:59:42 +0000407 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000408 DK_CV_FILE, DK_CV_FUNC_ID, DK_CV_INLINE_SITE_ID, DK_CV_LOC, DK_CV_LINETABLE,
409 DK_CV_INLINE_LINETABLE, DK_CV_DEF_RANGE, DK_CV_STRINGTABLE,
410 DK_CV_FILECHECKSUMS,
Eli Bendersky17233942013-01-15 22:59:42 +0000411 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
412 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
413 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
414 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
415 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000416 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
Michael Zuckerman56704612017-05-01 13:20:12 +0000417 DK_MACROS_ON, DK_MACROS_OFF, DK_ALTMACRO, DK_NOALTMACRO,
Nico Weber155dccd12014-07-24 17:08:39 +0000418 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000419 DK_SLEB128, DK_ULEB128,
Nico Weber404012b2014-07-24 16:26:06 +0000420 DK_ERR, DK_ERROR, DK_WARNING,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000421 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000422 };
423
Jim Grosbach4b905842013-09-20 23:08:21 +0000424 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000425 /// directives parsed by this class.
426 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000427
428 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000429 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000430 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Nirav Dave1a9044b2016-10-24 14:35:29 +0000431 bool parseDirectiveValue(StringRef IDVal,
432 unsigned Size); // ".byte", ".long", ...
433 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
434 bool parseDirectiveRealValue(StringRef IDVal,
435 const fltSemantics &); // ".single", ...
Jim Grosbach4b905842013-09-20 23:08:21 +0000436 bool parseDirectiveFill(); // ".fill"
437 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000438 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000439 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
440 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000441 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000442 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000443
Eli Bendersky17233942013-01-15 22:59:42 +0000444 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000445 bool parseDirectiveFile(SMLoc DirectiveLoc);
446 bool parseDirectiveLine();
447 bool parseDirectiveLoc();
448 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000449
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000450 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
451 // ".cv_inline_linetable", ".cv_def_range"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000452 bool parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000453 bool parseDirectiveCVFuncId();
454 bool parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000455 bool parseDirectiveCVLoc();
456 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000457 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000458 bool parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000459 bool parseDirectiveCVStringTable();
460 bool parseDirectiveCVFileChecksums();
461
Eli Bendersky17233942013-01-15 22:59:42 +0000462 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000463 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000464 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000465 bool parseDirectiveCFISections();
466 bool parseDirectiveCFIStartProc();
467 bool parseDirectiveCFIEndProc();
468 bool parseDirectiveCFIDefCfaOffset();
469 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
470 bool parseDirectiveCFIAdjustCfaOffset();
471 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
472 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
473 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
474 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
475 bool parseDirectiveCFIRememberState();
476 bool parseDirectiveCFIRestoreState();
477 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
478 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
479 bool parseDirectiveCFIEscape();
480 bool parseDirectiveCFISignalFrame();
481 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000482
483 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000484 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000485 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000486 bool parseDirectiveEndMacro(StringRef Directive);
487 bool parseDirectiveMacro(SMLoc DirectiveLoc);
488 bool parseDirectiveMacrosOnOff(StringRef Directive);
Michael Zuckerman56704612017-05-01 13:20:12 +0000489 // alternate macro mode directives
490 bool parseDirectiveAltmacro(StringRef Directive);
Eli Benderskyf483ff92012-12-20 19:05:53 +0000491 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000492 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000493 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000494 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000495 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000496 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000497
Eli Bendersky17233942013-01-15 22:59:42 +0000498 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000499 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000500
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000501 // ".dcb"
502 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
503 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
Petr Hosek85b2f672016-09-23 21:53:36 +0000504 // ".ds"
505 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000506
Eli Bendersky17233942013-01-15 22:59:42 +0000507 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000508 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000509
Jim Grosbach4b905842013-09-20 23:08:21 +0000510 /// \brief Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000511 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000512 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000513
Jim Grosbach4b905842013-09-20 23:08:21 +0000514 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000515
Jim Grosbach4b905842013-09-20 23:08:21 +0000516 bool parseDirectiveAbort(); // ".abort"
517 bool parseDirectiveInclude(); // ".include"
518 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000519
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000520 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
521 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000522 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000523 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000524 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000525 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000526 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
527 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000528 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000529 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
530 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
531 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
532 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000533 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000534
Jim Grosbach4b905842013-09-20 23:08:21 +0000535 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000536 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000537
Rafael Espindola34b9c512012-06-03 23:57:14 +0000538 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000539 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
540 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000541 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000542 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000543 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
544 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
545 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000546
Chad Rosierc7f552c2013-02-12 21:33:51 +0000547 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000548 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000549 size_t Len);
550
551 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000552 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000553
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000554 // "end"
555 bool parseDirectiveEnd(SMLoc DirectiveLoc);
556
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000557 // ".err" or ".error"
558 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000559
Nico Weber404012b2014-07-24 16:26:06 +0000560 // ".warning"
561 bool parseDirectiveWarning(SMLoc DirectiveLoc);
562
Eli Bendersky17233942013-01-15 22:59:42 +0000563 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000564};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000565
566} // end anonymous namespace
Daniel Dunbar86033402010-07-12 17:54:38 +0000567
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000568namespace llvm {
569
570extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000571extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000572extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000573
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000574} // end namespace llvm
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000575
Chris Lattnerc35681b2010-01-19 19:46:13 +0000576enum { DEFAULT_ADDRSPACE = 0 };
577
David Blaikie9f380a32015-03-16 18:06:57 +0000578AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000579 const MCAsmInfo &MAI, unsigned CB = 0)
David Blaikie9f380a32015-03-16 18:06:57 +0000580 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000581 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
Nirav Dave2364748a2016-09-16 18:30:20 +0000582 HadError = false;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000583 // Save the old handler.
584 SavedDiagHandler = SrcMgr.getDiagHandler();
585 SavedDiagContext = SrcMgr.getDiagContext();
586 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000587 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000588 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000589
Daniel Dunbarc5011082010-07-12 18:12:02 +0000590 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000591 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
592 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000593 PlatformParser.reset(createCOFFAsmParser());
594 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000595 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000596 PlatformParser.reset(createDarwinAsmParser());
597 IsDarwin = true;
598 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000599 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000600 PlatformParser.reset(createELFAsmParser());
601 break;
Dan Gohman18eafb62017-02-22 01:23:18 +0000602 case MCObjectFileInfo::IsWasm:
603 llvm_unreachable("Wasm parsing not supported yet");
604 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000605 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000606
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000607 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000608 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000609
610 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000611}
612
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000613AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000614 assert((HadError || ActiveMacros.empty()) &&
615 "Unexpected active macro instantiation!");
Sanne Wouda29338752017-02-08 14:48:05 +0000616
617 // Restore the saved diagnostics handler and context for use during
618 // finalization.
619 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000620}
621
Jim Grosbach4b905842013-09-20 23:08:21 +0000622void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000623 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000624 for (std::vector<MacroInstantiation *>::const_reverse_iterator
625 it = ActiveMacros.rbegin(),
626 ie = ActiveMacros.rend();
627 it != ie; ++it)
628 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000629 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000630}
631
Nirav Dave2364748a2016-09-16 18:30:20 +0000632void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
633 printPendingErrors();
634 printMessage(L, SourceMgr::DK_Note, Msg, Range);
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000635 printMacroInstantiations();
636}
637
Nirav Dave2364748a2016-09-16 18:30:20 +0000638bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000639 if(getTargetParser().getTargetOptions().MCNoWarn)
640 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000641 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Nirav Dave2364748a2016-09-16 18:30:20 +0000642 return Error(L, Msg, Range);
643 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000644 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000645 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000646}
647
Nirav Dave2364748a2016-09-16 18:30:20 +0000648bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000649 HadError = true;
Nirav Dave2364748a2016-09-16 18:30:20 +0000650 printMessage(L, SourceMgr::DK_Error, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000651 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000652 return true;
653}
654
Jim Grosbach4b905842013-09-20 23:08:21 +0000655bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000656 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000657 unsigned NewBuf =
658 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
659 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000660 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000661
Sean Callanan7a77eae2010-01-21 00:19:58 +0000662 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000663 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000664 return false;
665}
Daniel Dunbar43235712010-07-18 18:54:11 +0000666
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000667/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000668/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000669/// returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000670bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
671 const MCExpr *Count, SMLoc Loc) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000672 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000673 unsigned NewBuf =
674 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
675 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000676 return true;
677
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000678 // Pick up the bytes from the file and emit them.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000679 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
680 Bytes = Bytes.drop_front(Skip);
681 if (Count) {
682 int64_t Res;
683 if (!Count->evaluateAsAbsolute(Res))
684 return Error(Loc, "expected absolute expression");
685 if (Res < 0)
686 return Warning(Loc, "negative count has no effect");
687 Bytes = Bytes.take_front(Res);
688 }
689 getStreamer().EmitBytes(Bytes);
Kevin Enderby109f25c2011-12-14 21:47:48 +0000690 return false;
691}
692
Alp Tokera55b95b2014-07-06 10:33:31 +0000693void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
694 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000695 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
696 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000697}
698
Sean Callanan7a77eae2010-01-21 00:19:58 +0000699const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000700 if (Lexer.getTok().is(AsmToken::Error))
701 Error(Lexer.getErrLoc(), Lexer.getErr());
702
Nirav Dave53a72f42016-07-11 12:42:14 +0000703 // if it's a end of statement with a comment in it
704 if (getTok().is(AsmToken::EndOfStatement)) {
705 // if this is a line comment output it.
706 if (getTok().getString().front() != '\n' &&
707 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
708 Out.addExplicitComment(Twine(getTok().getString()));
709 }
710
Sean Callanan7a77eae2010-01-21 00:19:58 +0000711 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000712
713 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000714 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000715 if (MAI.preserveAsmComments())
716 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000717 tok = &Lexer.Lex();
718 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000719
Sean Callanan7a77eae2010-01-21 00:19:58 +0000720 if (tok->is(AsmToken::Eof)) {
721 // If this is the end of an included file, pop the parent file off the
722 // include stack.
723 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
724 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000725 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000726 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000727 }
728 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000729
Sean Callanan7a77eae2010-01-21 00:19:58 +0000730 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000731}
732
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000733bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000734 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000735 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000736 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000737
Chris Lattner36e02122009-06-21 20:54:55 +0000738 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000739 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000740
741 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000742 AsmCond StartingCondState = TheCondState;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000743 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000744
Kevin Enderby6469fc22011-11-01 22:27:22 +0000745 // If we are generating dwarf for assembly source files save the initial text
746 // section and generate a .file directive.
747 if (getContext().getGenDwarfForAssembly()) {
Eric Christopher445c9522016-10-14 05:47:37 +0000748 MCSection *Sec = getStreamer().getCurrentSectionOnly();
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000749 if (!Sec->getBeginSymbol()) {
750 MCSymbol *SectionStartSym = getContext().createTempSymbol();
751 getStreamer().EmitLabel(SectionStartSym);
752 Sec->setBeginSymbol(SectionStartSym);
753 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000754 bool InsertResult = getContext().addGenDwarfSection(Sec);
755 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000756 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000757 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
758 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000759 }
760
Chris Lattner73f36112009-07-02 21:53:43 +0000761 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000762 while (Lexer.isNot(AsmToken::Eof)) {
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000763 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000764 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000765 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000766
Nirav Dave2364748a2016-09-16 18:30:20 +0000767 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
768 // for printing ErrMsg via Lex() only if no (presumably better) parser error
769 // exists.
770 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
Nirav Dave1180e6892016-06-02 17:15:05 +0000771 Lex();
772 }
773
Nirav Dave2364748a2016-09-16 18:30:20 +0000774 // parseStatement returned true so may need to emit an error.
775 printPendingErrors();
776
777 // Skipping to the next line if needed.
778 if (!getLexer().isAtStartOfStatement())
779 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000780 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000781
Nirav Dave2364748a2016-09-16 18:30:20 +0000782 // All errors should have been emitted.
783 assert(!hasPendingError() && "unexpected error from parseStatement");
784
Oliver Stannard21718282016-07-26 14:19:47 +0000785 getTargetParser().flushPendingInstructions(getStreamer());
786
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000787 if (TheCondState.TheCond != StartingCondState.TheCond ||
788 TheCondState.Ignore != StartingCondState.Ignore)
Nirav Dave2364748a2016-09-16 18:30:20 +0000789 printError(getTok().getLoc(), "unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000790 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000791 const auto &LineTables = getContext().getMCDwarfLineTables();
792 if (!LineTables.empty()) {
793 unsigned Index = 0;
794 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
795 if (File.Name.empty() && Index != 0)
Nirav Dave2364748a2016-09-16 18:30:20 +0000796 printError(getTok().getLoc(), "unassigned file number: " +
797 Twine(Index) +
798 " for .file directives");
David Blaikie8bf66c42014-04-01 07:35:52 +0000799 ++Index;
800 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000801 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000802
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000803 // Check to see that all assembler local symbols were actually defined.
804 // Targets that don't do subsections via symbols may not want this, though,
805 // so conservatively exclude them. Only do this if we're finalizing, though,
806 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000807 if (!NoFinalize) {
808 if (MAI.hasSubsectionsViaSymbols()) {
809 for (const auto &TableEntry : getContext().getSymbols()) {
810 MCSymbol *Sym = TableEntry.getValue();
811 // Variable symbols may not be marked as defined, so check those
812 // explicitly. If we know it's a variable, we have a definition for
813 // the purposes of this check.
814 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
815 // FIXME: We would really like to refer back to where the symbol was
816 // first referenced for a source location. We need to add something
817 // to track that. Currently, we just point to the end of the file.
Nirav Dave2364748a2016-09-16 18:30:20 +0000818 printError(getTok().getLoc(), "assembler local symbol '" +
819 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000820 }
821 }
822
823 // Temporary symbols like the ones for directional jumps don't go in the
824 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000825 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
826 if (std::get<2>(LocSym)->isUndefined()) {
827 // Reset the state of any "# line file" directives we've seen to the
828 // context as it was at the diagnostic site.
829 CppHashInfo = std::get<1>(LocSym);
Nirav Dave2364748a2016-09-16 18:30:20 +0000830 printError(std::get<0>(LocSym), "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000831 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000832 }
833 }
834
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000835 // Finalize the output stream if there are no errors and if the client wants
836 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000837 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000838 Out.Finish();
839
Oliver Stannard07b43d32015-11-17 09:58:07 +0000840 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000841}
842
Nirav Davef43cc9f2016-10-10 15:24:54 +0000843bool AsmParser::checkForValidSection() {
Eric Christopher445c9522016-10-14 05:47:37 +0000844 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000845 Out.InitSections(false);
Nirav Davef43cc9f2016-10-10 15:24:54 +0000846 return Error(getTok().getLoc(),
847 "expected section directive before assembly directive");
Daniel Dunbare5444a82010-09-09 22:42:59 +0000848 }
Nirav Davef43cc9f2016-10-10 15:24:54 +0000849 return false;
Daniel Dunbare5444a82010-09-09 22:42:59 +0000850}
851
Jim Grosbach4b905842013-09-20 23:08:21 +0000852/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000853void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000854 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000855 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000856
Chris Lattnere5074c42009-06-22 01:29:09 +0000857 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000858 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000859 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000860}
861
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000862StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000863 const char *Start = getTok().getLoc().getPointer();
864
Jim Grosbach4b905842013-09-20 23:08:21 +0000865 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000866 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000867
868 const char *End = getTok().getLoc().getPointer();
869 return StringRef(Start, End - Start);
870}
Chris Lattner78db3622009-06-22 05:51:26 +0000871
Jim Grosbach4b905842013-09-20 23:08:21 +0000872StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000873 const char *Start = getTok().getLoc().getPointer();
874
875 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000876 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000877 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000878
879 const char *End = getTok().getLoc().getPointer();
880 return StringRef(Start, End - Start);
881}
882
Jim Grosbach4b905842013-09-20 23:08:21 +0000883/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000884/// NOTE: This assumes the leading '(' has already been consumed.
885///
886/// parenexpr ::= expr)
887///
Jim Grosbach4b905842013-09-20 23:08:21 +0000888bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
889 if (parseExpression(Res))
890 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000891 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +0000892 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000893 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000894 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +0000895 return false;
896}
Chris Lattner78db3622009-06-22 05:51:26 +0000897
Jim Grosbach4b905842013-09-20 23:08:21 +0000898/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000899/// NOTE: This assumes the leading '[' has already been consumed.
900///
901/// bracketexpr ::= expr]
902///
Jim Grosbach4b905842013-09-20 23:08:21 +0000903bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
904 if (parseExpression(Res))
905 return true;
Nirav Davea645433c2016-07-18 15:24:03 +0000906 EndLoc = getTok().getEndLoc();
907 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
908 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000909 return false;
910}
911
Jim Grosbach4b905842013-09-20 23:08:21 +0000912/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000913/// primaryexpr ::= (parenexpr
914/// primaryexpr ::= symbol
915/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +0000916/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +0000917/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +0000918bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000919 SMLoc FirstTokenLoc = getLexer().getLoc();
920 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
921 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +0000922 default:
923 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +0000924 // If we have an error assume that we've already handled it.
925 case AsmToken::Error:
926 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000927 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000928 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000929 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000930 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +0000931 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000932 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +0000933 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +0000934 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +0000935 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +0000936 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +0000937 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000938 if (parseIdentifier(Identifier)) {
Nirav Daved0463322016-10-12 13:58:07 +0000939 // We may have failed but $ may be a valid token.
940 if (getTok().is(AsmToken::Dollar)) {
David Majnemer0c58bc62013-09-25 10:47:21 +0000941 if (Lexer.getMAI().getDollarIsPC()) {
Nirav Daved0463322016-10-12 13:58:07 +0000942 Lex();
David Majnemer0c58bc62013-09-25 10:47:21 +0000943 // This is a '$' reference, which references the current PC. Emit a
944 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000945 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +0000946 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000947 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +0000948 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +0000949 EndLoc = FirstTokenLoc;
950 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +0000951 }
952 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +0000953 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000954 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000955 // Parse symbol variant
956 std::pair<StringRef, StringRef> Split;
957 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +0000958 if (FirstTokenKind == AsmToken::String) {
959 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +0000960 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +0000961 SMLoc AtLoc = getLexer().getLoc();
962 StringRef VName;
963 if (parseIdentifier(VName))
964 return Error(AtLoc, "expected symbol variant after '@'");
965
966 Split = std::make_pair(Identifier, VName);
967 }
968 } else {
969 Split = Identifier.split('@');
970 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000971 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +0000972 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +0000973 StringRef VName;
974 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +0000975 // eat ')'.
976 if (parseToken(AsmToken::RParen,
977 "unexpected token in variant, expected ')'"))
978 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +0000979 Split = std::make_pair(Identifier, VName);
980 }
Daniel Dunbar24764322010-08-24 19:13:42 +0000981
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000982 EndLoc = SMLoc::getFromPointer(Identifier.end());
983
Daniel Dunbard20cda02009-10-16 01:34:54 +0000984 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +0000985 StringRef SymbolName = Identifier;
Weiming Zhaocf26d562016-12-01 18:00:36 +0000986 if (SymbolName.empty())
987 return true;
988
Hans Wennborgce69d772013-10-18 20:46:28 +0000989 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +0000990
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000991 // Lookup the symbol variant if used.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000992 if (!Split.second.empty()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000993 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +0000994 if (Variant != MCSymbolRefExpr::VK_Invalid) {
995 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +0000996 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +0000997 Variant = MCSymbolRefExpr::VK_None;
998 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +0000999 return Error(SMLoc::getFromPointer(Split.second.begin()),
1000 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001001 }
1002 }
Daniel Dunbar55992562010-03-15 23:51:06 +00001003
Jim Grosbach6f482002015-05-18 18:43:14 +00001004 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +00001005
Daniel Dunbard20cda02009-10-16 01:34:54 +00001006 // If this is an absolute variable reference, substitute it now to preserve
1007 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +00001008 if (Sym->isVariable() &&
1009 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +00001010 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +00001011 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +00001012
Vedant Kumar86dbd922015-08-31 17:44:53 +00001013 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +00001014 return false;
1015 }
1016
1017 // Otherwise create a symbol ref.
Chad Rosier9245e122017-01-19 20:06:32 +00001018 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
Chris Lattner78db3622009-06-22 05:51:26 +00001019 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001020 }
David Woodhousef42a6662014-02-01 16:20:54 +00001021 case AsmToken::BigNum:
1022 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001023 case AsmToken::Integer: {
1024 SMLoc Loc = getTok().getLoc();
1025 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001026 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001027 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001028 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001029 // Look for 'b' or 'f' following an Integer as a directional label
1030 if (Lexer.getKind() == AsmToken::Identifier) {
1031 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001032 // Lookup the symbol variant if used.
1033 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1034 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1035 if (Split.first.size() != IDVal.size()) {
1036 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001037 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001038 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001039 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001040 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001041 if (IDVal == "f" || IDVal == "b") {
1042 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001043 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001044 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001045 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001046 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001047 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001048 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001049 Lex(); // Eat identifier.
1050 }
1051 }
Chris Lattner78db3622009-06-22 05:51:26 +00001052 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001053 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001054 case AsmToken::Real: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001055 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001056 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001057 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001058 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001059 Lex(); // Eat token.
1060 return false;
1061 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001062 case AsmToken::Dot: {
1063 // This is a '.' reference, which references the current PC. Emit a
1064 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001065 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001066 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001067 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001068 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001069 Lex(); // Eat identifier.
1070 return false;
1071 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001072 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001073 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001074 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001075 case AsmToken::LBrac:
1076 if (!PlatformParser->HasBracketExpressions())
1077 return TokError("brackets expression not supported on this target");
1078 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001079 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001080 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001081 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001082 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001083 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001084 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001085 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001086 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001087 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001088 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001089 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001090 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001091 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001092 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001093 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001094 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001095 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001096 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001097 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001098 // MIPS unary expression operators. The lexer won't generate these tokens if
1099 // MCAsmInfo::HasMipsExpressions is false for the target.
1100 case AsmToken::PercentCall16:
1101 case AsmToken::PercentCall_Hi:
1102 case AsmToken::PercentCall_Lo:
1103 case AsmToken::PercentDtprel_Hi:
1104 case AsmToken::PercentDtprel_Lo:
1105 case AsmToken::PercentGot:
1106 case AsmToken::PercentGot_Disp:
1107 case AsmToken::PercentGot_Hi:
1108 case AsmToken::PercentGot_Lo:
1109 case AsmToken::PercentGot_Ofst:
1110 case AsmToken::PercentGot_Page:
1111 case AsmToken::PercentGottprel:
1112 case AsmToken::PercentGp_Rel:
1113 case AsmToken::PercentHi:
1114 case AsmToken::PercentHigher:
1115 case AsmToken::PercentHighest:
1116 case AsmToken::PercentLo:
1117 case AsmToken::PercentNeg:
1118 case AsmToken::PercentPcrel_Hi:
1119 case AsmToken::PercentPcrel_Lo:
1120 case AsmToken::PercentTlsgd:
1121 case AsmToken::PercentTlsldm:
1122 case AsmToken::PercentTprel_Hi:
1123 case AsmToken::PercentTprel_Lo:
1124 Lex(); // Eat the operator.
1125 if (Lexer.isNot(AsmToken::LParen))
1126 return TokError("expected '(' after operator");
1127 Lex(); // Eat the operator.
1128 if (parseExpression(Res, EndLoc))
1129 return true;
1130 if (Lexer.isNot(AsmToken::RParen))
1131 return TokError("expected ')'");
1132 Lex(); // Eat the operator.
1133 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1134 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001135 }
1136}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001137
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001138bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001139 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001140 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001141}
1142
Daniel Dunbar55f16672010-09-17 02:47:07 +00001143const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001144AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001145 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001146 // Ask the target implementation about this expression first.
1147 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1148 if (NewE)
1149 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001150 // Recurse over the given expression, rebuilding it to apply the given variant
1151 // if there is exactly one symbol.
1152 switch (E->getKind()) {
1153 case MCExpr::Target:
1154 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001155 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001156
1157 case MCExpr::SymbolRef: {
1158 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1159
1160 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001161 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1162 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001163 return E;
1164 }
1165
Jim Grosbach13760bd2015-05-30 01:25:56 +00001166 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001167 }
1168
1169 case MCExpr::Unary: {
1170 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001171 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001172 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001173 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001174 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001175 }
1176
1177 case MCExpr::Binary: {
1178 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001179 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1180 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001181
1182 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001183 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001184
Jim Grosbach4b905842013-09-20 23:08:21 +00001185 if (!LHS)
1186 LHS = BE->getLHS();
1187 if (!RHS)
1188 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001189
Jim Grosbach13760bd2015-05-30 01:25:56 +00001190 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001191 }
1192 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001193
Craig Toppera2886c22012-02-07 05:05:23 +00001194 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001195}
1196
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001197/// This function checks if the next token is <string> type or arithmetic.
1198/// string that begin with character '<' must end with character '>'.
1199/// otherwise it is arithmetics.
1200/// If the function returns a 'true' value,
1201/// the End argument will be filled with the last location pointed to the '>'
1202/// character.
1203
1204/// There is a gap between the AltMacro's documentation and the single quote implementation.
1205/// GCC does not fully support this feature and so we will not support it.
1206/// TODO: Adding single quote as a string.
1207bool AsmParser::isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc) {
1208 assert((StrLoc.getPointer() != NULL) &&
1209 "Argument to the function cannot be a NULL value");
1210 const char *CharPtr = StrLoc.getPointer();
1211 while ((*CharPtr != '>') && (*CharPtr != '\n') &&
1212 (*CharPtr != '\r') && (*CharPtr != '\0')){
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001213 if(*CharPtr == '!')
1214 CharPtr++;
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001215 CharPtr++;
1216 }
1217 if (*CharPtr == '>') {
1218 EndLoc = StrLoc.getFromPointer(CharPtr + 1);
1219 return true;
1220 }
1221 return false;
1222}
1223
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001224/// \brief creating a string without the escape characters '!'.
1225void AsmParser::altMacroString(StringRef AltMacroStr,std::string &Res) {
1226 for (int Pos = 0; Pos < AltMacroStr.size(); Pos++) {
1227 if (AltMacroStr[Pos] == '!')
1228 Pos++;
1229 Res += AltMacroStr[Pos];
1230 }
1231}
1232
Jim Grosbach4b905842013-09-20 23:08:21 +00001233/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001234///
Jim Grosbachbd164242011-08-20 16:24:13 +00001235/// expr ::= expr &&,|| expr -> lowest.
1236/// expr ::= expr |,^,&,! expr
1237/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1238/// expr ::= expr <<,>> expr
1239/// expr ::= expr +,- expr
1240/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001241/// expr ::= primaryexpr
1242///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001243bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001244 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001245 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001246 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001247 return true;
1248
Daniel Dunbar55f16672010-09-17 02:47:07 +00001249 // As a special case, we support 'a op b @ modifier' by rewriting the
1250 // expression to include the modifier. This is inefficient, but in general we
1251 // expect users to use 'a@modifier op b'.
1252 if (Lexer.getKind() == AsmToken::At) {
1253 Lex();
1254
1255 if (Lexer.isNot(AsmToken::Identifier))
1256 return TokError("unexpected symbol modifier following '@'");
1257
1258 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001259 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001260 if (Variant == MCSymbolRefExpr::VK_Invalid)
1261 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1262
Jim Grosbach4b905842013-09-20 23:08:21 +00001263 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001264 if (!ModifiedRes) {
1265 return TokError("invalid modifier '" + getTok().getIdentifier() +
1266 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001267 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001268
Daniel Dunbar55f16672010-09-17 02:47:07 +00001269 Res = ModifiedRes;
1270 Lex();
1271 }
1272
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001273 // Try to constant fold it up front, if possible.
1274 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001275 if (Res->evaluateAsAbsolute(Value))
1276 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001277
1278 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001279}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001280
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001281bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001282 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001283 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001284}
1285
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001286bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1287 SMLoc &EndLoc) {
1288 if (parseParenExpr(Res, EndLoc))
1289 return true;
1290
1291 for (; ParenDepth > 0; --ParenDepth) {
1292 if (parseBinOpRHS(1, Res, EndLoc))
1293 return true;
1294
1295 // We don't Lex() the last RParen.
1296 // This is the same behavior as parseParenExpression().
1297 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001298 EndLoc = getTok().getEndLoc();
1299 if (parseToken(AsmToken::RParen,
1300 "expected ')' in parentheses expression"))
1301 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001302 }
1303 }
1304 return false;
1305}
1306
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001307bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001308 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001309
Daniel Dunbar75630b32009-06-30 02:10:03 +00001310 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001311 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001312 return true;
1313
Jim Grosbach13760bd2015-05-30 01:25:56 +00001314 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001315 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001316
1317 return false;
1318}
1319
David Majnemer0993e0b2015-10-26 03:15:34 +00001320static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1321 MCBinaryExpr::Opcode &Kind,
1322 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001323 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001324 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001325 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001326
Jim Grosbach4b905842013-09-20 23:08:21 +00001327 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001328 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001329 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001330 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001331 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001332 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001333 return 1;
1334
Jim Grosbach4b905842013-09-20 23:08:21 +00001335 // Low Precedence: |, &, ^
1336 //
1337 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001338 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001339 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001340 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001341 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001342 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001343 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001344 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001345 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001346 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001347
Jim Grosbach4b905842013-09-20 23:08:21 +00001348 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001349 case AsmToken::EqualEqual:
1350 Kind = MCBinaryExpr::EQ;
1351 return 3;
1352 case AsmToken::ExclaimEqual:
1353 case AsmToken::LessGreater:
1354 Kind = MCBinaryExpr::NE;
1355 return 3;
1356 case AsmToken::Less:
1357 Kind = MCBinaryExpr::LT;
1358 return 3;
1359 case AsmToken::LessEqual:
1360 Kind = MCBinaryExpr::LTE;
1361 return 3;
1362 case AsmToken::Greater:
1363 Kind = MCBinaryExpr::GT;
1364 return 3;
1365 case AsmToken::GreaterEqual:
1366 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001367 return 3;
1368
Jim Grosbach4b905842013-09-20 23:08:21 +00001369 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001370 case AsmToken::LessLess:
1371 Kind = MCBinaryExpr::Shl;
1372 return 4;
1373 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001374 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001375 return 4;
1376
Jim Grosbach4b905842013-09-20 23:08:21 +00001377 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001378 case AsmToken::Plus:
1379 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001380 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001381 case AsmToken::Minus:
1382 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001383 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001384
Jim Grosbach4b905842013-09-20 23:08:21 +00001385 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001386 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001387 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001388 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001389 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001390 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001391 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001392 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001393 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001394 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001395 }
1396}
1397
David Majnemer0993e0b2015-10-26 03:15:34 +00001398static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1399 MCBinaryExpr::Opcode &Kind,
1400 bool ShouldUseLogicalShr) {
1401 switch (K) {
1402 default:
1403 return 0; // not a binop.
1404
1405 // Lowest Precedence: &&, ||
1406 case AsmToken::AmpAmp:
1407 Kind = MCBinaryExpr::LAnd;
1408 return 2;
1409 case AsmToken::PipePipe:
1410 Kind = MCBinaryExpr::LOr;
1411 return 1;
1412
1413 // Low Precedence: ==, !=, <>, <, <=, >, >=
1414 case AsmToken::EqualEqual:
1415 Kind = MCBinaryExpr::EQ;
1416 return 3;
1417 case AsmToken::ExclaimEqual:
1418 case AsmToken::LessGreater:
1419 Kind = MCBinaryExpr::NE;
1420 return 3;
1421 case AsmToken::Less:
1422 Kind = MCBinaryExpr::LT;
1423 return 3;
1424 case AsmToken::LessEqual:
1425 Kind = MCBinaryExpr::LTE;
1426 return 3;
1427 case AsmToken::Greater:
1428 Kind = MCBinaryExpr::GT;
1429 return 3;
1430 case AsmToken::GreaterEqual:
1431 Kind = MCBinaryExpr::GTE;
1432 return 3;
1433
1434 // Low Intermediate Precedence: +, -
1435 case AsmToken::Plus:
1436 Kind = MCBinaryExpr::Add;
1437 return 4;
1438 case AsmToken::Minus:
1439 Kind = MCBinaryExpr::Sub;
1440 return 4;
1441
1442 // High Intermediate Precedence: |, &, ^
1443 //
1444 // FIXME: gas seems to support '!' as an infix operator?
1445 case AsmToken::Pipe:
1446 Kind = MCBinaryExpr::Or;
1447 return 5;
1448 case AsmToken::Caret:
1449 Kind = MCBinaryExpr::Xor;
1450 return 5;
1451 case AsmToken::Amp:
1452 Kind = MCBinaryExpr::And;
1453 return 5;
1454
1455 // Highest Precedence: *, /, %, <<, >>
1456 case AsmToken::Star:
1457 Kind = MCBinaryExpr::Mul;
1458 return 6;
1459 case AsmToken::Slash:
1460 Kind = MCBinaryExpr::Div;
1461 return 6;
1462 case AsmToken::Percent:
1463 Kind = MCBinaryExpr::Mod;
1464 return 6;
1465 case AsmToken::LessLess:
1466 Kind = MCBinaryExpr::Shl;
1467 return 6;
1468 case AsmToken::GreaterGreater:
1469 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1470 return 6;
1471 }
1472}
1473
1474unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1475 MCBinaryExpr::Opcode &Kind) {
1476 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1477 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1478 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1479}
1480
Jim Grosbach4b905842013-09-20 23:08:21 +00001481/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001482/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001483bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001484 SMLoc &EndLoc) {
Chad Rosier9245e122017-01-19 20:06:32 +00001485 SMLoc StartLoc = Lexer.getLoc();
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001486 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001487 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001488 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001489
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001490 // If the next token is lower precedence than we are allowed to eat, return
1491 // successfully with what we ate already.
1492 if (TokPrec < Precedence)
1493 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001494
Sean Callanan686ed8d2010-01-19 20:22:31 +00001495 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001496
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001497 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001498 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001499 if (parsePrimaryExpr(RHS, EndLoc))
1500 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001501
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001502 // If BinOp binds less tightly with RHS than the operator after RHS, let
1503 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001504 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001505 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001506 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1507 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001508
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001509 // Merge LHS and RHS according to operator.
Chad Rosier9245e122017-01-19 20:06:32 +00001510 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001511 }
1512}
1513
Chris Lattner36e02122009-06-21 20:54:55 +00001514/// ParseStatement:
1515/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001516/// ::= Label* Directive ...Operands... EndOfStatement
1517/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001518bool AsmParser::parseStatement(ParseStatementInfo &Info,
1519 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001520 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001521 // Eat initial spaces and comments
1522 while (Lexer.is(AsmToken::Space))
1523 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001524 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001525 // if this is a line comment we can drop it safely
1526 if (getTok().getString().front() == '\r' ||
1527 getTok().getString().front() == '\n')
1528 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001529 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001530 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001531 }
Nirav Dave9263ae32016-08-02 19:17:54 +00001532 if (Lexer.is(AsmToken::Hash)) {
1533 // Seeing a hash here means that it was an end-of-line comment in
1534 // an asm syntax where hash's are not comment and the previous
1535 // statement parser did not check the end of statement. Relex as
1536 // EndOfStatement.
1537 StringRef CommentStr = parseStringToEndOfStatement();
1538 Lexer.Lex();
1539 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1540 return false;
1541 }
Nirav Davefd910412016-06-17 16:06:17 +00001542 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001543 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001544 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001545 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001546 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001547 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001548 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001549 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001550 if (Lexer.is(AsmToken::Integer)) {
1551 LocalLabelVal = getTok().getIntVal();
1552 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001553 if (!TheCondState.Ignore) {
1554 Lex(); // always eat a token
1555 return Error(IDLoc, "unexpected token at start of statement");
1556 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001557 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001558 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001559 IDVal = getTok().getString();
1560 Lex(); // Consume the integer token to be used as an identifier token.
1561 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001562 if (!TheCondState.Ignore) {
1563 Lex(); // always eat a token
1564 return Error(IDLoc, "unexpected token at start of statement");
1565 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001566 }
1567 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001568 } else if (Lexer.is(AsmToken::Dot)) {
1569 // Treat '.' as a valid identifier in this context.
1570 Lex();
1571 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001572 } else if (Lexer.is(AsmToken::LCurly)) {
1573 // Treat '{' as a valid identifier in this context.
1574 Lex();
1575 IDVal = "{";
1576
1577 } else if (Lexer.is(AsmToken::RCurly)) {
1578 // Treat '}' as a valid identifier in this context.
1579 Lex();
1580 IDVal = "}";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001581 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001582 if (!TheCondState.Ignore) {
1583 Lex(); // always eat a token
1584 return Error(IDLoc, "unexpected token at start of statement");
1585 }
Chris Lattner926885c2010-04-17 18:14:27 +00001586 IDVal = "";
1587 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001588
Chris Lattner926885c2010-04-17 18:14:27 +00001589 // Handle conditional assembly here before checking for skipping. We
1590 // have to do this so that .endif isn't skipped in a ".if 0" block for
1591 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001592 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001593 DirectiveKindMap.find(IDVal);
1594 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1595 ? DK_NO_DIRECTIVE
1596 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001597 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001598 default:
1599 break;
1600 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001601 case DK_IFEQ:
1602 case DK_IFGE:
1603 case DK_IFGT:
1604 case DK_IFLE:
1605 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001606 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001607 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001608 case DK_IFB:
1609 return parseDirectiveIfb(IDLoc, true);
1610 case DK_IFNB:
1611 return parseDirectiveIfb(IDLoc, false);
1612 case DK_IFC:
1613 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001614 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001615 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001616 case DK_IFNC:
1617 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001618 case DK_IFNES:
1619 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001620 case DK_IFDEF:
1621 return parseDirectiveIfdef(IDLoc, true);
1622 case DK_IFNDEF:
1623 case DK_IFNOTDEF:
1624 return parseDirectiveIfdef(IDLoc, false);
1625 case DK_ELSEIF:
1626 return parseDirectiveElseIf(IDLoc);
1627 case DK_ELSE:
1628 return parseDirectiveElse(IDLoc);
1629 case DK_ENDIF:
1630 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001631 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001632
Eli Bendersky88024712013-01-16 19:32:36 +00001633 // Ignore the statement if in the middle of inactive conditional
1634 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001635 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001636 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001637 return false;
1638 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001639
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001640 // FIXME: Recurse on local labels?
1641
1642 // See what kind of statement we have.
1643 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001644 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001645 if (!getTargetParser().isLabel(ID))
1646 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001647 if (checkForValidSection())
1648 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001649
Chris Lattner36e02122009-06-21 20:54:55 +00001650 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001651 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001652
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001653 // Diagnose attempt to use '.' as a label.
1654 if (IDVal == ".")
1655 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1656
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001657 // Diagnose attempt to use a variable as a label.
1658 //
1659 // FIXME: Diagnostics. Note the location of the definition as a label.
1660 // FIXME: This doesn't diagnose assignment to a symbol which has been
1661 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001662 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001663 if (LocalLabelVal == -1) {
1664 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001665 StringRef RewrittenLabel =
1666 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001667 assert(!RewrittenLabel.empty() &&
Nico Weber67e715f2015-06-19 23:43:47 +00001668 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001669 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1670 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001671 IDVal = RewrittenLabel;
1672 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001673 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001674 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001675 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
Nirav Dave9263ae32016-08-02 19:17:54 +00001676 // End of Labels should be treated as end of line for lexing
1677 // purposes but that information is not available to the Lexer who
1678 // does not understand Labels. This may cause us to see a Hash
1679 // here instead of a preprocessor line comment.
1680 if (getTok().is(AsmToken::Hash)) {
1681 StringRef CommentStr = parseStringToEndOfStatement();
1682 Lexer.Lex();
1683 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1684 }
1685
Nirav Dave8ea792d2016-07-13 14:03:12 +00001686 // Consume any end of statement token, if present, to avoid spurious
1687 // AddBlankLine calls().
1688 if (getTok().is(AsmToken::EndOfStatement)) {
1689 Lex();
1690 }
1691
Daniel Dunbare73b2672009-08-26 22:13:22 +00001692 // Emit the label.
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00001693 if (!getTargetParser().isParsingInlineAsm())
Rafael Espindolabe991572017-02-10 15:13:12 +00001694 Out.EmitLabel(Sym, IDLoc);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001695
Kevin Enderbye7739d42011-12-09 18:09:40 +00001696 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001697 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001698 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001699 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1700 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001701
Tim Northover1744d0a2013-10-25 12:49:50 +00001702 getTargetParser().onLabelParsed(Sym);
1703
Eli Friedman0f4871d2012-10-22 23:58:19 +00001704 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001705 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001706
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001707 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001708 if (!getTargetParser().equalIsAsmAssignment())
1709 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001710 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001711 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001712
Jim Grosbach4b905842013-09-20 23:08:21 +00001713 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001714
1715 default: // Normal instruction or directive.
1716 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001717 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001718
1719 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001720 if (areMacrosEnabled())
1721 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1722 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001723 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001724
Michael J. Spencer530ce852010-10-09 11:00:50 +00001725 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001726
Eli Bendersky17233942013-01-15 22:59:42 +00001727 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001728 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001729 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001730 //
Eli Bendersky17233942013-01-15 22:59:42 +00001731 // 1. The target-specific assembly parser. Some directives are target
1732 // specific or may potentially behave differently on certain targets.
1733 // 2. Asm parser extensions. For example, platform-specific parsers
1734 // (like the ELF parser) register themselves as extensions.
1735 // 3. The generic directive parser implemented by this class. These are
1736 // all the directives that behave in a target and platform independent
1737 // manner, or at least have a default behavior that's shared between
1738 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001739
Oliver Stannard21718282016-07-26 14:19:47 +00001740 getTargetParser().flushPendingInstructions(getStreamer());
1741
Nirav Dave2364748a2016-09-16 18:30:20 +00001742 SMLoc StartTokLoc = getTok().getLoc();
1743 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1744
1745 if (hasPendingError())
1746 return true;
1747 // Currently the return value should be true if we are
1748 // uninterested but as this is at odds with the standard parsing
1749 // convention (return true = error) we have instances of a parsed
1750 // directive that fails returning true as an error. Catch these
1751 // cases as best as possible errors here.
1752 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1753 return true;
1754 // Return if we did some parsing or believe we succeeded.
1755 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001756 return false;
1757
Alp Tokercb402912014-01-24 17:20:08 +00001758 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001759 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001760 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1761 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001762 if (Handler.first)
1763 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1764
1765 // Finally, if no one else is interested in this directive, it must be
1766 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001767 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001768 default:
1769 break;
1770 case DK_SET:
1771 case DK_EQU:
1772 return parseDirectiveSet(IDVal, true);
1773 case DK_EQUIV:
1774 return parseDirectiveSet(IDVal, false);
1775 case DK_ASCII:
1776 return parseDirectiveAscii(IDVal, false);
1777 case DK_ASCIZ:
1778 case DK_STRING:
1779 return parseDirectiveAscii(IDVal, true);
1780 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001781 case DK_DC_B:
1782 return parseDirectiveValue(IDVal, 1);
1783 case DK_DC:
1784 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001785 case DK_SHORT:
1786 case DK_VALUE:
1787 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001788 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001789 case DK_LONG:
1790 case DK_INT:
1791 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001792 case DK_DC_L:
1793 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001794 case DK_QUAD:
1795 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001796 return parseDirectiveValue(IDVal, 8);
1797 case DK_DC_A:
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001798 return parseDirectiveValue(
1799 IDVal, getContext().getAsmInfo()->getCodePointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001800 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001801 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001802 case DK_SINGLE:
1803 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001804 case DK_DC_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001805 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
Jim Grosbach4b905842013-09-20 23:08:21 +00001806 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001807 case DK_DC_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001808 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
Jim Grosbach4b905842013-09-20 23:08:21 +00001809 case DK_ALIGN: {
1810 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1811 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1812 }
1813 case DK_ALIGN32: {
1814 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1815 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1816 }
1817 case DK_BALIGN:
1818 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1819 case DK_BALIGNW:
1820 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1821 case DK_BALIGNL:
1822 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1823 case DK_P2ALIGN:
1824 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1825 case DK_P2ALIGNW:
1826 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1827 case DK_P2ALIGNL:
1828 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1829 case DK_ORG:
1830 return parseDirectiveOrg();
1831 case DK_FILL:
1832 return parseDirectiveFill();
1833 case DK_ZERO:
1834 return parseDirectiveZero();
1835 case DK_EXTERN:
1836 eatToEndOfStatement(); // .extern is the default, ignore it.
1837 return false;
1838 case DK_GLOBL:
1839 case DK_GLOBAL:
1840 return parseDirectiveSymbolAttribute(MCSA_Global);
1841 case DK_LAZY_REFERENCE:
1842 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1843 case DK_NO_DEAD_STRIP:
1844 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1845 case DK_SYMBOL_RESOLVER:
1846 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1847 case DK_PRIVATE_EXTERN:
1848 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1849 case DK_REFERENCE:
1850 return parseDirectiveSymbolAttribute(MCSA_Reference);
1851 case DK_WEAK_DEFINITION:
1852 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1853 case DK_WEAK_REFERENCE:
1854 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1855 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1856 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1857 case DK_COMM:
1858 case DK_COMMON:
1859 return parseDirectiveComm(/*IsLocal=*/false);
1860 case DK_LCOMM:
1861 return parseDirectiveComm(/*IsLocal=*/true);
1862 case DK_ABORT:
1863 return parseDirectiveAbort();
1864 case DK_INCLUDE:
1865 return parseDirectiveInclude();
1866 case DK_INCBIN:
1867 return parseDirectiveIncbin();
1868 case DK_CODE16:
1869 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001870 return TokError(Twine(IDVal) +
1871 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001872 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001873 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001874 case DK_IRP:
1875 return parseDirectiveIrp(IDLoc);
1876 case DK_IRPC:
1877 return parseDirectiveIrpc(IDLoc);
1878 case DK_ENDR:
1879 return parseDirectiveEndr(IDLoc);
1880 case DK_BUNDLE_ALIGN_MODE:
1881 return parseDirectiveBundleAlignMode();
1882 case DK_BUNDLE_LOCK:
1883 return parseDirectiveBundleLock();
1884 case DK_BUNDLE_UNLOCK:
1885 return parseDirectiveBundleUnlock();
1886 case DK_SLEB128:
1887 return parseDirectiveLEB128(true);
1888 case DK_ULEB128:
1889 return parseDirectiveLEB128(false);
1890 case DK_SPACE:
1891 case DK_SKIP:
1892 return parseDirectiveSpace(IDVal);
1893 case DK_FILE:
1894 return parseDirectiveFile(IDLoc);
1895 case DK_LINE:
1896 return parseDirectiveLine();
1897 case DK_LOC:
1898 return parseDirectiveLoc();
1899 case DK_STABS:
1900 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001901 case DK_CV_FILE:
1902 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001903 case DK_CV_FUNC_ID:
1904 return parseDirectiveCVFuncId();
1905 case DK_CV_INLINE_SITE_ID:
1906 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001907 case DK_CV_LOC:
1908 return parseDirectiveCVLoc();
1909 case DK_CV_LINETABLE:
1910 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00001911 case DK_CV_INLINE_LINETABLE:
1912 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00001913 case DK_CV_DEF_RANGE:
1914 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001915 case DK_CV_STRINGTABLE:
1916 return parseDirectiveCVStringTable();
1917 case DK_CV_FILECHECKSUMS:
1918 return parseDirectiveCVFileChecksums();
Jim Grosbach4b905842013-09-20 23:08:21 +00001919 case DK_CFI_SECTIONS:
1920 return parseDirectiveCFISections();
1921 case DK_CFI_STARTPROC:
1922 return parseDirectiveCFIStartProc();
1923 case DK_CFI_ENDPROC:
1924 return parseDirectiveCFIEndProc();
1925 case DK_CFI_DEF_CFA:
1926 return parseDirectiveCFIDefCfa(IDLoc);
1927 case DK_CFI_DEF_CFA_OFFSET:
1928 return parseDirectiveCFIDefCfaOffset();
1929 case DK_CFI_ADJUST_CFA_OFFSET:
1930 return parseDirectiveCFIAdjustCfaOffset();
1931 case DK_CFI_DEF_CFA_REGISTER:
1932 return parseDirectiveCFIDefCfaRegister(IDLoc);
1933 case DK_CFI_OFFSET:
1934 return parseDirectiveCFIOffset(IDLoc);
1935 case DK_CFI_REL_OFFSET:
1936 return parseDirectiveCFIRelOffset(IDLoc);
1937 case DK_CFI_PERSONALITY:
1938 return parseDirectiveCFIPersonalityOrLsda(true);
1939 case DK_CFI_LSDA:
1940 return parseDirectiveCFIPersonalityOrLsda(false);
1941 case DK_CFI_REMEMBER_STATE:
1942 return parseDirectiveCFIRememberState();
1943 case DK_CFI_RESTORE_STATE:
1944 return parseDirectiveCFIRestoreState();
1945 case DK_CFI_SAME_VALUE:
1946 return parseDirectiveCFISameValue(IDLoc);
1947 case DK_CFI_RESTORE:
1948 return parseDirectiveCFIRestore(IDLoc);
1949 case DK_CFI_ESCAPE:
1950 return parseDirectiveCFIEscape();
1951 case DK_CFI_SIGNAL_FRAME:
1952 return parseDirectiveCFISignalFrame();
1953 case DK_CFI_UNDEFINED:
1954 return parseDirectiveCFIUndefined(IDLoc);
1955 case DK_CFI_REGISTER:
1956 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00001957 case DK_CFI_WINDOW_SAVE:
1958 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00001959 case DK_MACROS_ON:
1960 case DK_MACROS_OFF:
1961 return parseDirectiveMacrosOnOff(IDVal);
1962 case DK_MACRO:
1963 return parseDirectiveMacro(IDLoc);
Michael Zuckerman56704612017-05-01 13:20:12 +00001964 case DK_ALTMACRO:
1965 case DK_NOALTMACRO:
1966 return parseDirectiveAltmacro(IDVal);
Nico Weber155dccd12014-07-24 17:08:39 +00001967 case DK_EXITM:
1968 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001969 case DK_ENDM:
1970 case DK_ENDMACRO:
1971 return parseDirectiveEndMacro(IDVal);
1972 case DK_PURGEM:
1973 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00001974 case DK_END:
1975 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00001976 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00001977 return parseDirectiveError(IDLoc, false);
1978 case DK_ERROR:
1979 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00001980 case DK_WARNING:
1981 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00001982 case DK_RELOC:
1983 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001984 case DK_DCB:
1985 case DK_DCB_W:
1986 return parseDirectiveDCB(IDVal, 2);
1987 case DK_DCB_B:
1988 return parseDirectiveDCB(IDVal, 1);
1989 case DK_DCB_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001990 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001991 case DK_DCB_L:
1992 return parseDirectiveDCB(IDVal, 4);
1993 case DK_DCB_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001994 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
Petr Hosek731bb9c2016-08-23 21:34:53 +00001995 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001996 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00001997 return TokError(Twine(IDVal) +
1998 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00001999 case DK_DS:
2000 case DK_DS_W:
2001 return parseDirectiveDS(IDVal, 2);
2002 case DK_DS_B:
2003 return parseDirectiveDS(IDVal, 1);
2004 case DK_DS_D:
2005 return parseDirectiveDS(IDVal, 8);
2006 case DK_DS_L:
2007 case DK_DS_S:
2008 return parseDirectiveDS(IDVal, 4);
2009 case DK_DS_P:
2010 case DK_DS_X:
2011 return parseDirectiveDS(IDVal, 12);
Eli Friedman20b02642010-07-19 04:17:25 +00002012 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002013
Jim Grosbach758e0cc2012-05-01 18:38:27 +00002014 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00002015 }
Chris Lattner36e02122009-06-21 20:54:55 +00002016
Chad Rosierc7f552c2013-02-12 21:33:51 +00002017 // __asm _emit or __asm __emit
2018 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
2019 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002020 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00002021
2022 // __asm align
2023 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002024 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00002025
Coby Tayree3847be92017-04-04 17:57:23 +00002026 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
Michael Zuckerman02ecd432015-12-13 17:07:23 +00002027 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00002028 if (checkForValidSection())
2029 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00002030
Chris Lattner7cbfa442010-05-19 23:34:33 +00002031 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00002032 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00002033 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00002034 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
2035 Info.ParsedOperands);
2036 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00002037
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002038 // Dump the parsed representation, if requested.
2039 if (getShowParsedOperands()) {
2040 SmallString<256> Str;
2041 raw_svector_ostream OS(Str);
2042 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002043 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002044 if (i != 0)
2045 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002046 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002047 }
2048 OS << "]";
2049
Jim Grosbach4b905842013-09-20 23:08:21 +00002050 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002051 }
2052
Nirav Dave2364748a2016-09-16 18:30:20 +00002053 // Fail even if ParseInstruction erroneously returns false.
2054 if (hasPendingError() || ParseHadError)
2055 return true;
2056
Oliver Stannard8b273082014-06-19 15:52:37 +00002057 // If we are generating dwarf for the current section then generate a .loc
2058 // directive for the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002059 if (!ParseHadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002060 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002061 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002062 unsigned Line;
2063 if (ActiveMacros.empty())
2064 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2065 else
Frederic Riss16238d92015-06-25 21:57:33 +00002066 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2067 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002068
Eli Bendersky88024712013-01-16 19:32:36 +00002069 // If we previously parsed a cpp hash file line comment then make sure the
2070 // current Dwarf File is for the CppHashFilename if not then emit the
2071 // Dwarf File table for it and adjust the line number for the .loc.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00002072 if (!CppHashInfo.Filename.empty()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002073 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002074 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002075 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002076
Jim Grosbach4b905842013-09-20 23:08:21 +00002077 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
2078 // cache with the different Loc from the call above we save the last
2079 // info we queried here with SrcMgr.FindLineNumber().
2080 unsigned CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002081 if (LastQueryIDLoc == CppHashInfo.Loc &&
2082 LastQueryBuffer == CppHashInfo.Buf)
Jim Grosbach4b905842013-09-20 23:08:21 +00002083 CppHashLocLineNo = LastQueryLine;
2084 else {
Tim Northoverc0bef992016-04-13 19:46:54 +00002085 CppHashLocLineNo =
2086 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002087 LastQueryLine = CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002088 LastQueryIDLoc = CppHashInfo.Loc;
2089 LastQueryBuffer = CppHashInfo.Buf;
Jim Grosbach4b905842013-09-20 23:08:21 +00002090 }
Tim Northoverc0bef992016-04-13 19:46:54 +00002091 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002092 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002093
Jim Grosbach4b905842013-09-20 23:08:21 +00002094 getStreamer().EmitDwarfLocDirective(
2095 getContext().getGenDwarfFileNumber(), Line, 0,
2096 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2097 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002098 }
2099
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002100 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002101 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002102 uint64_t ErrorInfo;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00002103 if (getTargetParser().MatchAndEmitInstruction(
2104 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2105 getTargetParser().isParsingInlineAsm()))
Nirav Dave2364748a2016-09-16 18:30:20 +00002106 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002107 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002108 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002109}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002110
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002111// Parse and erase curly braces marking block start/end
2112bool
2113AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2114 // Identify curly brace marking block start/end
2115 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2116 return false;
2117
2118 SMLoc StartLoc = Lexer.getLoc();
2119 Lex(); // Eat the brace
2120 if (Lexer.is(AsmToken::EndOfStatement))
2121 Lex(); // Eat EndOfStatement following the brace
2122
2123 // Erase the block start/end brace from the output asm string
2124 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2125 StartLoc.getPointer());
2126 return true;
2127}
2128
Jim Grosbach4b905842013-09-20 23:08:21 +00002129/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002130/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002131bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002132 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002133 // Lexer only ever emits HashDirective if it fully formed if it's
2134 // done the checking already so this is an internal error.
2135 assert(getTok().is(AsmToken::Integer) &&
2136 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002137 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002138 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002139 assert(getTok().is(AsmToken::String) &&
2140 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002141 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002142 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002143
Kevin Enderby72553612011-09-13 23:45:18 +00002144 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002145 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002146
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002147 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002148 CppHashInfo.Loc = L;
2149 CppHashInfo.Filename = Filename;
2150 CppHashInfo.LineNumber = LineNumber;
2151 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002152 return false;
2153}
2154
Jim Grosbach4b905842013-09-20 23:08:21 +00002155/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002156/// for the Filename and LineNo if any in the diagnostic.
2157void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002158 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002159 raw_ostream &OS = errs();
2160
2161 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002162 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002163 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2164 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002165 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002166
Jim Grosbach4b905842013-09-20 23:08:21 +00002167 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002168 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002169 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2170 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2171 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002172 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2173 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002174 }
2175
Eric Christophera7c32732012-12-18 00:30:54 +00002176 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002177 // manager changed or buffer changed (like in a nested include) then just
2178 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002179 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002180 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002181 if (Parser->SavedDiagHandler)
2182 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2183 else
Craig Topper353eda42014-04-24 06:44:33 +00002184 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002185 return;
2186 }
2187
Eric Christophera7c32732012-12-18 00:30:54 +00002188 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002189 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2190 // for the diagnostic.
2191 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002192
2193 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2194 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002195 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002196 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002197 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002198
Jim Grosbach4b905842013-09-20 23:08:21 +00002199 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2200 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002201 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002202
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002203 if (Parser->SavedDiagHandler)
2204 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2205 else
Craig Topper353eda42014-04-24 06:44:33 +00002206 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002207}
2208
Rafael Espindola2c064482012-08-21 18:29:30 +00002209// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2210// difference being that that function accepts '@' as part of identifiers and
2211// we can't do that. AsmLexer.cpp should probably be changed to handle
2212// '@' as a special case when needed.
2213static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002214 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2215 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002216}
2217
Rafael Espindola34b9c512012-06-03 23:57:14 +00002218bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002219 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002220 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002221 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002222 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002223 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002224 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002225 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002226
Preston Gurd05500642012-09-19 20:36:12 +00002227 // A macro without parameters is handled differently on Darwin:
2228 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002229 while (!Body.empty()) {
2230 // Scan for the next substitution.
2231 std::size_t End = Body.size(), Pos = 0;
2232 for (; Pos != End; ++Pos) {
2233 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002234 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002235 // This macro has no parameters, look for $0, $1, etc.
2236 if (Body[Pos] != '$' || Pos + 1 == End)
2237 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002238
Rafael Espindola1134ab232011-06-05 02:43:45 +00002239 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002240 if (Next == '$' || Next == 'n' ||
2241 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002242 break;
2243 } else {
2244 // This macro has parameters, look for \foo, \bar, etc.
2245 if (Body[Pos] == '\\' && Pos + 1 != End)
2246 break;
2247 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002248 }
2249
2250 // Add the prefix.
2251 OS << Body.slice(0, Pos);
2252
2253 // Check if we reached the end.
2254 if (Pos == End)
2255 break;
2256
Benjamin Kramer513e7442014-02-20 13:36:32 +00002257 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002258 switch (Body[Pos + 1]) {
2259 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002260 case '$':
2261 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002262 break;
2263
Jim Grosbach4b905842013-09-20 23:08:21 +00002264 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002265 case 'n':
2266 OS << A.size();
2267 break;
2268
Jim Grosbach4b905842013-09-20 23:08:21 +00002269 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002270 default: {
2271 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002272 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002273 if (Index >= A.size())
2274 break;
2275
2276 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002277 for (const AsmToken &Token : A[Index])
2278 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002279 break;
2280 }
2281 }
2282 Pos += 2;
2283 } else {
2284 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002285
2286 // Check for the \@ pseudo-variable.
2287 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002288 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002289 else
2290 while (isIdentifierChar(Body[I]) && I + 1 != End)
2291 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002292
Jim Grosbach4b905842013-09-20 23:08:21 +00002293 const char *Begin = Body.data() + Pos + 1;
2294 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002295 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002296
Toma Tabacu217116e2015-04-27 10:50:29 +00002297 if (Argument == "@") {
2298 OS << NumOfMacroInstantiations;
2299 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002300 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002301 for (; Index < NParameters; ++Index)
2302 if (Parameters[Index].Name == Argument)
2303 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002304
Toma Tabacu217116e2015-04-27 10:50:29 +00002305 if (Index == NParameters) {
2306 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2307 Pos += 3;
2308 else {
2309 OS << '\\' << Argument;
2310 Pos = I;
2311 }
2312 } else {
2313 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002314 for (const AsmToken &Token : A[Index])
Michael Zuckerman56704612017-05-01 13:20:12 +00002315 // For altmacro mode, you can write '%expr'.
2316 // The prefix '%' evaluates the expression 'expr'
2317 // and uses the result as a string (e.g. replace %(1+2) with the string "3").
2318 // Here, we identify the integer token which is the result of the
2319 // absolute expression evaluation and replace it with its string representation.
2320 if ((Lexer.IsaAltMacroMode()) &&
2321 (*(Token.getString().begin()) == '%') && Token.is(AsmToken::Integer))
2322 // Emit an integer value to the buffer.
2323 OS << Token.getIntVal();
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002324 // Only Token that was validated as a string and begins with '<'
2325 // is considered altMacroString!!!
2326 else if ((Lexer.IsaAltMacroMode()) &&
2327 (*(Token.getString().begin()) == '<') &&
2328 Token.is(AsmToken::String)) {
2329 std::string Res;
2330 altMacroString(Token.getStringContents(), Res);
2331 OS << Res;
2332 }
Toma Tabacu217116e2015-04-27 10:50:29 +00002333 // We expect no quotes around the string's contents when
2334 // parsing for varargs.
Michael Zuckerman56704612017-05-01 13:20:12 +00002335 else if (Token.isNot(AsmToken::String) || VarargParameter)
Craig Topper84008482015-10-10 05:38:14 +00002336 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002337 else
Craig Topper84008482015-10-10 05:38:14 +00002338 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002339
2340 Pos += 1 + Argument.size();
2341 }
Preston Gurd05500642012-09-19 20:36:12 +00002342 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002343 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002344 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002345 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002346 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002347
Rafael Espindola1134ab232011-06-05 02:43:45 +00002348 return false;
2349}
Daniel Dunbar43235712010-07-18 18:54:11 +00002350
Nico Weber2a8f9222014-07-24 16:29:04 +00002351MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002352 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002353 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002354 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002355
Jim Grosbach4b905842013-09-20 23:08:21 +00002356static bool isOperator(AsmToken::TokenKind kind) {
2357 switch (kind) {
2358 default:
2359 return false;
2360 case AsmToken::Plus:
2361 case AsmToken::Minus:
2362 case AsmToken::Tilde:
2363 case AsmToken::Slash:
2364 case AsmToken::Star:
2365 case AsmToken::Dot:
2366 case AsmToken::Equal:
2367 case AsmToken::EqualEqual:
2368 case AsmToken::Pipe:
2369 case AsmToken::PipePipe:
2370 case AsmToken::Caret:
2371 case AsmToken::Amp:
2372 case AsmToken::AmpAmp:
2373 case AsmToken::Exclaim:
2374 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002375 case AsmToken::Less:
2376 case AsmToken::LessEqual:
2377 case AsmToken::LessLess:
2378 case AsmToken::LessGreater:
2379 case AsmToken::Greater:
2380 case AsmToken::GreaterEqual:
2381 case AsmToken::GreaterGreater:
2382 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002383 }
2384}
2385
David Majnemer16252452014-01-29 00:07:39 +00002386namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002387
David Majnemer16252452014-01-29 00:07:39 +00002388class AsmLexerSkipSpaceRAII {
2389public:
2390 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2391 Lexer.setSkipSpace(SkipSpace);
2392 }
2393
2394 ~AsmLexerSkipSpaceRAII() {
2395 Lexer.setSkipSpace(true);
2396 }
2397
2398private:
2399 AsmLexer &Lexer;
2400};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002401
2402} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002403
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002404bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2405
2406 if (Vararg) {
2407 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2408 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002409 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002410 }
2411 return false;
2412 }
2413
Rafael Espindola768b41c2012-06-15 14:02:34 +00002414 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002415
David Majnemer16252452014-01-29 00:07:39 +00002416 // Darwin doesn't use spaces to delmit arguments.
2417 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002418
Scott Egertona1fa68a2016-02-11 13:48:49 +00002419 bool SpaceEaten;
2420
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002421 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002422 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002423 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002424 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002425
Scott Egertona1fa68a2016-02-11 13:48:49 +00002426 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002427
Scott Egertona1fa68a2016-02-11 13:48:49 +00002428 if (Lexer.is(AsmToken::Comma))
2429 break;
2430
2431 if (Lexer.is(AsmToken::Space)) {
2432 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002433 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002434 }
Preston Gurd05500642012-09-19 20:36:12 +00002435
2436 // Spaces can delimit parameters, but could also be part an expression.
2437 // If the token after a space is an operator, add the token and the next
2438 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002439 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002440 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002441 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002442 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002443
Scott Egertona1fa68a2016-02-11 13:48:49 +00002444 // Whitespace after an operator can be ignored.
2445 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002446 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002447
2448 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002449 }
2450 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002451 if (SpaceEaten)
2452 break;
Preston Gurd05500642012-09-19 20:36:12 +00002453 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002454
Jim Grosbach4b905842013-09-20 23:08:21 +00002455 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002456 // to be able to fill in the remaining default parameter values
2457 if (Lexer.is(AsmToken::EndOfStatement))
2458 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002459
2460 // Adjust the current parentheses level.
2461 if (Lexer.is(AsmToken::LParen))
2462 ++ParenLevel;
2463 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2464 --ParenLevel;
2465
2466 // Append the token to the current argument list.
2467 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002468 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002469 }
Preston Gurd05500642012-09-19 20:36:12 +00002470
Rafael Espindola768b41c2012-06-15 14:02:34 +00002471 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002472 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002473 return false;
2474}
2475
2476// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002477bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002478 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002479 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002480 bool NamedParametersFound = false;
2481 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002482
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002483 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002484 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002485
Rafael Espindola768b41c2012-06-15 14:02:34 +00002486 // Parse two kinds of macro invocations:
2487 // - macros defined without any parameters accept an arbitrary number of them
2488 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002489 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002490 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2491 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002492 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002493 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002494
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002495 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002496 if (parseIdentifier(FA.Name))
2497 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002498
Nirav Dave2364748a2016-09-16 18:30:20 +00002499 if (Lexer.isNot(AsmToken::Equal))
2500 return TokError("expected '=' after formal parameter identifier");
2501
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002502 Lex();
2503
2504 NamedParametersFound = true;
2505 }
Michael Zuckerman56704612017-05-01 13:20:12 +00002506 bool Vararg = HasVararg && Parameter == (NParameters - 1);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002507
Nirav Dave2364748a2016-09-16 18:30:20 +00002508 if (NamedParametersFound && FA.Name.empty())
2509 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002510
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002511 SMLoc StrLoc = Lexer.getLoc();
2512 SMLoc EndLoc;
Michael Zuckerman56704612017-05-01 13:20:12 +00002513 if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Percent)) {
Michael Zuckerman56704612017-05-01 13:20:12 +00002514 const MCExpr *AbsoluteExp;
2515 int64_t Value;
2516 /// Eat '%'
2517 Lex();
2518 if (parseExpression(AbsoluteExp, EndLoc))
2519 return false;
2520 if (!AbsoluteExp->evaluateAsAbsolute(Value))
2521 return Error(StrLoc, "expected absolute expression");
2522 const char *StrChar = StrLoc.getPointer();
2523 const char *EndChar = EndLoc.getPointer();
2524 AsmToken newToken(AsmToken::Integer, StringRef(StrChar , EndChar - StrChar), Value);
2525 FA.Value.push_back(newToken);
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002526 } else if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Less) &&
2527 isAltmacroString(StrLoc, EndLoc)) {
2528 const char *StrChar = StrLoc.getPointer();
2529 const char *EndChar = EndLoc.getPointer();
2530 jumpToLoc(EndLoc, CurBuffer);
2531 /// Eat from '<' to '>'
2532 Lex();
2533 AsmToken newToken(AsmToken::String, StringRef(StrChar, EndChar - StrChar));
2534 FA.Value.push_back(newToken);
2535 } else if(parseMacroArgument(FA.Value, Vararg))
Michael Zuckerman56704612017-05-01 13:20:12 +00002536 return true;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002537
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002538 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002539 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002540 unsigned FAI = 0;
2541 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002542 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002543 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002544
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002545 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002546 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002547 return Error(IDLoc, "parameter named '" + FA.Name +
2548 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002549 }
2550 PI = FAI;
2551 }
2552
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002553 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002554 if (A.size() <= PI)
2555 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002556 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002557
2558 if (FALocs.size() <= PI)
2559 FALocs.resize(PI + 1);
2560
2561 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002562 }
Jim Grosbach206661622012-07-30 22:44:17 +00002563
Preston Gurd242ed3152012-09-19 20:29:04 +00002564 // At the end of the statement, fill in remaining arguments that have
2565 // default values. If there aren't any, then the next argument is
2566 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002567 if (Lexer.is(AsmToken::EndOfStatement)) {
2568 bool Failure = false;
2569 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2570 if (A[FAI].empty()) {
2571 if (M->Parameters[FAI].Required) {
2572 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2573 "missing value for required parameter "
2574 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2575 Failure = true;
2576 }
2577
2578 if (!M->Parameters[FAI].Value.empty())
2579 A[FAI] = M->Parameters[FAI].Value;
2580 }
2581 }
2582 return Failure;
2583 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002584
2585 if (Lexer.is(AsmToken::Comma))
2586 Lex();
2587 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002588
2589 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002590}
2591
Jim Grosbach4b905842013-09-20 23:08:21 +00002592const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002593 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2594 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002595}
2596
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002597void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2598 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002599}
2600
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002601void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002602
Jim Grosbach4b905842013-09-20 23:08:21 +00002603bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002604 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2605 // eliminate this, although we should protect against infinite loops.
2606 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2607 if (ActiveMacros.size() == MaxNestingDepth) {
2608 std::ostringstream MaxNestingDepthError;
2609 MaxNestingDepthError << "macros cannot be nested more than "
2610 << MaxNestingDepth << " levels deep."
2611 << " Use -asm-macro-max-nesting-depth to increase "
2612 "this limit.";
2613 return TokError(MaxNestingDepthError.str());
2614 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002615
Eli Bendersky38274122013-01-14 23:22:36 +00002616 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002617 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002618 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002619
Rafael Espindola1134ab232011-06-05 02:43:45 +00002620 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2621 // to hold the macro body with substitutions.
2622 SmallString<256> Buf;
2623 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002624 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002625
Toma Tabacu217116e2015-04-27 10:50:29 +00002626 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002627 return true;
2628
Eli Bendersky38274122013-01-14 23:22:36 +00002629 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002630 // instantiation.
2631 OS << ".endmacro\n";
2632
Rafael Espindola3560ff22014-08-27 20:03:13 +00002633 std::unique_ptr<MemoryBuffer> Instantiation =
2634 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002635
Daniel Dunbar43235712010-07-18 18:54:11 +00002636 // Create the macro instantiation object and add to the current macro
2637 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002638 MacroInstantiation *MI = new MacroInstantiation(
2639 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002640 ActiveMacros.push_back(MI);
2641
Toma Tabacu217116e2015-04-27 10:50:29 +00002642 ++NumOfMacroInstantiations;
2643
Daniel Dunbar43235712010-07-18 18:54:11 +00002644 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002645 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002646 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002647 Lex();
2648
2649 return false;
2650}
2651
Jim Grosbach4b905842013-09-20 23:08:21 +00002652void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002653 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002654 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002655 Lex();
2656
2657 // Pop the instantiation entry.
2658 delete ActiveMacros.back();
2659 ActiveMacros.pop_back();
2660}
2661
Jim Grosbach4b905842013-09-20 23:08:21 +00002662bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002663 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002664 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002665 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002666 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2667 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002668 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002669
Pete Cooper80d21cb2015-06-22 19:35:57 +00002670 if (!Sym) {
2671 // In the case where we parse an expression starting with a '.', we will
2672 // not generate an error, nor will we create a symbol. In this case we
2673 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002674 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002675 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002676
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002677 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002678 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002679 if (NoDeadStrip)
2680 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2681
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002682 return false;
2683}
2684
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002685/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002686/// ::= identifier
2687/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002688bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002689 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002690 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2691 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002692 // handle this as a context dependent token, instead we detect adjacent tokens
2693 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002694 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2695 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002696
Hans Wennborgce69d772013-10-18 20:46:28 +00002697 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002698
2699 AsmToken Buf[1];
2700 Lexer.peekTokens(Buf, false);
2701
2702 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002703 return true;
2704
Hans Wennborgce69d772013-10-18 20:46:28 +00002705 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002706 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002707 return true;
2708
Nirav Daved0463322016-10-12 13:58:07 +00002709 // eat $ or @
2710 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002711 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002712 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002713 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002714 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002715 return false;
2716 }
2717
Jim Grosbach4b905842013-09-20 23:08:21 +00002718 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002719 return true;
2720
Sean Callanan936b0d32010-01-19 21:44:56 +00002721 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002722
Sean Callanan686ed8d2010-01-19 20:22:31 +00002723 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002724
2725 return false;
2726}
2727
Jim Grosbach4b905842013-09-20 23:08:21 +00002728/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002729/// ::= .equ identifier ',' expression
2730/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002731/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002732bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002733 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002734 if (check(parseIdentifier(Name), "expected identifier") ||
2735 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2736 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2737 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002738}
2739
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002740bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002741 if (check(getTok().isNot(AsmToken::String), "expected string"))
2742 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002743
2744 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002745 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002746 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2747 if (Str[i] != '\\') {
2748 Data += Str[i];
2749 continue;
2750 }
2751
2752 // Recognize escaped characters. Note that this escape semantics currently
2753 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2754 ++i;
2755 if (i == e)
2756 return TokError("unexpected backslash at end of string");
2757
2758 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002759 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002760 // Consume up to three octal characters.
2761 unsigned Value = Str[i] - '0';
2762
Jim Grosbach4b905842013-09-20 23:08:21 +00002763 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002764 ++i;
2765 Value = Value * 8 + (Str[i] - '0');
2766
Jim Grosbach4b905842013-09-20 23:08:21 +00002767 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002768 ++i;
2769 Value = Value * 8 + (Str[i] - '0');
2770 }
2771 }
2772
2773 if (Value > 255)
2774 return TokError("invalid octal escape sequence (out of range)");
2775
Jim Grosbach4b905842013-09-20 23:08:21 +00002776 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002777 continue;
2778 }
2779
2780 // Otherwise recognize individual escapes.
2781 switch (Str[i]) {
2782 default:
2783 // Just reject invalid escape sequences for now.
2784 return TokError("invalid escape sequence (unrecognized character)");
2785
2786 case 'b': Data += '\b'; break;
2787 case 'f': Data += '\f'; break;
2788 case 'n': Data += '\n'; break;
2789 case 'r': Data += '\r'; break;
2790 case 't': Data += '\t'; break;
2791 case '"': Data += '"'; break;
2792 case '\\': Data += '\\'; break;
2793 }
2794 }
2795
Nirav Davea645433c2016-07-18 15:24:03 +00002796 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002797 return false;
2798}
2799
Jim Grosbach4b905842013-09-20 23:08:21 +00002800/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002801/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002802bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002803 auto parseOp = [&]() -> bool {
2804 std::string Data;
2805 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002806 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002807 getStreamer().EmitBytes(Data);
2808 if (ZeroTerminated)
2809 getStreamer().EmitBytes(StringRef("\0", 1));
2810 return false;
2811 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002812
Nirav Dave1a9044b2016-10-24 14:35:29 +00002813 if (parseMany(parseOp))
2814 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002815 return false;
2816}
2817
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002818/// parseDirectiveReloc
2819/// ::= .reloc expression , identifier [ , expression ]
2820bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2821 const MCExpr *Offset;
2822 const MCExpr *Expr = nullptr;
2823
2824 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00002825 int64_t OffsetValue;
2826 // We can only deal with constant expressions at the moment.
2827
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002828 if (parseExpression(Offset))
2829 return true;
2830
Nirav Davea645433c2016-07-18 15:24:03 +00002831 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2832 "expression is not a constant value") ||
2833 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2834 parseToken(AsmToken::Comma, "expected comma") ||
2835 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2836 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002837
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002838 SMLoc NameLoc = Lexer.getTok().getLoc();
2839 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002840 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002841
2842 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002843 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002844 SMLoc ExprLoc = Lexer.getLoc();
2845 if (parseExpression(Expr))
2846 return true;
2847
2848 MCValue Value;
2849 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2850 return Error(ExprLoc, "expression must be relocatable");
2851 }
2852
Nirav Davea645433c2016-07-18 15:24:03 +00002853 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002854 "unexpected token in .reloc directive"))
2855 return true;
2856
2857 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2858 return Error(NameLoc, "unknown relocation name");
2859
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002860 return false;
2861}
2862
Jim Grosbach4b905842013-09-20 23:08:21 +00002863/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002864/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002865bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2866 auto parseOp = [&]() -> bool {
2867 const MCExpr *Value;
2868 SMLoc ExprLoc = getLexer().getLoc();
2869 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002870 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002871 // Special case constant expressions to match code generator.
2872 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2873 assert(Size <= 8 && "Invalid size");
2874 uint64_t IntValue = MCE->getValue();
2875 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2876 return Error(ExprLoc, "out of range literal value");
2877 getStreamer().EmitIntValue(IntValue, Size);
2878 } else
2879 getStreamer().EmitValue(Value, Size, ExprLoc);
2880 return false;
2881 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002882
Nirav Dave1a9044b2016-10-24 14:35:29 +00002883 if (parseMany(parseOp))
2884 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002885 return false;
2886}
2887
David Woodhoused6de0d92014-02-01 16:20:59 +00002888/// ParseDirectiveOctaValue
2889/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002890
2891bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
2892 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00002893 if (checkForValidSection())
2894 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002895 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
2896 return TokError("unknown token in expression");
2897 SMLoc ExprLoc = getTok().getLoc();
2898 APInt IntValue = getTok().getAPIntVal();
2899 uint64_t hi, lo;
2900 Lex();
2901 if (!IntValue.isIntN(128))
2902 return Error(ExprLoc, "out of range literal value");
2903 if (!IntValue.isIntN(64)) {
2904 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2905 lo = IntValue.getLoBits(64).getZExtValue();
2906 } else {
2907 hi = 0;
2908 lo = IntValue.getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002909 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00002910 if (MAI.isLittleEndian()) {
2911 getStreamer().EmitIntValue(lo, 8);
2912 getStreamer().EmitIntValue(hi, 8);
2913 } else {
2914 getStreamer().EmitIntValue(hi, 8);
2915 getStreamer().EmitIntValue(lo, 8);
2916 }
2917 return false;
2918 };
David Woodhoused6de0d92014-02-01 16:20:59 +00002919
Nirav Dave1a9044b2016-10-24 14:35:29 +00002920 if (parseMany(parseOp))
2921 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00002922 return false;
2923}
2924
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002925bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
2926 // We don't truly support arithmetic on floating point expressions, so we
2927 // have to manually parse unary prefixes.
2928 bool IsNeg = false;
2929 if (getLexer().is(AsmToken::Minus)) {
2930 Lexer.Lex();
2931 IsNeg = true;
2932 } else if (getLexer().is(AsmToken::Plus))
2933 Lexer.Lex();
2934
2935 if (Lexer.is(AsmToken::Error))
2936 return TokError(Lexer.getErr());
2937 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
2938 Lexer.isNot(AsmToken::Identifier))
2939 return TokError("unexpected token in directive");
2940
2941 // Convert to an APFloat.
2942 APFloat Value(Semantics);
2943 StringRef IDVal = getTok().getString();
2944 if (getLexer().is(AsmToken::Identifier)) {
2945 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2946 Value = APFloat::getInf(Semantics);
2947 else if (!IDVal.compare_lower("nan"))
2948 Value = APFloat::getNaN(Semantics, false, ~0);
2949 else
2950 return TokError("invalid floating point literal");
2951 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2952 APFloat::opInvalidOp)
2953 return TokError("invalid floating point literal");
2954 if (IsNeg)
2955 Value.changeSign();
2956
2957 // Consume the numeric token.
2958 Lex();
2959
2960 Res = Value.bitcastToAPInt();
2961
2962 return false;
2963}
2964
Jim Grosbach4b905842013-09-20 23:08:21 +00002965/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00002966/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002967bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
2968 const fltSemantics &Semantics) {
2969 auto parseOp = [&]() -> bool {
2970 APInt AsInt;
2971 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002972 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002973 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2974 AsInt.getBitWidth() / 8);
2975 return false;
2976 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00002977
Nirav Dave1a9044b2016-10-24 14:35:29 +00002978 if (parseMany(parseOp))
2979 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00002980 return false;
2981}
2982
Jim Grosbach4b905842013-09-20 23:08:21 +00002983/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00002984/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002985bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00002986 SMLoc NumBytesLoc = Lexer.getLoc();
2987 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00002988 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00002989 return true;
2990
Rafael Espindolab91bac62010-10-05 19:42:57 +00002991 int64_t Val = 0;
2992 if (getLexer().is(AsmToken::Comma)) {
2993 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002994 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00002995 return true;
2996 }
2997
Nirav Davea645433c2016-07-18 15:24:03 +00002998 if (parseToken(AsmToken::EndOfStatement,
2999 "unexpected token in '.zero' directive"))
3000 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00003001 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00003002
3003 return false;
3004}
3005
Jim Grosbach4b905842013-09-20 23:08:21 +00003006/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00003007/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003008bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003009 SMLoc NumValuesLoc = Lexer.getLoc();
3010 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003011 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00003012 return true;
3013
Roman Divackye33098f2013-09-24 17:44:41 +00003014 int64_t FillSize = 1;
3015 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00003016
David Majnemer522d3db2014-02-01 07:19:38 +00003017 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003018
Nirav Dave1a9044b2016-10-24 14:35:29 +00003019 if (parseOptionalToken(AsmToken::Comma)) {
3020 SizeLoc = getTok().getLoc();
3021 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00003022 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003023 if (parseOptionalToken(AsmToken::Comma)) {
3024 ExprLoc = getTok().getLoc();
3025 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00003026 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00003027 }
3028 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003029 if (parseToken(AsmToken::EndOfStatement,
3030 "unexpected token in '.fill' directive"))
3031 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003032
David Majnemer522d3db2014-02-01 07:19:38 +00003033 if (FillSize < 0) {
3034 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00003035 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00003036 }
3037 if (FillSize > 8) {
3038 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
3039 FillSize = 8;
3040 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00003041
David Majnemer522d3db2014-02-01 07:19:38 +00003042 if (!isUInt<32>(FillExpr) && FillSize > 4)
3043 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
3044
Petr Hosek67a94a72016-05-28 05:57:48 +00003045 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00003046
3047 return false;
3048}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003049
Jim Grosbach4b905842013-09-20 23:08:21 +00003050/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003051/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003052bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00003053 const MCExpr *Offset;
Oliver Stannard268f42f2016-12-14 10:43:58 +00003054 SMLoc OffsetLoc = Lexer.getLoc();
Nirav Davef43cc9f2016-10-10 15:24:54 +00003055 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003056 return true;
3057
3058 // Parse optional fill expression.
3059 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003060 if (parseOptionalToken(AsmToken::Comma))
3061 if (parseAbsoluteExpression(FillExpr))
3062 return addErrorSuffix(" in '.org' directive");
3063 if (parseToken(AsmToken::EndOfStatement))
3064 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00003065
Oliver Stannard268f42f2016-12-14 10:43:58 +00003066 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003067 return false;
3068}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003069
Jim Grosbach4b905842013-09-20 23:08:21 +00003070/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003071/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00003072bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003073 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003074 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003075 SMLoc MaxBytesLoc;
3076 bool HasFillExpr = false;
3077 int64_t FillExpr = 0;
3078 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003079
3080 auto parseAlign = [&]() -> bool {
3081 if (checkForValidSection() || parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00003082 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003083 if (parseOptionalToken(AsmToken::Comma)) {
3084 // The fill expression can be omitted while specifying a maximum number of
3085 // alignment bytes, e.g:
3086 // .align 3,,4
3087 if (getTok().isNot(AsmToken::Comma)) {
3088 HasFillExpr = true;
3089 if (parseAbsoluteExpression(FillExpr))
3090 return true;
3091 }
3092 if (parseOptionalToken(AsmToken::Comma))
3093 if (parseTokenLoc(MaxBytesLoc) ||
3094 parseAbsoluteExpression(MaxBytesToFill))
3095 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003096 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003097 return parseToken(AsmToken::EndOfStatement);
3098 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003099
Nirav Dave1a9044b2016-10-24 14:35:29 +00003100 if (parseAlign())
3101 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003102
Nirav Dave2364748a2016-09-16 18:30:20 +00003103 // Always emit an alignment here even if we thrown an error.
3104 bool ReturnVal = false;
3105
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003106 // Compute alignment in bytes.
3107 if (IsPow2) {
3108 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003109 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003110 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003111 Alignment = 31;
3112 }
3113
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003114 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003115 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003116 // Reject alignments that aren't either a power of two or zero,
3117 // for gas compatibility. Alignment of zero is silently rounded
3118 // up to one.
3119 if (Alignment == 0)
3120 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003121 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003122 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003123 }
3124
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003125 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003126 if (MaxBytesLoc.isValid()) {
3127 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003128 ReturnVal |= Error(MaxBytesLoc,
3129 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003130 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003131 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003132 }
3133
3134 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003135 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003136 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003137 MaxBytesToFill = 0;
3138 }
3139 }
3140
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003141 // Check whether we should use optimal code alignment for this .align
3142 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003143 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003144 assert(Section && "must have section to emit alignment");
3145 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003146 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3147 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003148 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003149 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003150 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003151 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3152 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003153 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003154
Nirav Dave2364748a2016-09-16 18:30:20 +00003155 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003156}
3157
Jim Grosbach4b905842013-09-20 23:08:21 +00003158/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00003159/// ::= .file [number] filename
3160/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00003161bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003162 // FIXME: I'm not sure what this is.
3163 int64_t FileNumber = -1;
3164 SMLoc FileNumberLoc = getLexer().getLoc();
3165 if (getLexer().is(AsmToken::Integer)) {
3166 FileNumber = getTok().getIntVal();
3167 Lex();
3168
3169 if (FileNumber < 1)
3170 return TokError("file number less than one");
3171 }
3172
Nirav Davea645433c2016-07-18 15:24:03 +00003173 std::string Path = getTok().getString();
Eli Bendersky17233942013-01-15 22:59:42 +00003174
3175 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003176 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003177 if (check(getTok().isNot(AsmToken::String),
3178 "unexpected token in '.file' directive") ||
3179 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003180 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003181
3182 StringRef Directory;
3183 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003184 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003185 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003186 if (check(FileNumber == -1,
3187 "explicit path specified, but no file number") ||
3188 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003189 return true;
3190 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003191 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003192 } else {
3193 Filename = Path;
3194 }
3195
Nirav Davea645433c2016-07-18 15:24:03 +00003196 if (parseToken(AsmToken::EndOfStatement,
3197 "unexpected token in '.file' directive"))
3198 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003199
3200 if (FileNumber == -1)
3201 getStreamer().EmitFileDirective(Filename);
3202 else {
David Blaikie22748082016-05-26 00:22:26 +00003203 // If there is -g option as well as debug info from directive file,
3204 // we turn off -g option, directly use the existing debug info instead.
David Blaikiedc3f01e2015-03-09 01:57:13 +00003205 if (getContext().getGenDwarfForAssembly())
David Blaikie22748082016-05-26 00:22:26 +00003206 getContext().setGenDwarfForAssembly(false);
3207 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
David Blaikiec714ef42014-03-17 01:52:11 +00003208 0)
Nirav Dave2364748a2016-09-16 18:30:20 +00003209 return Error(FileNumberLoc, "file number already allocated");
Eli Bendersky17233942013-01-15 22:59:42 +00003210 }
3211
3212 return false;
3213}
3214
Jim Grosbach4b905842013-09-20 23:08:21 +00003215/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003216/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003217bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003218 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003219 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003220 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3221 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003222 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003223 // FIXME: Do something with the .line.
3224 }
Nirav Davea645433c2016-07-18 15:24:03 +00003225 if (parseToken(AsmToken::EndOfStatement,
3226 "unexpected token in '.line' directive"))
3227 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003228
3229 return false;
3230}
3231
Jim Grosbach4b905842013-09-20 23:08:21 +00003232/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003233/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3234/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3235/// The first number is a file number, must have been previously assigned with
3236/// a .file directive, the second number is the line number and optionally the
3237/// third number is a column position (zero if not specified). The remaining
3238/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003239bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003240 int64_t FileNumber = 0, LineNumber = 0;
3241 SMLoc Loc = getTok().getLoc();
3242 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3243 check(FileNumber < 1, Loc,
3244 "file number less than one in '.loc' directive") ||
3245 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3246 "unassigned file number in '.loc' directive"))
3247 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003248
Nirav Davea645433c2016-07-18 15:24:03 +00003249 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003250 if (getLexer().is(AsmToken::Integer)) {
3251 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003252 if (LineNumber < 0)
3253 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003254 Lex();
3255 }
3256
3257 int64_t ColumnPos = 0;
3258 if (getLexer().is(AsmToken::Integer)) {
3259 ColumnPos = getTok().getIntVal();
3260 if (ColumnPos < 0)
3261 return TokError("column position less than zero in '.loc' directive");
3262 Lex();
3263 }
3264
3265 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3266 unsigned Isa = 0;
3267 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003268
Nirav Dave1a9044b2016-10-24 14:35:29 +00003269 auto parseLocOp = [&]() -> bool {
3270 StringRef Name;
3271 SMLoc Loc = getTok().getLoc();
3272 if (parseIdentifier(Name))
3273 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003274
Nirav Dave1a9044b2016-10-24 14:35:29 +00003275 if (Name == "basic_block")
3276 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3277 else if (Name == "prologue_end")
3278 Flags |= DWARF2_FLAG_PROLOGUE_END;
3279 else if (Name == "epilogue_begin")
3280 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3281 else if (Name == "is_stmt") {
3282 Loc = getTok().getLoc();
3283 const MCExpr *Value;
3284 if (parseExpression(Value))
3285 return true;
3286 // The expression must be the constant 0 or 1.
3287 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3288 int Value = MCE->getValue();
3289 if (Value == 0)
3290 Flags &= ~DWARF2_FLAG_IS_STMT;
3291 else if (Value == 1)
3292 Flags |= DWARF2_FLAG_IS_STMT;
3293 else
3294 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003295 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003296 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003297 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003298 } else if (Name == "isa") {
3299 Loc = getTok().getLoc();
3300 const MCExpr *Value;
3301 if (parseExpression(Value))
3302 return true;
3303 // The expression must be a constant greater or equal to 0.
3304 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3305 int Value = MCE->getValue();
3306 if (Value < 0)
3307 return Error(Loc, "isa number less than zero");
3308 Isa = Value;
3309 } else {
3310 return Error(Loc, "isa number not a constant value");
3311 }
3312 } else if (Name == "discriminator") {
3313 if (parseAbsoluteExpression(Discriminator))
3314 return true;
3315 } else {
3316 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003317 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003318 return false;
3319 };
3320
Nirav Davee2369aa2016-10-26 17:28:58 +00003321 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003322 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003323
3324 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3325 Isa, Discriminator, StringRef());
3326
3327 return false;
3328}
3329
Jim Grosbach4b905842013-09-20 23:08:21 +00003330/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003331/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003332bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003333 return TokError("unsupported directive '.stabs'");
3334}
3335
Reid Kleckner2214ed82016-01-29 00:49:42 +00003336/// parseDirectiveCVFile
3337/// ::= .cv_file number filename
3338bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003339 SMLoc FileNumberLoc = getTok().getLoc();
3340 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003341 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00003342
3343 if (parseIntToken(FileNumber,
3344 "expected file number in '.cv_file' directive") ||
3345 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3346 check(getTok().isNot(AsmToken::String),
3347 "unexpected token in '.cv_file' directive") ||
3348 // Usually directory and filename are together, otherwise just
3349 // directory. Allow the strings to have escaped octal character sequence.
3350 parseEscapedString(Filename) ||
3351 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00003352 "unexpected token in '.cv_file' directive"))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003353 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00003354
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003355 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003356 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003357
3358 return false;
3359}
3360
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003361bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3362 StringRef DirectiveName) {
3363 SMLoc Loc;
3364 return parseTokenLoc(Loc) ||
3365 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3366 "' directive") ||
3367 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3368 "expected function id within range [0, UINT_MAX)");
3369}
3370
3371bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3372 SMLoc Loc;
3373 return parseTokenLoc(Loc) ||
3374 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3375 "' directive") ||
3376 check(FileNumber < 1, Loc, "file number less than one in '" +
3377 DirectiveName + "' directive") ||
3378 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3379 "unassigned file number in '" + DirectiveName + "' directive");
3380}
3381
3382/// parseDirectiveCVFuncId
3383/// ::= .cv_func_id FunctionId
3384///
3385/// Introduces a function ID that can be used with .cv_loc.
3386bool AsmParser::parseDirectiveCVFuncId() {
3387 SMLoc FunctionIdLoc = getTok().getLoc();
3388 int64_t FunctionId;
3389
3390 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3391 parseToken(AsmToken::EndOfStatement,
3392 "unexpected token in '.cv_func_id' directive"))
3393 return true;
3394
3395 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003396 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003397
3398 return false;
3399}
3400
3401/// parseDirectiveCVInlineSiteId
3402/// ::= .cv_inline_site_id FunctionId
3403/// "within" IAFunc
3404/// "inlined_at" IAFile IALine [IACol]
3405///
3406/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3407/// at" source location information for use in the line table of the caller,
3408/// whether the caller is a real function or another inlined call site.
3409bool AsmParser::parseDirectiveCVInlineSiteId() {
3410 SMLoc FunctionIdLoc = getTok().getLoc();
3411 int64_t FunctionId;
3412 int64_t IAFunc;
3413 int64_t IAFile;
3414 int64_t IALine;
3415 int64_t IACol = 0;
3416
3417 // FunctionId
3418 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3419 return true;
3420
3421 // "within"
3422 if (check((getLexer().isNot(AsmToken::Identifier) ||
3423 getTok().getIdentifier() != "within"),
3424 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3425 return true;
3426 Lex();
3427
3428 // IAFunc
3429 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3430 return true;
3431
3432 // "inlined_at"
3433 if (check((getLexer().isNot(AsmToken::Identifier) ||
3434 getTok().getIdentifier() != "inlined_at"),
3435 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3436 "directive") )
3437 return true;
3438 Lex();
3439
3440 // IAFile IALine
3441 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3442 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3443 return true;
3444
3445 // [IACol]
3446 if (getLexer().is(AsmToken::Integer)) {
3447 IACol = getTok().getIntVal();
3448 Lex();
3449 }
3450
3451 if (parseToken(AsmToken::EndOfStatement,
3452 "unexpected token in '.cv_inline_site_id' directive"))
3453 return true;
3454
3455 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3456 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003457 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003458
3459 return false;
3460}
3461
Reid Kleckner2214ed82016-01-29 00:49:42 +00003462/// parseDirectiveCVLoc
3463/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3464/// [is_stmt VALUE]
3465/// The first number is a file number, must have been previously assigned with
3466/// a .file directive, the second number is the line number and optionally the
3467/// third number is a column position (zero if not specified). The remaining
3468/// optional items are .loc sub-directives.
3469bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003470 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003471 SMLoc Loc;
3472 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003473 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3474 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003475 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003476
3477 int64_t LineNumber = 0;
3478 if (getLexer().is(AsmToken::Integer)) {
3479 LineNumber = getTok().getIntVal();
3480 if (LineNumber < 0)
3481 return TokError("line number less than zero in '.cv_loc' directive");
3482 Lex();
3483 }
3484
3485 int64_t ColumnPos = 0;
3486 if (getLexer().is(AsmToken::Integer)) {
3487 ColumnPos = getTok().getIntVal();
3488 if (ColumnPos < 0)
3489 return TokError("column position less than zero in '.cv_loc' directive");
3490 Lex();
3491 }
3492
3493 bool PrologueEnd = false;
3494 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003495
3496 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003497 StringRef Name;
3498 SMLoc Loc = getTok().getLoc();
3499 if (parseIdentifier(Name))
3500 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003501 if (Name == "prologue_end")
3502 PrologueEnd = true;
3503 else if (Name == "is_stmt") {
3504 Loc = getTok().getLoc();
3505 const MCExpr *Value;
3506 if (parseExpression(Value))
3507 return true;
3508 // The expression must be the constant 0 or 1.
3509 IsStmt = ~0ULL;
3510 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3511 IsStmt = MCE->getValue();
3512
3513 if (IsStmt > 1)
3514 return Error(Loc, "is_stmt value not 0 or 1");
3515 } else {
3516 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3517 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003518 return false;
3519 };
3520
3521 if (parseMany(parseOp, false /*hasComma*/))
3522 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003523
3524 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003525 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3526 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003527 return false;
3528}
3529
3530/// parseDirectiveCVLinetable
3531/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3532bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003533 int64_t FunctionId;
3534 StringRef FnStartName, FnEndName;
3535 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003536 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003537 parseToken(AsmToken::Comma,
3538 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003539 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3540 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003541 parseToken(AsmToken::Comma,
3542 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003543 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3544 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003545 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003546
3547 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3548 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3549
3550 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3551 return false;
3552}
3553
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003554/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003555/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003556bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003557 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3558 StringRef FnStartName, FnEndName;
3559 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003560 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003561 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003562 parseIntToken(
3563 SourceFileId,
3564 "expected SourceField in '.cv_inline_linetable' directive") ||
3565 check(SourceFileId <= 0, Loc,
3566 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003567 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003568 parseIntToken(
3569 SourceLineNum,
3570 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3571 check(SourceLineNum < 0, Loc,
3572 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003573 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3574 "expected identifier in directive") ||
3575 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3576 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003577 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003578
Nirav Davea645433c2016-07-18 15:24:03 +00003579 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3580 return true;
3581
3582 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3583 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003584 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3585 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003586 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003587 return false;
3588}
3589
David Majnemer408b5e62016-02-05 01:55:49 +00003590/// parseDirectiveCVDefRange
3591/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3592bool AsmParser::parseDirectiveCVDefRange() {
3593 SMLoc Loc;
3594 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3595 while (getLexer().is(AsmToken::Identifier)) {
3596 Loc = getLexer().getLoc();
3597 StringRef GapStartName;
3598 if (parseIdentifier(GapStartName))
3599 return Error(Loc, "expected identifier in directive");
3600 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3601
3602 Loc = getLexer().getLoc();
3603 StringRef GapEndName;
3604 if (parseIdentifier(GapEndName))
3605 return Error(Loc, "expected identifier in directive");
3606 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3607
3608 Ranges.push_back({GapStartSym, GapEndSym});
3609 }
3610
David Majnemer408b5e62016-02-05 01:55:49 +00003611 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003612 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3613 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003614 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003615
3616 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3617 return false;
3618}
3619
Reid Kleckner2214ed82016-01-29 00:49:42 +00003620/// parseDirectiveCVStringTable
3621/// ::= .cv_stringtable
3622bool AsmParser::parseDirectiveCVStringTable() {
3623 getStreamer().EmitCVStringTableDirective();
3624 return false;
3625}
3626
3627/// parseDirectiveCVFileChecksums
3628/// ::= .cv_filechecksums
3629bool AsmParser::parseDirectiveCVFileChecksums() {
3630 getStreamer().EmitCVFileChecksumsDirective();
3631 return false;
3632}
3633
Jim Grosbach4b905842013-09-20 23:08:21 +00003634/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003635/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003636bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003637 StringRef Name;
3638 bool EH = false;
3639 bool Debug = false;
3640
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003641 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003642 return TokError("Expected an identifier");
3643
3644 if (Name == ".eh_frame")
3645 EH = true;
3646 else if (Name == ".debug_frame")
3647 Debug = true;
3648
3649 if (getLexer().is(AsmToken::Comma)) {
3650 Lex();
3651
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003652 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003653 return TokError("Expected an identifier");
3654
3655 if (Name == ".eh_frame")
3656 EH = true;
3657 else if (Name == ".debug_frame")
3658 Debug = true;
3659 }
3660
3661 getStreamer().EmitCFISections(EH, Debug);
3662 return false;
3663}
3664
Jim Grosbach4b905842013-09-20 23:08:21 +00003665/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003666/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003667bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003668 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003669 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3670 if (check(parseIdentifier(Simple) || Simple != "simple",
3671 "unexpected token") ||
3672 parseToken(AsmToken::EndOfStatement))
3673 return addErrorSuffix(" in '.cfi_startproc' directive");
3674 }
Nirav Davea645433c2016-07-18 15:24:03 +00003675
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003676 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003677 return false;
3678}
3679
Jim Grosbach4b905842013-09-20 23:08:21 +00003680/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003681/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003682bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003683 getStreamer().EmitCFIEndProc();
3684 return false;
3685}
3686
Jim Grosbach4b905842013-09-20 23:08:21 +00003687/// \brief parse register name or number.
3688bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003689 SMLoc DirectiveLoc) {
3690 unsigned RegNo;
3691
3692 if (getLexer().isNot(AsmToken::Integer)) {
3693 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3694 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003695 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003696 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003697 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003698
3699 return false;
3700}
3701
Jim Grosbach4b905842013-09-20 23:08:21 +00003702/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003703/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003704bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003705 int64_t Register = 0, Offset = 0;
3706 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3707 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3708 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003709 return true;
3710
3711 getStreamer().EmitCFIDefCfa(Register, Offset);
3712 return false;
3713}
3714
Jim Grosbach4b905842013-09-20 23:08:21 +00003715/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003716/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003717bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003718 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003719 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003720 return true;
3721
3722 getStreamer().EmitCFIDefCfaOffset(Offset);
3723 return false;
3724}
3725
Jim Grosbach4b905842013-09-20 23:08:21 +00003726/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003727/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003728bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003729 int64_t Register1 = 0, Register2 = 0;
3730 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3731 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3732 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003733 return true;
3734
3735 getStreamer().EmitCFIRegister(Register1, Register2);
3736 return false;
3737}
3738
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003739/// parseDirectiveCFIWindowSave
3740/// ::= .cfi_window_save
3741bool AsmParser::parseDirectiveCFIWindowSave() {
3742 getStreamer().EmitCFIWindowSave();
3743 return false;
3744}
3745
Jim Grosbach4b905842013-09-20 23:08:21 +00003746/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003747/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003748bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003749 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003750 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003751 return true;
3752
3753 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3754 return false;
3755}
3756
Jim Grosbach4b905842013-09-20 23:08:21 +00003757/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003758/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003759bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003760 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003761 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003762 return true;
3763
3764 getStreamer().EmitCFIDefCfaRegister(Register);
3765 return false;
3766}
3767
Jim Grosbach4b905842013-09-20 23:08:21 +00003768/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003769/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003770bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003771 int64_t Register = 0;
3772 int64_t Offset = 0;
3773
Nirav Davea645433c2016-07-18 15:24:03 +00003774 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3775 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3776 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003777 return true;
3778
3779 getStreamer().EmitCFIOffset(Register, Offset);
3780 return false;
3781}
3782
Jim Grosbach4b905842013-09-20 23:08:21 +00003783/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003784/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003785bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003786 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003787
Nirav Davea645433c2016-07-18 15:24:03 +00003788 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3789 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3790 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003791 return true;
3792
3793 getStreamer().EmitCFIRelOffset(Register, Offset);
3794 return false;
3795}
3796
3797static bool isValidEncoding(int64_t Encoding) {
3798 if (Encoding & ~0xff)
3799 return false;
3800
3801 if (Encoding == dwarf::DW_EH_PE_omit)
3802 return true;
3803
3804 const unsigned Format = Encoding & 0xf;
3805 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3806 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3807 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3808 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3809 return false;
3810
3811 const unsigned Application = Encoding & 0x70;
3812 if (Application != dwarf::DW_EH_PE_absptr &&
3813 Application != dwarf::DW_EH_PE_pcrel)
3814 return false;
3815
3816 return true;
3817}
3818
Jim Grosbach4b905842013-09-20 23:08:21 +00003819/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003820/// IsPersonality true for cfi_personality, false for cfi_lsda
3821/// ::= .cfi_personality encoding, [symbol_name]
3822/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003823bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003824 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003825 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003826 return true;
3827 if (Encoding == dwarf::DW_EH_PE_omit)
3828 return false;
3829
Eli Bendersky17233942013-01-15 22:59:42 +00003830 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00003831 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
3832 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3833 check(parseIdentifier(Name), "expected identifier in directive"))
3834 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003835
Jim Grosbach6f482002015-05-18 18:43:14 +00003836 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003837
3838 if (IsPersonality)
3839 getStreamer().EmitCFIPersonality(Sym, Encoding);
3840 else
3841 getStreamer().EmitCFILsda(Sym, Encoding);
3842 return false;
3843}
3844
Jim Grosbach4b905842013-09-20 23:08:21 +00003845/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00003846/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003847bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003848 getStreamer().EmitCFIRememberState();
3849 return false;
3850}
3851
Jim Grosbach4b905842013-09-20 23:08:21 +00003852/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00003853/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003854bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003855 getStreamer().EmitCFIRestoreState();
3856 return false;
3857}
3858
Jim Grosbach4b905842013-09-20 23:08:21 +00003859/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00003860/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00003861bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003862 int64_t Register = 0;
3863
Jim Grosbach4b905842013-09-20 23:08:21 +00003864 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003865 return true;
3866
3867 getStreamer().EmitCFISameValue(Register);
3868 return false;
3869}
3870
Jim Grosbach4b905842013-09-20 23:08:21 +00003871/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00003872/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00003873bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003874 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003875 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003876 return true;
3877
3878 getStreamer().EmitCFIRestore(Register);
3879 return false;
3880}
3881
Jim Grosbach4b905842013-09-20 23:08:21 +00003882/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00003883/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003884bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00003885 std::string Values;
3886 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003887 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003888 return true;
3889
3890 Values.push_back((uint8_t)CurrValue);
3891
3892 while (getLexer().is(AsmToken::Comma)) {
3893 Lex();
3894
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003895 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003896 return true;
3897
3898 Values.push_back((uint8_t)CurrValue);
3899 }
3900
3901 getStreamer().EmitCFIEscape(Values);
3902 return false;
3903}
3904
Jim Grosbach4b905842013-09-20 23:08:21 +00003905/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00003906/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00003907bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00003908 if (parseToken(AsmToken::EndOfStatement,
3909 "unexpected token in '.cfi_signal_frame'"))
3910 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003911
3912 getStreamer().EmitCFISignalFrame();
3913 return false;
3914}
3915
Jim Grosbach4b905842013-09-20 23:08:21 +00003916/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00003917/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00003918bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003919 int64_t Register = 0;
3920
Jim Grosbach4b905842013-09-20 23:08:21 +00003921 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003922 return true;
3923
3924 getStreamer().EmitCFIUndefined(Register);
3925 return false;
3926}
3927
Michael Zuckerman56704612017-05-01 13:20:12 +00003928/// parseDirectiveAltmacro
3929/// ::= .altmacro
3930/// ::= .noaltmacro
3931bool AsmParser::parseDirectiveAltmacro(StringRef Directive) {
3932 if (getLexer().isNot(AsmToken::EndOfStatement))
3933 return TokError("unexpected token in '" + Directive + "' directive");
3934 if (Directive == ".altmacro")
3935 getLexer().SetAltMacroMode(true);
3936 else
3937 getLexer().SetAltMacroMode(false);
3938 return false;
3939}
3940
Jim Grosbach4b905842013-09-20 23:08:21 +00003941/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00003942/// ::= .macros_on
3943/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00003944bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00003945 if (parseToken(AsmToken::EndOfStatement,
3946 "unexpected token in '" + Directive + "' directive"))
3947 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003948
Jim Grosbach4b905842013-09-20 23:08:21 +00003949 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00003950 return false;
3951}
3952
Jim Grosbach4b905842013-09-20 23:08:21 +00003953/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003954/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00003955bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003956 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003957 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003958 return TokError("expected identifier in '.macro' directive");
3959
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003960 if (getLexer().is(AsmToken::Comma))
3961 Lex();
3962
Eli Bendersky17233942013-01-15 22:59:42 +00003963 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00003964 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003965
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003966 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003967 return Error(Lexer.getLoc(),
3968 "Vararg parameter '" + Parameters.back().Name +
3969 "' should be last one in the list of parameters.");
3970
David Majnemer91fc4c22014-01-29 18:57:46 +00003971 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003972 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00003973 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003974
Coby Tayreebedaae02017-04-08 20:29:03 +00003975 // Emit an error if two (or more) named parameters share the same name
3976 for (const MCAsmMacroParameter& CurrParam : Parameters)
3977 if (CurrParam.Name.equals(Parameter.Name))
3978 return TokError("macro '" + Name + "' has multiple parameters"
3979 " named '" + Parameter.Name + "'");
3980
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003981 if (Lexer.is(AsmToken::Colon)) {
3982 Lex(); // consume ':'
3983
3984 SMLoc QualLoc;
3985 StringRef Qualifier;
3986
3987 QualLoc = Lexer.getLoc();
3988 if (parseIdentifier(Qualifier))
3989 return Error(QualLoc, "missing parameter qualifier for "
3990 "'" + Parameter.Name + "' in macro '" + Name + "'");
3991
3992 if (Qualifier == "req")
3993 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00003994 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003995 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003996 else
3997 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3998 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3999 }
4000
David Majnemer91fc4c22014-01-29 18:57:46 +00004001 if (getLexer().is(AsmToken::Equal)) {
4002 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004003
4004 SMLoc ParamLoc;
4005
4006 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004007 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00004008 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004009
4010 if (Parameter.Required)
4011 Warning(ParamLoc, "pointless default value for required parameter "
4012 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00004013 }
David Majnemer91fc4c22014-01-29 18:57:46 +00004014
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00004015 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00004016
4017 if (getLexer().is(AsmToken::Comma))
4018 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004019 }
4020
Nirav Dave1180e6892016-06-02 17:15:05 +00004021 // Eat just the end of statement.
4022 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004023
Nirav Dave1180e6892016-06-02 17:15:05 +00004024 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00004025 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004026 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00004027 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004028 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00004029 // Ignore Lexing errors in macros.
4030 while (Lexer.is(AsmToken::Error)) {
4031 Lexer.Lex();
4032 }
4033
Eli Bendersky17233942013-01-15 22:59:42 +00004034 // Check whether we have reached the end of the file.
4035 if (getLexer().is(AsmToken::Eof))
4036 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
4037
4038 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004039 if (getLexer().is(AsmToken::Identifier)) {
4040 if (getTok().getIdentifier() == ".endm" ||
4041 getTok().getIdentifier() == ".endmacro") {
4042 if (MacroDepth == 0) { // Outermost macro.
4043 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00004044 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004045 if (getLexer().isNot(AsmToken::EndOfStatement))
4046 return TokError("unexpected token in '" + EndToken.getIdentifier() +
4047 "' directive");
4048 break;
4049 } else {
4050 // Otherwise we just found the end of an inner macro.
4051 --MacroDepth;
4052 }
4053 } else if (getTok().getIdentifier() == ".macro") {
4054 // We allow nested macros. Those aren't instantiated until the outermost
4055 // macro is expanded so just ignore them for now.
4056 ++MacroDepth;
4057 }
Eli Bendersky17233942013-01-15 22:59:42 +00004058 }
4059
4060 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004061 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00004062 }
4063
Jim Grosbach4b905842013-09-20 23:08:21 +00004064 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00004065 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
4066 }
4067
4068 const char *BodyStart = StartToken.getLoc().getPointer();
4069 const char *BodyEnd = EndToken.getLoc().getPointer();
4070 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00004071 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00004072 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00004073 return false;
4074}
4075
Jim Grosbach4b905842013-09-20 23:08:21 +00004076/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00004077///
4078/// With the support added for named parameters there may be code out there that
4079/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00004080/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00004081/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00004082/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00004083/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4084/// warning that the positional parameter found in body which have no effect.
4085/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00004086/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00004087/// intended or change the macro to use the named parameters. It is possible
4088/// this warning will trigger when the none of the named parameters are used
4089/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00004090void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00004091 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004092 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00004093 // If this macro is not defined with named parameters the warning we are
4094 // checking for here doesn't apply.
4095 unsigned NParameters = Parameters.size();
4096 if (NParameters == 0)
4097 return;
4098
4099 bool NamedParametersFound = false;
4100 bool PositionalParametersFound = false;
4101
4102 // Look at the body of the macro for use of both the named parameters and what
4103 // are likely to be positional parameters. This is what expandMacro() is
4104 // doing when it finds the parameters in the body.
4105 while (!Body.empty()) {
4106 // Scan for the next possible parameter.
4107 std::size_t End = Body.size(), Pos = 0;
4108 for (; Pos != End; ++Pos) {
4109 // Check for a substitution or escape.
4110 // This macro is defined with parameters, look for \foo, \bar, etc.
4111 if (Body[Pos] == '\\' && Pos + 1 != End)
4112 break;
4113
4114 // This macro should have parameters, but look for $0, $1, ..., $n too.
4115 if (Body[Pos] != '$' || Pos + 1 == End)
4116 continue;
4117 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004118 if (Next == '$' || Next == 'n' ||
4119 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004120 break;
4121 }
4122
4123 // Check if we reached the end.
4124 if (Pos == End)
4125 break;
4126
4127 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004128 switch (Body[Pos + 1]) {
4129 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004130 case '$':
4131 break;
4132
Jim Grosbach4b905842013-09-20 23:08:21 +00004133 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004134 case 'n':
4135 PositionalParametersFound = true;
4136 break;
4137
Jim Grosbach4b905842013-09-20 23:08:21 +00004138 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004139 default: {
4140 PositionalParametersFound = true;
4141 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004142 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004143 }
4144 Pos += 2;
4145 } else {
4146 unsigned I = Pos + 1;
4147 while (isIdentifierChar(Body[I]) && I + 1 != End)
4148 ++I;
4149
Jim Grosbach4b905842013-09-20 23:08:21 +00004150 const char *Begin = Body.data() + Pos + 1;
4151 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004152 unsigned Index = 0;
4153 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004154 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004155 break;
4156
4157 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004158 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4159 Pos += 3;
4160 else {
4161 Pos = I;
4162 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004163 } else {
4164 NamedParametersFound = true;
4165 Pos += 1 + Argument.size();
4166 }
4167 }
4168 // Update the scan point.
4169 Body = Body.substr(Pos);
4170 }
4171
4172 if (!NamedParametersFound && PositionalParametersFound)
4173 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4174 "used in macro body, possible positional parameter "
4175 "found in body which will have no effect");
4176}
4177
Nico Weber155dccd12014-07-24 17:08:39 +00004178/// parseDirectiveExitMacro
4179/// ::= .exitm
4180bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004181 if (parseToken(AsmToken::EndOfStatement,
4182 "unexpected token in '" + Directive + "' directive"))
4183 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004184
4185 if (!isInsideMacroInstantiation())
4186 return TokError("unexpected '" + Directive + "' in file, "
4187 "no current macro definition");
4188
4189 // Exit all conditionals that are active in the current macro.
4190 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4191 TheCondState = TheCondStack.back();
4192 TheCondStack.pop_back();
4193 }
4194
4195 handleMacroExit();
4196 return false;
4197}
4198
Jim Grosbach4b905842013-09-20 23:08:21 +00004199/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004200/// ::= .endm
4201/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004202bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004203 if (getLexer().isNot(AsmToken::EndOfStatement))
4204 return TokError("unexpected token in '" + Directive + "' directive");
4205
4206 // If we are inside a macro instantiation, terminate the current
4207 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004208 if (isInsideMacroInstantiation()) {
4209 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004210 return false;
4211 }
4212
4213 // Otherwise, this .endmacro is a stray entry in the file; well formed
4214 // .endmacro directives are handled during the macro definition parsing.
4215 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004216 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004217}
4218
Jim Grosbach4b905842013-09-20 23:08:21 +00004219/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004220/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004221bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004222 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004223 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004224 if (parseTokenLoc(Loc) ||
4225 check(parseIdentifier(Name), Loc,
4226 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004227 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004228 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004229 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004230
Nirav Dave1ab71992016-07-18 19:35:21 +00004231 if (!lookupMacro(Name))
4232 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4233
Jim Grosbach4b905842013-09-20 23:08:21 +00004234 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004235 return false;
4236}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004237
Jim Grosbach4b905842013-09-20 23:08:21 +00004238/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004239/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004240bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004241 // Expect a single argument: an expression that evaluates to a constant
4242 // in the inclusive range 0-30.
4243 SMLoc ExprLoc = getLexer().getLoc();
4244 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004245 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004246 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4247 "in '.bundle_align_mode' "
4248 "directive") ||
4249 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4250 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004251 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004252
4253 // Because of AlignSizePow2's verified range we can safely truncate it to
4254 // unsigned.
4255 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4256 return false;
4257}
4258
Jim Grosbach4b905842013-09-20 23:08:21 +00004259/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004260/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004261bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004262 if (checkForValidSection())
4263 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004264 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004265
Nirav Dave1a9044b2016-10-24 14:35:29 +00004266 StringRef Option;
4267 SMLoc Loc = getTok().getLoc();
4268 const char *kInvalidOptionError =
4269 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004270
Nirav Dave1a9044b2016-10-24 14:35:29 +00004271 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004272 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4273 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004274 parseToken(AsmToken::EndOfStatement,
4275 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004276 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004277 AlignToEnd = true;
4278 }
4279
Eli Bendersky802b6282013-01-07 21:51:08 +00004280 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004281 return false;
4282}
4283
Jim Grosbach4b905842013-09-20 23:08:21 +00004284/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004285/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004286bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004287 if (checkForValidSection() ||
4288 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004289 "unexpected token in '.bundle_unlock' directive"))
4290 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004291
4292 getStreamer().EmitBundleUnlock();
4293 return false;
4294}
4295
Jim Grosbach4b905842013-09-20 23:08:21 +00004296/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004297/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004298bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Petr Hosek67a94a72016-05-28 05:57:48 +00004299 SMLoc NumBytesLoc = Lexer.getLoc();
4300 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004301 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004302 return true;
4303
4304 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004305 if (parseOptionalToken(AsmToken::Comma))
4306 if (parseAbsoluteExpression(FillExpr))
4307 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4308 if (parseToken(AsmToken::EndOfStatement))
4309 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004310
Eli Bendersky17233942013-01-15 22:59:42 +00004311 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004312 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004313
4314 return false;
4315}
4316
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004317/// parseDirectiveDCB
4318/// ::= .dcb.{b, l, w} expression, expression
4319bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004320 SMLoc NumValuesLoc = Lexer.getLoc();
4321 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004322 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004323 return true;
4324
4325 if (NumValues < 0) {
4326 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4327 return false;
4328 }
4329
4330 if (parseToken(AsmToken::Comma,
4331 "unexpected token in '" + Twine(IDVal) + "' directive"))
4332 return true;
4333
4334 const MCExpr *Value;
4335 SMLoc ExprLoc = getLexer().getLoc();
4336 if (parseExpression(Value))
4337 return true;
4338
4339 // Special case constant expressions to match code generator.
4340 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4341 assert(Size <= 8 && "Invalid size");
4342 uint64_t IntValue = MCE->getValue();
4343 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4344 return Error(ExprLoc, "literal value out of range for directive");
4345 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4346 getStreamer().EmitIntValue(IntValue, Size);
4347 } else {
4348 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4349 getStreamer().EmitValue(Value, Size, ExprLoc);
4350 }
4351
4352 if (parseToken(AsmToken::EndOfStatement,
4353 "unexpected token in '" + Twine(IDVal) + "' directive"))
4354 return true;
4355
4356 return false;
4357}
4358
4359/// parseDirectiveRealDCB
4360/// ::= .dcb.{d, s} expression, expression
4361bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004362 SMLoc NumValuesLoc = Lexer.getLoc();
4363 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004364 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004365 return true;
4366
4367 if (NumValues < 0) {
4368 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4369 return false;
4370 }
4371
4372 if (parseToken(AsmToken::Comma,
4373 "unexpected token in '" + Twine(IDVal) + "' directive"))
4374 return true;
4375
4376 APInt AsInt;
4377 if (parseRealValue(Semantics, AsInt))
4378 return true;
4379
4380 if (parseToken(AsmToken::EndOfStatement,
4381 "unexpected token in '" + Twine(IDVal) + "' directive"))
4382 return true;
4383
4384 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4385 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4386 AsInt.getBitWidth() / 8);
4387
4388 return false;
4389}
4390
Petr Hosek85b2f672016-09-23 21:53:36 +00004391/// parseDirectiveDS
4392/// ::= .ds.{b, d, l, p, s, w, x} expression
4393bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004394 SMLoc NumValuesLoc = Lexer.getLoc();
4395 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004396 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004397 return true;
4398
4399 if (NumValues < 0) {
4400 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4401 return false;
4402 }
4403
4404 if (parseToken(AsmToken::EndOfStatement,
4405 "unexpected token in '" + Twine(IDVal) + "' directive"))
4406 return true;
4407
4408 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4409 getStreamer().emitFill(Size, 0);
4410
4411 return false;
4412}
4413
Jim Grosbach4b905842013-09-20 23:08:21 +00004414/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004415/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004416bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004417 if (checkForValidSection())
4418 return true;
4419
Nirav Dave1a9044b2016-10-24 14:35:29 +00004420 auto parseOp = [&]() -> bool {
4421 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004422 if (parseExpression(Value))
4423 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004424 if (Signed)
4425 getStreamer().EmitSLEB128Value(Value);
4426 else
4427 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004428 return false;
4429 };
Eli Bendersky17233942013-01-15 22:59:42 +00004430
Nirav Dave1a9044b2016-10-24 14:35:29 +00004431 if (parseMany(parseOp))
4432 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004433
4434 return false;
4435}
4436
Jim Grosbach4b905842013-09-20 23:08:21 +00004437/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004438/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004439bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004440 auto parseOp = [&]() -> bool {
4441 StringRef Name;
4442 SMLoc Loc = getTok().getLoc();
4443 if (parseIdentifier(Name))
4444 return Error(Loc, "expected identifier");
4445 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004446
Nirav Dave1a9044b2016-10-24 14:35:29 +00004447 // Assembler local symbols don't make any sense here. Complain loudly.
4448 if (Sym->isTemporary())
4449 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004450
Nirav Dave1a9044b2016-10-24 14:35:29 +00004451 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4452 return Error(Loc, "unable to emit symbol attribute");
4453 return false;
4454 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004455
Nirav Dave1a9044b2016-10-24 14:35:29 +00004456 if (parseMany(parseOp))
4457 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004458 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004459}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004460
Jim Grosbach4b905842013-09-20 23:08:21 +00004461/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004462/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004463bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004464 if (checkForValidSection())
4465 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004466
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004467 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004468 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004469 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004470 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004471
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004472 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004473 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004474
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004475 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004476 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004477 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004478
4479 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004480 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004481 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004482 return true;
4483
4484 int64_t Pow2Alignment = 0;
4485 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004486 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004487 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004488 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004489 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004490 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004491
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004492 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4493 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004494 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4495
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004496 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004497 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4498 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004499 if (!isPowerOf2_64(Pow2Alignment))
4500 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4501 Pow2Alignment = Log2_64(Pow2Alignment);
4502 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004503 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004504
Nirav Dave1a9044b2016-10-24 14:35:29 +00004505 if (parseToken(AsmToken::EndOfStatement,
4506 "unexpected token in '.comm' or '.lcomm' directive"))
4507 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004508
Chris Lattner28ad7542009-07-09 17:25:12 +00004509 // NOTE: a size of zero for a .comm should create a undefined symbol
4510 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004511 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004512 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004513 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004514
Eric Christopherbc818852010-05-14 01:38:54 +00004515 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004516 // may internally end up wanting an alignment in bytes.
4517 // FIXME: Diagnose overflow.
4518 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004519 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004520 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004521
Rafael Espindola13a79bb2017-02-02 21:26:06 +00004522 Sym->redefineIfPossible();
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004523 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004524 return Error(IDLoc, "invalid symbol redefinition");
4525
Chris Lattner28ad7542009-07-09 17:25:12 +00004526 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004527 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004528 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004529 return false;
4530 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004531
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004532 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004533 return false;
4534}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004535
Jim Grosbach4b905842013-09-20 23:08:21 +00004536/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004537/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004538bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004539 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004540 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004541
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004542 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004543 if (parseToken(AsmToken::EndOfStatement,
4544 "unexpected token in '.abort' directive"))
4545 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004546
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004547 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004548 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004549 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004550 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004551 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004552
4553 return false;
4554}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004555
Jim Grosbach4b905842013-09-20 23:08:21 +00004556/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004557/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004558bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004559 // Allow the strings to have escaped octal character sequence.
4560 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004561 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004562
Nirav Davea645433c2016-07-18 15:24:03 +00004563 if (check(getTok().isNot(AsmToken::String),
4564 "expected string in '.include' directive") ||
4565 parseEscapedString(Filename) ||
4566 check(getTok().isNot(AsmToken::EndOfStatement),
4567 "unexpected token in '.include' directive") ||
4568 // Attempt to switch the lexer to the included file before consuming the
4569 // end of statement to avoid losing it when we switch.
4570 check(enterIncludeFile(Filename), IncludeLoc,
4571 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004572 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004573
4574 return false;
4575}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004576
Jim Grosbach4b905842013-09-20 23:08:21 +00004577/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004578/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004579bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004580 // Allow the strings to have escaped octal character sequence.
4581 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004582 SMLoc IncbinLoc = getTok().getLoc();
4583 if (check(getTok().isNot(AsmToken::String),
4584 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00004585 parseEscapedString(Filename))
4586 return true;
4587
4588 int64_t Skip = 0;
4589 const MCExpr *Count = nullptr;
4590 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004591 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00004592 // The skip expression can be omitted while specifying the count, e.g:
4593 // .incbin "filename",,4
4594 if (getTok().isNot(AsmToken::Comma)) {
4595 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4596 return true;
4597 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00004598 if (parseOptionalToken(AsmToken::Comma)) {
4599 CountLoc = getTok().getLoc();
4600 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00004601 return true;
4602 }
4603 }
4604
4605 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004606 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004607 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004608
Petr Hosek2f4ac442016-09-23 00:41:06 +00004609 if (check(Skip < 0, SkipLoc, "skip is negative"))
4610 return true;
4611
Nirav Dave1ab71992016-07-18 19:35:21 +00004612 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00004613 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00004614 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004615 return false;
4616}
4617
Jim Grosbach4b905842013-09-20 23:08:21 +00004618/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004619/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4620bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004621 TheCondStack.push_back(TheCondState);
4622 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004623 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004624 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004625 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004626 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004627 if (parseAbsoluteExpression(ExprValue) ||
4628 parseToken(AsmToken::EndOfStatement,
4629 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004630 return true;
4631
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004632 switch (DirKind) {
4633 default:
4634 llvm_unreachable("unsupported directive");
4635 case DK_IF:
4636 case DK_IFNE:
4637 break;
4638 case DK_IFEQ:
4639 ExprValue = ExprValue == 0;
4640 break;
4641 case DK_IFGE:
4642 ExprValue = ExprValue >= 0;
4643 break;
4644 case DK_IFGT:
4645 ExprValue = ExprValue > 0;
4646 break;
4647 case DK_IFLE:
4648 ExprValue = ExprValue <= 0;
4649 break;
4650 case DK_IFLT:
4651 ExprValue = ExprValue < 0;
4652 break;
4653 }
4654
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004655 TheCondState.CondMet = ExprValue;
4656 TheCondState.Ignore = !TheCondState.CondMet;
4657 }
4658
4659 return false;
4660}
4661
Jim Grosbach4b905842013-09-20 23:08:21 +00004662/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004663/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004664bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004665 TheCondStack.push_back(TheCondState);
4666 TheCondState.TheCond = AsmCond::IfCond;
4667
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004668 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004669 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004670 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004671 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004672
Nirav Davea645433c2016-07-18 15:24:03 +00004673 if (parseToken(AsmToken::EndOfStatement,
4674 "unexpected token in '.ifb' directive"))
4675 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004676
4677 TheCondState.CondMet = ExpectBlank == Str.empty();
4678 TheCondState.Ignore = !TheCondState.CondMet;
4679 }
4680
4681 return false;
4682}
4683
Jim Grosbach4b905842013-09-20 23:08:21 +00004684/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004685/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004686/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004687bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004688 TheCondStack.push_back(TheCondState);
4689 TheCondState.TheCond = AsmCond::IfCond;
4690
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004691 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004692 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004693 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004694 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004695
Nirav Davea645433c2016-07-18 15:24:03 +00004696 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4697 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004698
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004699 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004700
Nirav Davea645433c2016-07-18 15:24:03 +00004701 if (parseToken(AsmToken::EndOfStatement,
4702 "unexpected token in '.ifc' directive"))
4703 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004704
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004705 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004706 TheCondState.Ignore = !TheCondState.CondMet;
4707 }
4708
4709 return false;
4710}
4711
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004712/// parseDirectiveIfeqs
4713/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004714bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004715 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004716 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004717 return TokError("expected string parameter for '.ifeqs' directive");
4718 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004719 }
4720
4721 StringRef String1 = getTok().getStringContents();
4722 Lex();
4723
4724 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004725 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004726 return TokError(
4727 "expected comma after first string for '.ifeqs' directive");
4728 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004729 }
4730
4731 Lex();
4732
4733 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004734 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004735 return TokError("expected string parameter for '.ifeqs' directive");
4736 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004737 }
4738
4739 StringRef String2 = getTok().getStringContents();
4740 Lex();
4741
4742 TheCondStack.push_back(TheCondState);
4743 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004744 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004745 TheCondState.Ignore = !TheCondState.CondMet;
4746
4747 return false;
4748}
4749
Jim Grosbach4b905842013-09-20 23:08:21 +00004750/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004751/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004752bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004753 StringRef Name;
4754 TheCondStack.push_back(TheCondState);
4755 TheCondState.TheCond = AsmCond::IfCond;
4756
4757 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004758 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004759 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00004760 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4761 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4762 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004763
Jim Grosbach6f482002015-05-18 18:43:14 +00004764 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004765
4766 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004767 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004768 else
Craig Topper353eda42014-04-24 06:44:33 +00004769 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004770 TheCondState.Ignore = !TheCondState.CondMet;
4771 }
4772
4773 return false;
4774}
4775
Jim Grosbach4b905842013-09-20 23:08:21 +00004776/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004777/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004778bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004779 if (TheCondState.TheCond != AsmCond::IfCond &&
4780 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004781 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
4782 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004783 TheCondState.TheCond = AsmCond::ElseIfCond;
4784
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004785 bool LastIgnoreState = false;
4786 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004787 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004788 if (LastIgnoreState || TheCondState.CondMet) {
4789 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004790 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004791 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004792 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004793 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004794 return true;
4795
Nirav Dave1a9044b2016-10-24 14:35:29 +00004796 if (parseToken(AsmToken::EndOfStatement,
4797 "unexpected token in '.elseif' directive"))
4798 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004799
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004800 TheCondState.CondMet = ExprValue;
4801 TheCondState.Ignore = !TheCondState.CondMet;
4802 }
4803
4804 return false;
4805}
4806
Jim Grosbach4b905842013-09-20 23:08:21 +00004807/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004808/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004809bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004810 if (parseToken(AsmToken::EndOfStatement,
4811 "unexpected token in '.else' directive"))
4812 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004813
4814 if (TheCondState.TheCond != AsmCond::IfCond &&
4815 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004816 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
4817 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004818 TheCondState.TheCond = AsmCond::ElseCond;
4819 bool LastIgnoreState = false;
4820 if (!TheCondStack.empty())
4821 LastIgnoreState = TheCondStack.back().Ignore;
4822 if (LastIgnoreState || TheCondState.CondMet)
4823 TheCondState.Ignore = true;
4824 else
4825 TheCondState.Ignore = false;
4826
4827 return false;
4828}
4829
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004830/// parseDirectiveEnd
4831/// ::= .end
4832bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004833 if (parseToken(AsmToken::EndOfStatement,
4834 "unexpected token in '.end' directive"))
4835 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004836
4837 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00004838 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004839
4840 return false;
4841}
4842
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004843/// parseDirectiveError
4844/// ::= .err
4845/// ::= .error [string]
4846bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4847 if (!TheCondStack.empty()) {
4848 if (TheCondStack.back().Ignore) {
4849 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004850 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004851 }
4852 }
4853
4854 if (!WithMessage)
4855 return Error(L, ".err encountered");
4856
4857 StringRef Message = ".error directive invoked in source file";
4858 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004859 if (Lexer.isNot(AsmToken::String))
4860 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004861
4862 Message = getTok().getStringContents();
4863 Lex();
4864 }
4865
Nirav Dave2364748a2016-09-16 18:30:20 +00004866 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004867}
4868
Nico Weber404012b2014-07-24 16:26:06 +00004869/// parseDirectiveWarning
4870/// ::= .warning [string]
4871bool AsmParser::parseDirectiveWarning(SMLoc L) {
4872 if (!TheCondStack.empty()) {
4873 if (TheCondStack.back().Ignore) {
4874 eatToEndOfStatement();
4875 return false;
4876 }
4877 }
4878
4879 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00004880
4881 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004882 if (Lexer.isNot(AsmToken::String))
4883 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00004884
4885 Message = getTok().getStringContents();
4886 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00004887 if (parseToken(AsmToken::EndOfStatement,
4888 "expected end of statement in '.warning' directive"))
4889 return true;
Nico Weber404012b2014-07-24 16:26:06 +00004890 }
4891
Nirav Dave2364748a2016-09-16 18:30:20 +00004892 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00004893}
4894
Jim Grosbach4b905842013-09-20 23:08:21 +00004895/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004896/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00004897bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004898 if (parseToken(AsmToken::EndOfStatement,
4899 "unexpected token in '.endif' directive"))
4900 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004901
Jim Grosbach4b905842013-09-20 23:08:21 +00004902 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004903 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
4904 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004905 if (!TheCondStack.empty()) {
4906 TheCondState = TheCondStack.back();
4907 TheCondStack.pop_back();
4908 }
4909
4910 return false;
4911}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00004912
Eli Bendersky17233942013-01-15 22:59:42 +00004913void AsmParser::initializeDirectiveKindMap() {
4914 DirectiveKindMap[".set"] = DK_SET;
4915 DirectiveKindMap[".equ"] = DK_EQU;
4916 DirectiveKindMap[".equiv"] = DK_EQUIV;
4917 DirectiveKindMap[".ascii"] = DK_ASCII;
4918 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4919 DirectiveKindMap[".string"] = DK_STRING;
4920 DirectiveKindMap[".byte"] = DK_BYTE;
4921 DirectiveKindMap[".short"] = DK_SHORT;
4922 DirectiveKindMap[".value"] = DK_VALUE;
4923 DirectiveKindMap[".2byte"] = DK_2BYTE;
4924 DirectiveKindMap[".long"] = DK_LONG;
4925 DirectiveKindMap[".int"] = DK_INT;
4926 DirectiveKindMap[".4byte"] = DK_4BYTE;
4927 DirectiveKindMap[".quad"] = DK_QUAD;
4928 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00004929 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00004930 DirectiveKindMap[".single"] = DK_SINGLE;
4931 DirectiveKindMap[".float"] = DK_FLOAT;
4932 DirectiveKindMap[".double"] = DK_DOUBLE;
4933 DirectiveKindMap[".align"] = DK_ALIGN;
4934 DirectiveKindMap[".align32"] = DK_ALIGN32;
4935 DirectiveKindMap[".balign"] = DK_BALIGN;
4936 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4937 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4938 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4939 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4940 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4941 DirectiveKindMap[".org"] = DK_ORG;
4942 DirectiveKindMap[".fill"] = DK_FILL;
4943 DirectiveKindMap[".zero"] = DK_ZERO;
4944 DirectiveKindMap[".extern"] = DK_EXTERN;
4945 DirectiveKindMap[".globl"] = DK_GLOBL;
4946 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00004947 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4948 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4949 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4950 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4951 DirectiveKindMap[".reference"] = DK_REFERENCE;
4952 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4953 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4954 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4955 DirectiveKindMap[".comm"] = DK_COMM;
4956 DirectiveKindMap[".common"] = DK_COMMON;
4957 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4958 DirectiveKindMap[".abort"] = DK_ABORT;
4959 DirectiveKindMap[".include"] = DK_INCLUDE;
4960 DirectiveKindMap[".incbin"] = DK_INCBIN;
4961 DirectiveKindMap[".code16"] = DK_CODE16;
4962 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4963 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004964 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00004965 DirectiveKindMap[".irp"] = DK_IRP;
4966 DirectiveKindMap[".irpc"] = DK_IRPC;
4967 DirectiveKindMap[".endr"] = DK_ENDR;
4968 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4969 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4970 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4971 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004972 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4973 DirectiveKindMap[".ifge"] = DK_IFGE;
4974 DirectiveKindMap[".ifgt"] = DK_IFGT;
4975 DirectiveKindMap[".ifle"] = DK_IFLE;
4976 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00004977 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00004978 DirectiveKindMap[".ifb"] = DK_IFB;
4979 DirectiveKindMap[".ifnb"] = DK_IFNB;
4980 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004981 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00004982 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00004983 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00004984 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4985 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4986 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4987 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4988 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004989 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00004990 DirectiveKindMap[".endif"] = DK_ENDIF;
4991 DirectiveKindMap[".skip"] = DK_SKIP;
4992 DirectiveKindMap[".space"] = DK_SPACE;
4993 DirectiveKindMap[".file"] = DK_FILE;
4994 DirectiveKindMap[".line"] = DK_LINE;
4995 DirectiveKindMap[".loc"] = DK_LOC;
4996 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004997 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00004998 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004999 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
5000 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00005001 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005002 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00005003 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005004 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
5005 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Eli Bendersky17233942013-01-15 22:59:42 +00005006 DirectiveKindMap[".sleb128"] = DK_SLEB128;
5007 DirectiveKindMap[".uleb128"] = DK_ULEB128;
5008 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
5009 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
5010 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
5011 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
5012 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
5013 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
5014 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
5015 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
5016 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
5017 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
5018 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
5019 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
5020 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
5021 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
5022 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
5023 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
5024 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
5025 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
5026 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00005027 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00005028 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
5029 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
5030 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00005031 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00005032 DirectiveKindMap[".endm"] = DK_ENDM;
5033 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
5034 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005035 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005036 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00005037 DirectiveKindMap[".warning"] = DK_WARNING;
Michael Zuckerman56704612017-05-01 13:20:12 +00005038 DirectiveKindMap[".altmacro"] = DK_ALTMACRO;
5039 DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00005040 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00005041 DirectiveKindMap[".dc"] = DK_DC;
5042 DirectiveKindMap[".dc.a"] = DK_DC_A;
5043 DirectiveKindMap[".dc.b"] = DK_DC_B;
5044 DirectiveKindMap[".dc.d"] = DK_DC_D;
5045 DirectiveKindMap[".dc.l"] = DK_DC_L;
5046 DirectiveKindMap[".dc.s"] = DK_DC_S;
5047 DirectiveKindMap[".dc.w"] = DK_DC_W;
5048 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00005049 DirectiveKindMap[".dcb"] = DK_DCB;
5050 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
5051 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
5052 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
5053 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
5054 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
5055 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00005056 DirectiveKindMap[".ds"] = DK_DS;
5057 DirectiveKindMap[".ds.b"] = DK_DS_B;
5058 DirectiveKindMap[".ds.d"] = DK_DS_D;
5059 DirectiveKindMap[".ds.l"] = DK_DS_L;
5060 DirectiveKindMap[".ds.p"] = DK_DS_P;
5061 DirectiveKindMap[".ds.s"] = DK_DS_S;
5062 DirectiveKindMap[".ds.w"] = DK_DS_W;
5063 DirectiveKindMap[".ds.x"] = DK_DS_X;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00005064}
5065
Jim Grosbach4b905842013-09-20 23:08:21 +00005066MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005067 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005068
Rafael Espindola34b9c512012-06-03 23:57:14 +00005069 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005070 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005071 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00005072 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005073 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00005074 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005075 }
5076
Rafael Espindola34b9c512012-06-03 23:57:14 +00005077 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00005078 (getTok().getIdentifier() == ".rept" ||
5079 getTok().getIdentifier() == ".irp" ||
5080 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005081 ++NestLevel;
5082 }
5083
5084 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00005085 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005086 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005087 EndToken = getTok();
5088 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005089 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005090 printError(getTok().getLoc(),
5091 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00005092 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005093 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005094 break;
5095 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005096 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005097 }
5098
Rafael Espindola34b9c512012-06-03 23:57:14 +00005099 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005100 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005101 }
5102
5103 const char *BodyStart = StartToken.getLoc().getPointer();
5104 const char *BodyEnd = EndToken.getLoc().getPointer();
5105 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5106
Rafael Espindola34b9c512012-06-03 23:57:14 +00005107 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005108 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00005109 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005110}
5111
Jim Grosbach4b905842013-09-20 23:08:21 +00005112void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005113 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005114 OS << ".endr\n";
5115
Rafael Espindola3560ff22014-08-27 20:03:13 +00005116 std::unique_ptr<MemoryBuffer> Instantiation =
5117 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005118
Rafael Espindola34b9c512012-06-03 23:57:14 +00005119 // Create the macro instantiation object and add to the current macro
5120 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005121 MacroInstantiation *MI = new MacroInstantiation(
5122 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005123 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005124
Rafael Espindola34b9c512012-06-03 23:57:14 +00005125 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005126 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005127 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005128 Lex();
5129}
5130
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005131/// parseDirectiveRept
5132/// ::= .rep | .rept count
5133bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005134 const MCExpr *CountExpr;
5135 SMLoc CountLoc = getTok().getLoc();
5136 if (parseExpression(CountExpr))
5137 return true;
5138
Rafael Espindola34b9c512012-06-03 23:57:14 +00005139 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00005140 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005141 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5142 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005143
Nirav Davea645433c2016-07-18 15:24:03 +00005144 if (check(Count < 0, CountLoc, "Count is negative") ||
5145 parseToken(AsmToken::EndOfStatement,
5146 "unexpected token in '" + Dir + "' directive"))
5147 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005148
5149 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005150 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005151 if (!M)
5152 return true;
5153
5154 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5155 // to hold the macro body with substitutions.
5156 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005157 raw_svector_ostream OS(Buf);
5158 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005159 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5160 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005161 return true;
5162 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005163 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005164
5165 return false;
5166}
5167
Jim Grosbach4b905842013-09-20 23:08:21 +00005168/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005169/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005170bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005171 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005172 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005173 if (check(parseIdentifier(Parameter.Name),
5174 "expected identifier in '.irp' directive") ||
5175 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5176 parseMacroArguments(nullptr, A) ||
5177 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005178 return true;
5179
Rafael Espindola768b41c2012-06-15 14:02:34 +00005180 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005181 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005182 if (!M)
5183 return true;
5184
5185 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5186 // to hold the macro body with substitutions.
5187 SmallString<256> Buf;
5188 raw_svector_ostream OS(Buf);
5189
Craig Topper84008482015-10-10 05:38:14 +00005190 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005191 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5192 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005193 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005194 return true;
5195 }
5196
Jim Grosbach4b905842013-09-20 23:08:21 +00005197 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005198
5199 return false;
5200}
5201
Jim Grosbach4b905842013-09-20 23:08:21 +00005202/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005203/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005204bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005205 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005206 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005207
5208 if (check(parseIdentifier(Parameter.Name),
5209 "expected identifier in '.irpc' directive") ||
5210 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5211 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005212 return true;
5213
5214 if (A.size() != 1 || A.front().size() != 1)
5215 return TokError("unexpected token in '.irpc' directive");
5216
5217 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005218 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5219 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005220
5221 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005222 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005223 if (!M)
5224 return true;
5225
5226 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5227 // to hold the macro body with substitutions.
5228 SmallString<256> Buf;
5229 raw_svector_ostream OS(Buf);
5230
5231 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005232 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005233 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005234 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005235
Toma Tabacu217116e2015-04-27 10:50:29 +00005236 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5237 // This is undocumented, but GAS seems to support it.
5238 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005239 return true;
5240 }
5241
Jim Grosbach4b905842013-09-20 23:08:21 +00005242 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005243
5244 return false;
5245}
5246
Jim Grosbach4b905842013-09-20 23:08:21 +00005247bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005248 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005249 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005250
5251 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005252 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005253 assert(getLexer().is(AsmToken::EndOfStatement));
5254
Jim Grosbach4b905842013-09-20 23:08:21 +00005255 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005256 return false;
5257}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005258
Jim Grosbach4b905842013-09-20 23:08:21 +00005259bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005260 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005261 const MCExpr *Value;
5262 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005263 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005264 return true;
5265 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5266 if (!MCE)
5267 return Error(ExprLoc, "unexpected expression in _emit");
5268 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005269 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005270 return Error(ExprLoc, "literal value out of range for directive");
5271
Craig Topper7d5b2312015-10-10 05:25:02 +00005272 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005273 return false;
5274}
5275
Jim Grosbach4b905842013-09-20 23:08:21 +00005276bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005277 const MCExpr *Value;
5278 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005279 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005280 return true;
5281 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5282 if (!MCE)
5283 return Error(ExprLoc, "unexpected expression in align");
5284 uint64_t IntValue = MCE->getValue();
5285 if (!isPowerOf2_64(IntValue))
5286 return Error(ExprLoc, "literal value not a power of two greater then zero");
5287
Craig Topper7d5b2312015-10-10 05:25:02 +00005288 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005289 return false;
5290}
5291
Chad Rosierf43fcf52013-02-13 21:27:17 +00005292// We are comparing pointers, but the pointers are relative to a single string.
5293// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005294static int rewritesSort(const AsmRewrite *AsmRewriteA,
5295 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005296 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5297 return -1;
5298 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5299 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005300
Chad Rosierfce4fab2013-04-08 17:43:47 +00005301 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5302 // rewrite to the same location. Make sure the SizeDirective rewrite is
5303 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5304 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005305 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5306 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005307 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005308
Jim Grosbach4b905842013-09-20 23:08:21 +00005309 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5310 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005311 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005312 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005313}
5314
Jim Grosbach4b905842013-09-20 23:08:21 +00005315bool AsmParser::parseMSInlineAsm(
5316 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00005317 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
Jim Grosbach4b905842013-09-20 23:08:21 +00005318 SmallVectorImpl<std::string> &Constraints,
5319 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5320 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005321 SmallVector<void *, 4> InputDecls;
5322 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005323 SmallVector<bool, 4> InputDeclsAddressOf;
5324 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005325 SmallVector<std::string, 4> InputConstraints;
5326 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005327 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005328
Benjamin Kramer1a136112013-02-15 20:37:21 +00005329 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005330
5331 // Prime the lexer.
5332 Lex();
5333
5334 // While we have input, parse each statement.
5335 unsigned InputIdx = 0;
5336 unsigned OutputIdx = 0;
5337 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005338 // Parse curly braces marking block start/end
5339 if (parseCurlyBlockScope(AsmStrRewrites))
5340 continue;
5341
Eli Friedman0f4871d2012-10-22 23:58:19 +00005342 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005343 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005344
Nirav Dave2364748a2016-09-16 18:30:20 +00005345 if (StatementErr || Info.ParseError) {
5346 // Emit pending errors if any exist.
5347 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005348 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005349 }
5350
5351 // No pending error should exist here.
5352 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005353
Benjamin Kramer1a136112013-02-15 20:37:21 +00005354 if (Info.Opcode == ~0U)
5355 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005356
Benjamin Kramer1a136112013-02-15 20:37:21 +00005357 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005358
Benjamin Kramer1a136112013-02-15 20:37:21 +00005359 // Build the list of clobbers, outputs and inputs.
5360 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005361 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005362
Benjamin Kramer1a136112013-02-15 20:37:21 +00005363 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005364 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005365 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005366
Benjamin Kramer1a136112013-02-15 20:37:21 +00005367 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005368 if (Operand.isReg() && !Operand.needAddressOf() &&
5369 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005370 unsigned NumDefs = Desc.getNumDefs();
5371 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005372 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5373 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005374 continue;
5375 }
5376
5377 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005378 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005379 if (SymName.empty())
5380 continue;
5381
David Blaikie960ea3f2014-06-08 16:18:35 +00005382 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005383 if (!OpDecl)
5384 continue;
5385
5386 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005387 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005388 if (isOutput) {
5389 ++InputIdx;
5390 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005391 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005392 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005393 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005394 } else {
5395 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005396 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5397 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005398 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005399 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005400 }
Reid Kleckneree088972013-12-10 18:27:32 +00005401
5402 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005403 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5404 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005405 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005406 }
5407
5408 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005409 NumOutputs = OutputDecls.size();
5410 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005411
5412 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005413 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5414 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5415 ClobberRegs.end());
5416 Clobbers.assign(ClobberRegs.size(), std::string());
5417 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5418 raw_string_ostream OS(Clobbers[I]);
5419 IP->printRegName(OS, ClobberRegs[I]);
5420 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005421
5422 // Merge the various outputs and inputs. Output are expected first.
5423 if (NumOutputs || NumInputs) {
5424 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005425 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005426 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005427 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005428 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005429 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005430 }
5431 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005432 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005433 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005434 }
5435 }
5436
5437 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005438 std::string AsmStringIR;
5439 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005440 StringRef ASMString =
5441 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5442 const char *AsmStart = ASMString.begin();
5443 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005444 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005445 for (const AsmRewrite &AR : AsmStrRewrites) {
5446 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005447 if (Kind == AOK_Delete)
5448 continue;
5449
David Majnemer8114c1a2014-06-23 02:17:16 +00005450 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005451 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005452
Chad Rosier120eefd2013-03-19 17:32:17 +00005453 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005454 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005455 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005456
Chad Rosier37e755c2012-10-23 17:43:43 +00005457 // Skip the original expression.
5458 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005459 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005460 continue;
5461 }
5462
Chad Rosierff10ed12013-04-12 16:26:42 +00005463 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005464 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005465 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005466 default:
5467 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005468 case AOK_Imm:
David Majnemer8114c1a2014-06-23 02:17:16 +00005469 OS << "$$" << AR.Val;
Chad Rosier11c42f22012-10-26 18:04:20 +00005470 break;
5471 case AOK_ImmPrefix:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005472 OS << "$$";
Chad Rosier8bce6642012-10-18 15:49:34 +00005473 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005474 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005475 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005476 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005477 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005478 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005479 break;
5480 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005481 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005482 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005483 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005484 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005485 default: break;
5486 case 8: OS << "byte ptr "; break;
5487 case 16: OS << "word ptr "; break;
5488 case 32: OS << "dword ptr "; break;
5489 case 64: OS << "qword ptr "; break;
5490 case 80: OS << "xword ptr "; break;
5491 case 128: OS << "xmmword ptr "; break;
5492 case 256: OS << "ymmword ptr "; break;
5493 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005494 break;
5495 case AOK_Emit:
5496 OS << ".byte";
5497 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005498 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005499 // MS alignment directives are measured in bytes. If the native assembler
5500 // measures alignment in bytes, we can pass it straight through.
5501 OS << ".align";
5502 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5503 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005504
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005505 // Alignment is in log2 form, so print that instead and skip the original
5506 // immediate.
5507 unsigned Val = AR.Val;
5508 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005509 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005510 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5511 break;
5512 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005513 case AOK_EVEN:
5514 OS << ".even";
5515 break;
Chad Rosierf0e87202012-10-25 20:41:34 +00005516 case AOK_DotOperator:
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005517 // Insert the dot if the user omitted it.
Alp Tokere69170a2014-06-26 22:52:05 +00005518 OS.flush();
5519 if (AsmStringIR.back() != '.')
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005520 OS << '.';
David Majnemer8114c1a2014-06-23 02:17:16 +00005521 OS << AR.Val;
Chad Rosierf0e87202012-10-25 20:41:34 +00005522 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005523 case AOK_EndOfStatement:
5524 OS << "\n\t";
5525 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005526 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005527
Chad Rosier8bce6642012-10-18 15:49:34 +00005528 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005529 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005530 }
5531
5532 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005533 if (AsmStart != AsmEnd)
5534 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005535
5536 AsmString = OS.str();
5537 return false;
5538}
5539
Pete Cooper80d21cb2015-06-22 19:35:57 +00005540namespace llvm {
5541namespace MCParserUtils {
5542
5543/// Returns whether the given symbol is used anywhere in the given expression,
5544/// or subexpressions.
5545static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5546 switch (Value->getKind()) {
5547 case MCExpr::Binary: {
5548 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5549 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5550 isSymbolUsedInExpression(Sym, BE->getRHS());
5551 }
5552 case MCExpr::Target:
5553 case MCExpr::Constant:
5554 return false;
5555 case MCExpr::SymbolRef: {
5556 const MCSymbol &S =
5557 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5558 if (S.isVariable())
5559 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5560 return &S == Sym;
5561 }
5562 case MCExpr::Unary:
5563 return isSymbolUsedInExpression(
5564 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5565 }
5566
5567 llvm_unreachable("Unknown expr kind!");
5568}
5569
5570bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5571 MCAsmParser &Parser, MCSymbol *&Sym,
5572 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005573
5574 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005575 SMLoc EqualLoc = Parser.getTok().getLoc();
Pete Cooper80d21cb2015-06-22 19:35:57 +00005576
5577 if (Parser.parseExpression(Value)) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00005578 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005579 }
5580
5581 // Note: we don't count b as used in "a = b". This is to allow
5582 // a = b
5583 // b = c
5584
Nirav Dave1a9044b2016-10-24 14:35:29 +00005585 if (Parser.parseToken(AsmToken::EndOfStatement))
5586 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00005587
5588 // Validate that the LHS is allowed to be a variable (either it has not been
5589 // used as a symbol, or it is an absolute symbol).
5590 Sym = Parser.getContext().lookupSymbol(Name);
5591 if (Sym) {
5592 // Diagnose assignment to a label.
5593 //
5594 // FIXME: Diagnostics. Note the location of the definition as a label.
5595 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5596 if (isSymbolUsedInExpression(Sym, Value))
5597 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005598 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5599 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005600 ; // Allow redefinitions of undefined symbols only used in directives.
5601 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5602 ; // Allow redefinitions of variables that haven't yet been used.
5603 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5604 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5605 else if (!Sym->isVariable())
5606 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5607 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5608 return Parser.Error(EqualLoc,
5609 "invalid reassignment of non-absolute variable '" +
5610 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005611 } else if (Name == ".") {
Oliver Stannard268f42f2016-12-14 10:43:58 +00005612 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005613 return false;
5614 } else
5615 Sym = Parser.getContext().getOrCreateSymbol(Name);
5616
5617 Sym->setRedefinable(allow_redef);
5618
5619 return false;
5620}
5621
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005622} // end namespace MCParserUtils
5623} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005624
Daniel Dunbar01e36072010-07-17 02:26:10 +00005625/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005626MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
Sanne Wouda29338752017-02-08 14:48:05 +00005627 MCStreamer &Out, const MCAsmInfo &MAI,
5628 unsigned CB) {
5629 return new AsmParser(SM, C, Out, MAI, CB);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005630}