blob: 529f16525fe33264ca4a1d00d55f9b6c4060a11f [file] [log] [blame]
Chris Lattnerb0133452009-06-21 20:16:42 +00001//===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This class implements the parser for assembly files.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar2af16532010-09-24 01:59:56 +000014#include "llvm/ADT/APFloat.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000015#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/None.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000018#include "llvm/ADT/STLExtras.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000019#include "llvm/ADT/SmallString.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000020#include "llvm/ADT/SmallVector.h"
Reid Kleckner26fa1bf2017-09-19 18:14:45 +000021#include "llvm/ADT/StringExtras.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000022#include "llvm/ADT/StringMap.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000023#include "llvm/ADT/StringRef.h"
Daniel Dunbareb6bb322009-07-27 23:20:52 +000024#include "llvm/ADT/Twine.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000025#include "llvm/BinaryFormat/Dwarf.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000026#include "llvm/MC/MCAsmInfo.h"
Reid Klecknera5b1eef2016-08-26 17:58:37 +000027#include "llvm/MC/MCCodeView.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000028#include "llvm/MC/MCContext.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000029#include "llvm/MC/MCDirectives.h"
Evan Cheng11424442011-07-26 00:24:13 +000030#include "llvm/MC/MCDwarf.h"
Daniel Dunbar115e4d62009-08-31 08:06:59 +000031#include "llvm/MC/MCExpr.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000032#include "llvm/MC/MCInstPrinter.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000033#include "llvm/MC/MCInstrDesc.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000034#include "llvm/MC/MCInstrInfo.h"
Rafael Espindolae28610d2013-12-09 20:26:40 +000035#include "llvm/MC/MCObjectFileInfo.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000036#include "llvm/MC/MCParser/AsmCond.h"
37#include "llvm/MC/MCParser/AsmLexer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000038#include "llvm/MC/MCParser/MCAsmLexer.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000039#include "llvm/MC/MCParser/MCAsmParser.h"
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000040#include "llvm/MC/MCParser/MCAsmParserExtension.h"
Pete Cooper80d21cb2015-06-22 19:35:57 +000041#include "llvm/MC/MCParser/MCAsmParserUtils.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000042#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000043#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Cheng76792992011-07-20 05:58:47 +000044#include "llvm/MC/MCRegisterInfo.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000045#include "llvm/MC/MCSection.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000046#include "llvm/MC/MCStreamer.h"
Daniel Dunbarae7ac012009-06-29 23:43:14 +000047#include "llvm/MC/MCSymbol.h"
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000048#include "llvm/MC/MCTargetOptions.h"
Daniel Sanders9f6ad492015-11-12 13:33:00 +000049#include "llvm/MC/MCValue.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000050#include "llvm/Support/Casting.h"
Davide Italiano7c9fc732016-07-27 05:51:56 +000051#include "llvm/Support/CommandLine.h"
Benjamin Kramer4efe5062012-01-28 15:28:41 +000052#include "llvm/Support/ErrorHandling.h"
Paul Robinson29f5f982018-01-09 23:31:48 +000053#include "llvm/Support/MD5.h"
Jim Grosbach76346c32011-06-29 16:05:14 +000054#include "llvm/Support/MathExtras.h"
Kevin Enderbye233dda2010-06-28 21:45:58 +000055#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000056#include "llvm/Support/SMLoc.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000057#include "llvm/Support/SourceMgr.h"
Chris Lattner36e02122009-06-21 20:54:55 +000058#include "llvm/Support/raw_ostream.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000059#include <algorithm>
60#include <cassert>
Nick Lewycky0de20af2010-12-19 20:43:38 +000061#include <cctype>
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000062#include <climits>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000063#include <cstddef>
64#include <cstdint>
Benjamin Kramerd59664f2014-04-29 23:26:49 +000065#include <deque>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000066#include <memory>
Davide Italiano7c9fc732016-07-27 05:51:56 +000067#include <sstream>
Chad Rosier8bce6642012-10-18 15:49:34 +000068#include <string>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000069#include <tuple>
70#include <utility>
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000071#include <vector>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000072
Chris Lattnerb0133452009-06-21 20:16:42 +000073using namespace llvm;
74
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000075MCAsmParserSemaCallback::~MCAsmParserSemaCallback() = default;
Nick Lewyckyac612272012-10-19 07:00:09 +000076
Davide Italiano7c9fc732016-07-27 05:51:56 +000077static cl::opt<unsigned> AsmMacroMaxNestingDepth(
78 "asm-macro-max-nesting-depth", cl::init(20), cl::Hidden,
79 cl::desc("The maximum nesting depth allowed for assembly macros."));
80
Daniel Dunbar86033402010-07-12 17:54:38 +000081namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +000082
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000083/// Helper types for tracking macro definitions.
Eli Benderskya313ae62013-01-16 18:56:50 +000084typedef std::vector<AsmToken> MCAsmMacroArgument;
85typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000086
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000087/// Helper class for storing information about an active macro
Daniel Dunbar43235712010-07-18 18:54:11 +000088/// instantiation.
89struct MacroInstantiation {
Daniel Dunbar43235712010-07-18 18:54:11 +000090 /// The location of the instantiation.
91 SMLoc InstantiationLoc;
92
Daniel Dunbar40f1d852012-12-01 01:38:48 +000093 /// The buffer where parsing should resume upon instantiation completion.
94 int ExitBuffer;
95
Daniel Dunbar43235712010-07-18 18:54:11 +000096 /// The location where parsing should resume upon instantiation completion.
97 SMLoc ExitLoc;
98
Nico Weber155dccd12014-07-24 17:08:39 +000099 /// The depth of TheCondStack at the start of the instantiation.
100 size_t CondStackDepth;
101
Daniel Dunbar43235712010-07-18 18:54:11 +0000102public:
Rafael Espindola9eef18c2014-08-27 19:49:03 +0000103 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
Daniel Dunbar43235712010-07-18 18:54:11 +0000104};
105
Eli Friedman0f4871d2012-10-22 23:58:19 +0000106struct ParseStatementInfo {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000107 /// The parsed operands from the last parsed statement.
David Blaikie960ea3f2014-06-08 16:18:35 +0000108 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000109
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000110 /// The opcode from the last parsed instruction.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000111 unsigned Opcode = ~0U;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000112
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000113 /// Was there an error parsing the inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000114 bool ParseError = false;
Chad Rosier149e8e02012-12-12 22:45:52 +0000115
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000116 SmallVectorImpl<AsmRewrite> *AsmRewrites = nullptr;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000117
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000118 ParseStatementInfo() = delete;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000119 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000120 : AsmRewrites(rewrites) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000121};
122
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000123/// The concrete assembly parser instance.
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000124class AsmParser : public MCAsmParser {
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000125private:
126 AsmLexer Lexer;
127 MCContext &Ctx;
128 MCStreamer &Out;
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000129 const MCAsmInfo &MAI;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000130 SourceMgr &SrcMgr;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000131 SourceMgr::DiagHandlerTy SavedDiagHandler;
132 void *SavedDiagContext;
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000133 std::unique_ptr<MCAsmParserExtension> PlatformParser;
Rafael Espindola82065cb2011-04-11 21:49:50 +0000134
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000135 /// This is the current buffer index we're lexing from as managed by the
136 /// SourceMgr object.
Alp Tokera55b95b2014-07-06 10:33:31 +0000137 unsigned CurBuffer;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000138
139 AsmCond TheCondState;
140 std::vector<AsmCond> TheCondStack;
141
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000142 /// maps directive names to handler methods in parser
Eli Bendersky17233942013-01-15 22:59:42 +0000143 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000144 /// addDirectiveHandler.
Eli Bendersky17233942013-01-15 22:59:42 +0000145 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000146
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000147 /// Stack of active macro instantiations.
Daniel Dunbar43235712010-07-18 18:54:11 +0000148 std::vector<MacroInstantiation*> ActiveMacros;
149
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000150 /// List of bodies of anonymous macros.
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +0000151 std::deque<MCAsmMacro> MacroLikeBodies;
152
Daniel Dunbar828984f2010-07-18 18:38:02 +0000153 /// Boolean tracking whether macro substitution is enabled.
Eli Benderskyc2f6f922013-01-14 18:08:41 +0000154 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000155
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000156 /// Keeps track of how many .macro's have been instantiated.
Toma Tabacu217116e2015-04-27 10:50:29 +0000157 unsigned NumOfMacroInstantiations;
158
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000159 /// The values from the last parsed cpp hash file line comment if any.
Tim Northoverc0bef992016-04-13 19:46:54 +0000160 struct CppHashInfoTy {
161 StringRef Filename;
Andrew Kaylorca196472016-04-21 20:09:35 +0000162 int64_t LineNumber = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000163 SMLoc Loc;
Andrew Kaylorca196472016-04-21 20:09:35 +0000164 unsigned Buf = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000165 };
166 CppHashInfoTy CppHashInfo;
167
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000168 /// List of forward directional labels for diagnosis at the end.
Tim Northoverc0bef992016-04-13 19:46:54 +0000169 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
170
Devang Patela173ee52012-01-31 18:14:05 +0000171 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000172 unsigned AssemblerDialect = ~0U;
Devang Patela173ee52012-01-31 18:14:05 +0000173
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000174 /// is Darwin compatibility enabled?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000175 bool IsDarwin = false;
Preston Gurd05500642012-09-19 20:36:12 +0000176
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000177 /// Are we parsing ms-style inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000178 bool ParsingInlineAsm = false;
Chad Rosier49963552012-10-13 00:26:04 +0000179
Paul Robinsoncc7344a2018-06-14 13:38:20 +0000180 /// Did we already inform the user about inconsistent MD5 usage?
181 bool ReportedInconsistentMD5 = false;
182
Craig Topperc81aff72018-09-25 20:55:55 +0000183 // Is alt macro mode enabled.
184 bool AltMacroMode = false;
185
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000186public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000187 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000188 const MCAsmInfo &MAI, unsigned CB);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000189 AsmParser(const AsmParser &) = delete;
190 AsmParser &operator=(const AsmParser &) = delete;
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000191 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000192
Craig Topper59be68f2014-03-08 07:14:16 +0000193 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000194
Craig Topper59be68f2014-03-08 07:14:16 +0000195 void addDirectiveHandler(StringRef Directive,
196 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000197 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000198 }
199
Toma Tabacu11e14a92015-04-21 11:50:52 +0000200 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
201 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
202 }
203
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000204 /// @name MCAsmParser Interface
205 /// {
206
Craig Topper59be68f2014-03-08 07:14:16 +0000207 SourceMgr &getSourceManager() override { return SrcMgr; }
208 MCAsmLexer &getLexer() override { return Lexer; }
209 MCContext &getContext() override { return Ctx; }
210 MCStreamer &getStreamer() override { return Out; }
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000211
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000212 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
213
Craig Topper59be68f2014-03-08 07:14:16 +0000214 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000215 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000216 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000217 else
218 return AssemblerDialect;
219 }
Craig Topper59be68f2014-03-08 07:14:16 +0000220 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000221 AssemblerDialect = i;
222 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000223
Nirav Dave2364748a2016-09-16 18:30:20 +0000224 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
225 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
226 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000227
Craig Topper59be68f2014-03-08 07:14:16 +0000228 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000229
Yunzhong Gao27ea29b2016-09-02 23:15:29 +0000230 void setParsingInlineAsm(bool V) override {
231 ParsingInlineAsm = V;
232 Lexer.setParsingMSInlineAsm(V);
233 }
Craig Topper59be68f2014-03-08 07:14:16 +0000234 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000235
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000236 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000237 unsigned &NumOutputs, unsigned &NumInputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000238 SmallVectorImpl<std::pair<void *,bool>> &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000239 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000240 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000241 const MCInstrInfo *MII, const MCInstPrinter *IP,
242 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000243
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000244 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000245 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
246 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
247 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000248 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
249 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000250 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000251
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000252 /// Parse a floating point expression using the float \p Semantics
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000253 /// and set \p Res to the value.
254 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
255
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000256 /// Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000257 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000258 bool parseIdentifier(StringRef &Res) override;
259 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000260
Nirav Davef43cc9f2016-10-10 15:24:54 +0000261 bool checkForValidSection() override;
Nirav Davea645433c2016-07-18 15:24:03 +0000262
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000263 /// }
264
265private:
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000266 bool parseStatement(ParseStatementInfo &Info,
267 MCAsmParserSemaCallback *SI);
Marina Yatsina5f5de9f2016-03-07 18:11:16 +0000268 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
Craig Topper3c76c522015-09-20 23:35:59 +0000269 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000270
Jim Grosbach4b905842013-09-20 23:08:21 +0000271 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000272 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000273 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000274 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000275 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000276 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000277
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000278 /// Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000279 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000280
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000281 /// Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000282 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000283
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000284 /// Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000285 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000286
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000287 /// Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000288 ///
289 /// \param M The macro.
290 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000291 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000292
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000293 /// Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000294 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000295
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000296 /// Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000297 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000298
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000299 /// Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000300 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000301
Jim Grosbach4b905842013-09-20 23:08:21 +0000302 void printMacroInstantiations();
303 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Nirav Dave2364748a2016-09-16 18:30:20 +0000304 SMRange Range = None) const {
305 ArrayRef<SMRange> Ranges(Range);
Chris Lattner72845262011-10-16 05:47:55 +0000306 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000307 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000308 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000309
Paul Robinson938d9a02018-03-22 15:48:01 +0000310 /// Should we emit DWARF describing this assembler source? (Returns false if
311 /// the source has .file directives, which means we don't want to generate
312 /// info describing the assembler source itself.)
313 bool enabledGenDwarfForAssembly();
314
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000315 /// Enter the specified file. This returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000316 bool enterIncludeFile(const std::string &Filename);
317
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000318 /// Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000319 /// This returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000320 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
321 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
Daniel Dunbar43235712010-07-18 18:54:11 +0000322
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000323 /// Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000324 /// current token is not set; clients should ensure Lex() is called
325 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000326 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000327 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000328 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000329 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000330
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000331 /// Parse up to the end of statement and a return the contents from the
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000332 /// current token until the end of the statement; the current token on exit
333 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000334 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000335
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000336 /// Parse until the end of a statement or a comma is encountered,
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000337 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000338 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000339
Jim Grosbach4b905842013-09-20 23:08:21 +0000340 bool parseAssignment(StringRef Name, bool allow_redef,
Nirav Dave7fd992a2018-08-16 16:31:14 +0000341 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000342
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000343 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
344 MCBinaryExpr::Opcode &Kind);
345
Jim Grosbach4b905842013-09-20 23:08:21 +0000346 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
347 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
348 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000349
Jim Grosbach4b905842013-09-20 23:08:21 +0000350 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000351
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000352 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
353 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
354
Eli Bendersky17233942013-01-15 22:59:42 +0000355 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000356 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000357 DK_NO_DIRECTIVE, // Placeholder
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000358 DK_SET,
359 DK_EQU,
360 DK_EQUIV,
361 DK_ASCII,
362 DK_ASCIZ,
363 DK_STRING,
364 DK_BYTE,
365 DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000366 DK_RELOC,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000367 DK_VALUE,
368 DK_2BYTE,
369 DK_LONG,
370 DK_INT,
371 DK_4BYTE,
372 DK_QUAD,
373 DK_8BYTE,
374 DK_OCTA,
375 DK_DC,
376 DK_DC_A,
377 DK_DC_B,
378 DK_DC_D,
379 DK_DC_L,
380 DK_DC_S,
381 DK_DC_W,
382 DK_DC_X,
383 DK_DCB,
384 DK_DCB_B,
385 DK_DCB_D,
386 DK_DCB_L,
387 DK_DCB_S,
388 DK_DCB_W,
389 DK_DCB_X,
390 DK_DS,
391 DK_DS_B,
392 DK_DS_D,
393 DK_DS_L,
394 DK_DS_P,
395 DK_DS_S,
396 DK_DS_W,
397 DK_DS_X,
398 DK_SINGLE,
399 DK_FLOAT,
400 DK_DOUBLE,
401 DK_ALIGN,
402 DK_ALIGN32,
403 DK_BALIGN,
404 DK_BALIGNW,
405 DK_BALIGNL,
406 DK_P2ALIGN,
407 DK_P2ALIGNW,
408 DK_P2ALIGNL,
409 DK_ORG,
410 DK_FILL,
411 DK_ENDR,
412 DK_BUNDLE_ALIGN_MODE,
413 DK_BUNDLE_LOCK,
414 DK_BUNDLE_UNLOCK,
415 DK_ZERO,
416 DK_EXTERN,
417 DK_GLOBL,
418 DK_GLOBAL,
419 DK_LAZY_REFERENCE,
420 DK_NO_DEAD_STRIP,
421 DK_SYMBOL_RESOLVER,
422 DK_PRIVATE_EXTERN,
423 DK_REFERENCE,
424 DK_WEAK_DEFINITION,
425 DK_WEAK_REFERENCE,
426 DK_WEAK_DEF_CAN_BE_HIDDEN,
427 DK_COMM,
428 DK_COMMON,
429 DK_LCOMM,
430 DK_ABORT,
431 DK_INCLUDE,
432 DK_INCBIN,
433 DK_CODE16,
434 DK_CODE16GCC,
435 DK_REPT,
436 DK_IRP,
437 DK_IRPC,
438 DK_IF,
439 DK_IFEQ,
440 DK_IFGE,
441 DK_IFGT,
442 DK_IFLE,
443 DK_IFLT,
444 DK_IFNE,
445 DK_IFB,
446 DK_IFNB,
447 DK_IFC,
448 DK_IFEQS,
449 DK_IFNC,
450 DK_IFNES,
451 DK_IFDEF,
452 DK_IFNDEF,
453 DK_IFNOTDEF,
454 DK_ELSEIF,
455 DK_ELSE,
456 DK_ENDIF,
457 DK_SPACE,
458 DK_SKIP,
459 DK_FILE,
460 DK_LINE,
461 DK_LOC,
462 DK_STABS,
463 DK_CV_FILE,
464 DK_CV_FUNC_ID,
465 DK_CV_INLINE_SITE_ID,
466 DK_CV_LOC,
467 DK_CV_LINETABLE,
468 DK_CV_INLINE_LINETABLE,
469 DK_CV_DEF_RANGE,
470 DK_CV_STRINGTABLE,
Reid Kleckner06d02d02018-09-07 21:30:52 +0000471 DK_CV_STRING,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000472 DK_CV_FILECHECKSUMS,
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000473 DK_CV_FILECHECKSUM_OFFSET,
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000474 DK_CV_FPO_DATA,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000475 DK_CFI_SECTIONS,
476 DK_CFI_STARTPROC,
477 DK_CFI_ENDPROC,
478 DK_CFI_DEF_CFA,
479 DK_CFI_DEF_CFA_OFFSET,
480 DK_CFI_ADJUST_CFA_OFFSET,
481 DK_CFI_DEF_CFA_REGISTER,
482 DK_CFI_OFFSET,
483 DK_CFI_REL_OFFSET,
484 DK_CFI_PERSONALITY,
485 DK_CFI_LSDA,
486 DK_CFI_REMEMBER_STATE,
487 DK_CFI_RESTORE_STATE,
488 DK_CFI_SAME_VALUE,
489 DK_CFI_RESTORE,
490 DK_CFI_ESCAPE,
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000491 DK_CFI_RETURN_COLUMN,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000492 DK_CFI_SIGNAL_FRAME,
493 DK_CFI_UNDEFINED,
494 DK_CFI_REGISTER,
495 DK_CFI_WINDOW_SAVE,
496 DK_MACROS_ON,
497 DK_MACROS_OFF,
498 DK_ALTMACRO,
499 DK_NOALTMACRO,
500 DK_MACRO,
501 DK_EXITM,
502 DK_ENDM,
503 DK_ENDMACRO,
504 DK_PURGEM,
505 DK_SLEB128,
506 DK_ULEB128,
507 DK_ERR,
508 DK_ERROR,
509 DK_WARNING,
Coby Tayree01e53202017-10-02 14:36:31 +0000510 DK_PRINT,
Peter Collingbourne3e227332018-07-17 22:17:18 +0000511 DK_ADDRSIG,
512 DK_ADDRSIG_SYM,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000513 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000514 };
515
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000516 /// Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000517 /// directives parsed by this class.
518 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000519
520 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000521 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000522 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Nirav Dave1a9044b2016-10-24 14:35:29 +0000523 bool parseDirectiveValue(StringRef IDVal,
524 unsigned Size); // ".byte", ".long", ...
525 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
526 bool parseDirectiveRealValue(StringRef IDVal,
527 const fltSemantics &); // ".single", ...
Jim Grosbach4b905842013-09-20 23:08:21 +0000528 bool parseDirectiveFill(); // ".fill"
529 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000530 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000531 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
532 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000533 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000534 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000535
Eli Bendersky17233942013-01-15 22:59:42 +0000536 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000537 bool parseDirectiveFile(SMLoc DirectiveLoc);
538 bool parseDirectiveLine();
539 bool parseDirectiveLoc();
540 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000541
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000542 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
Reid Kleckner06d02d02018-09-07 21:30:52 +0000543 // ".cv_inline_linetable", ".cv_def_range", ".cv_string"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000544 bool parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000545 bool parseDirectiveCVFuncId();
546 bool parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000547 bool parseDirectiveCVLoc();
548 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000549 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000550 bool parseDirectiveCVDefRange();
Reid Kleckner06d02d02018-09-07 21:30:52 +0000551 bool parseDirectiveCVString();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000552 bool parseDirectiveCVStringTable();
553 bool parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000554 bool parseDirectiveCVFileChecksumOffset();
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000555 bool parseDirectiveCVFPOData();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000556
Eli Bendersky17233942013-01-15 22:59:42 +0000557 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000558 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000559 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000560 bool parseDirectiveCFISections();
561 bool parseDirectiveCFIStartProc();
562 bool parseDirectiveCFIEndProc();
563 bool parseDirectiveCFIDefCfaOffset();
564 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
565 bool parseDirectiveCFIAdjustCfaOffset();
566 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
567 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
568 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
569 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
570 bool parseDirectiveCFIRememberState();
571 bool parseDirectiveCFIRestoreState();
572 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
573 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
574 bool parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000575 bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +0000576 bool parseDirectiveCFISignalFrame();
577 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000578
579 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000580 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000581 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000582 bool parseDirectiveEndMacro(StringRef Directive);
583 bool parseDirectiveMacro(SMLoc DirectiveLoc);
584 bool parseDirectiveMacrosOnOff(StringRef Directive);
Michael Zuckerman56704612017-05-01 13:20:12 +0000585 // alternate macro mode directives
586 bool parseDirectiveAltmacro(StringRef Directive);
Eli Benderskyf483ff92012-12-20 19:05:53 +0000587 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000588 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000589 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000590 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000591 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000592 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000593
Eli Bendersky17233942013-01-15 22:59:42 +0000594 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000595 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000596
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000597 // ".dcb"
598 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
599 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
Petr Hosek85b2f672016-09-23 21:53:36 +0000600 // ".ds"
601 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000602
Eli Bendersky17233942013-01-15 22:59:42 +0000603 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000604 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000605
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000606 /// Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000607 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000608 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000609
Jim Grosbach4b905842013-09-20 23:08:21 +0000610 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000611
Jim Grosbach4b905842013-09-20 23:08:21 +0000612 bool parseDirectiveAbort(); // ".abort"
613 bool parseDirectiveInclude(); // ".include"
614 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000615
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000616 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
617 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000618 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000619 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000620 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000621 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000622 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
623 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000624 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000625 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
626 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
627 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
628 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000629 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000630
Jim Grosbach4b905842013-09-20 23:08:21 +0000631 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000632 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000633
Rafael Espindola34b9c512012-06-03 23:57:14 +0000634 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000635 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
636 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000637 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000638 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000639 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
640 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
641 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000642
Chad Rosierc7f552c2013-02-12 21:33:51 +0000643 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000644 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000645 size_t Len);
646
647 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000648 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000649
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000650 // "end"
651 bool parseDirectiveEnd(SMLoc DirectiveLoc);
652
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000653 // ".err" or ".error"
654 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000655
Nico Weber404012b2014-07-24 16:26:06 +0000656 // ".warning"
657 bool parseDirectiveWarning(SMLoc DirectiveLoc);
658
Coby Tayree01e53202017-10-02 14:36:31 +0000659 // .print <double-quotes-string>
660 bool parseDirectivePrint(SMLoc DirectiveLoc);
661
Peter Collingbourne3e227332018-07-17 22:17:18 +0000662 // Directives to support address-significance tables.
663 bool parseDirectiveAddrsig();
664 bool parseDirectiveAddrsigSym();
665
Eli Bendersky17233942013-01-15 22:59:42 +0000666 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000667};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000668
669} // end anonymous namespace
Daniel Dunbar86033402010-07-12 17:54:38 +0000670
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000671namespace llvm {
672
673extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000674extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000675extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000676
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000677} // end namespace llvm
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000678
Chris Lattnerc35681b2010-01-19 19:46:13 +0000679enum { DEFAULT_ADDRSPACE = 0 };
680
David Blaikie9f380a32015-03-16 18:06:57 +0000681AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000682 const MCAsmInfo &MAI, unsigned CB = 0)
David Blaikie9f380a32015-03-16 18:06:57 +0000683 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000684 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
Nirav Dave2364748a2016-09-16 18:30:20 +0000685 HadError = false;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000686 // Save the old handler.
687 SavedDiagHandler = SrcMgr.getDiagHandler();
688 SavedDiagContext = SrcMgr.getDiagContext();
689 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000690 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000691 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000692
Daniel Dunbarc5011082010-07-12 18:12:02 +0000693 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000694 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
695 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000696 PlatformParser.reset(createCOFFAsmParser());
697 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000698 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000699 PlatformParser.reset(createDarwinAsmParser());
700 IsDarwin = true;
701 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000702 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000703 PlatformParser.reset(createELFAsmParser());
704 break;
Dan Gohman18eafb62017-02-22 01:23:18 +0000705 case MCObjectFileInfo::IsWasm:
Sam Cleggf009da22018-04-19 22:00:53 +0000706 // TODO: WASM will need its own MCAsmParserExtension implementation, but
707 // for now we can re-use the ELF one, since the directives can be the
Sam Cleggcf2a9e22018-07-16 23:09:29 +0000708 // same for now.
Sam Cleggf009da22018-04-19 22:00:53 +0000709 PlatformParser.reset(createELFAsmParser());
Dan Gohman18eafb62017-02-22 01:23:18 +0000710 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000711 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000712
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000713 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000714 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000715
716 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000717}
718
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000719AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000720 assert((HadError || ActiveMacros.empty()) &&
721 "Unexpected active macro instantiation!");
Sanne Wouda29338752017-02-08 14:48:05 +0000722
723 // Restore the saved diagnostics handler and context for use during
724 // finalization.
725 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000726}
727
Jim Grosbach4b905842013-09-20 23:08:21 +0000728void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000729 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000730 for (std::vector<MacroInstantiation *>::const_reverse_iterator
731 it = ActiveMacros.rbegin(),
732 ie = ActiveMacros.rend();
733 it != ie; ++it)
734 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000735 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000736}
737
Nirav Dave2364748a2016-09-16 18:30:20 +0000738void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
739 printPendingErrors();
740 printMessage(L, SourceMgr::DK_Note, Msg, Range);
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000741 printMacroInstantiations();
742}
743
Nirav Dave2364748a2016-09-16 18:30:20 +0000744bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000745 if(getTargetParser().getTargetOptions().MCNoWarn)
746 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000747 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Nirav Dave2364748a2016-09-16 18:30:20 +0000748 return Error(L, Msg, Range);
749 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000750 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000751 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000752}
753
Nirav Dave2364748a2016-09-16 18:30:20 +0000754bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000755 HadError = true;
Nirav Dave2364748a2016-09-16 18:30:20 +0000756 printMessage(L, SourceMgr::DK_Error, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000757 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000758 return true;
759}
760
Jim Grosbach4b905842013-09-20 23:08:21 +0000761bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000762 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000763 unsigned NewBuf =
764 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
765 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000766 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000767
Sean Callanan7a77eae2010-01-21 00:19:58 +0000768 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000769 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000770 return false;
771}
Daniel Dunbar43235712010-07-18 18:54:11 +0000772
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000773/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000774/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000775/// returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000776bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
777 const MCExpr *Count, SMLoc Loc) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000778 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000779 unsigned NewBuf =
780 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
781 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000782 return true;
783
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000784 // Pick up the bytes from the file and emit them.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000785 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
786 Bytes = Bytes.drop_front(Skip);
787 if (Count) {
788 int64_t Res;
Nirav Dave6c0665e2018-04-30 19:22:40 +0000789 if (!Count->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
Petr Hosek2f4ac442016-09-23 00:41:06 +0000790 return Error(Loc, "expected absolute expression");
791 if (Res < 0)
792 return Warning(Loc, "negative count has no effect");
793 Bytes = Bytes.take_front(Res);
794 }
795 getStreamer().EmitBytes(Bytes);
Kevin Enderby109f25c2011-12-14 21:47:48 +0000796 return false;
797}
798
Alp Tokera55b95b2014-07-06 10:33:31 +0000799void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
800 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000801 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
802 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000803}
804
Sean Callanan7a77eae2010-01-21 00:19:58 +0000805const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000806 if (Lexer.getTok().is(AsmToken::Error))
807 Error(Lexer.getErrLoc(), Lexer.getErr());
808
Nirav Dave53a72f42016-07-11 12:42:14 +0000809 // if it's a end of statement with a comment in it
810 if (getTok().is(AsmToken::EndOfStatement)) {
811 // if this is a line comment output it.
Nirav Dave670109d2017-06-09 14:04:03 +0000812 if (!getTok().getString().empty() && getTok().getString().front() != '\n' &&
Nirav Dave53a72f42016-07-11 12:42:14 +0000813 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
814 Out.addExplicitComment(Twine(getTok().getString()));
815 }
816
Sean Callanan7a77eae2010-01-21 00:19:58 +0000817 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000818
819 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000820 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000821 if (MAI.preserveAsmComments())
822 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000823 tok = &Lexer.Lex();
824 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000825
Sean Callanan7a77eae2010-01-21 00:19:58 +0000826 if (tok->is(AsmToken::Eof)) {
827 // If this is the end of an included file, pop the parent file off the
828 // include stack.
829 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
830 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000831 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000832 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000833 }
834 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000835
Sean Callanan7a77eae2010-01-21 00:19:58 +0000836 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000837}
838
Paul Robinson938d9a02018-03-22 15:48:01 +0000839bool AsmParser::enabledGenDwarfForAssembly() {
840 // Check whether the user specified -g.
841 if (!getContext().getGenDwarfForAssembly())
842 return false;
843 // If we haven't encountered any .file directives (which would imply that
844 // the assembler source was produced with debug info already) then emit one
845 // describing the assembler source file itself.
846 if (getContext().getGenDwarfFileNumber() == 0)
847 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
848 0, StringRef(), getContext().getMainFileName()));
849 return true;
850}
851
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000852bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000853 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000854 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000855 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000856
Chris Lattner36e02122009-06-21 20:54:55 +0000857 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000858 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000859
860 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000861 AsmCond StartingCondState = TheCondState;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000862 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000863
Kevin Enderby6469fc22011-11-01 22:27:22 +0000864 // If we are generating dwarf for assembly source files save the initial text
Paul Robinson938d9a02018-03-22 15:48:01 +0000865 // section. (Don't use enabledGenDwarfForAssembly() here, as we aren't
866 // emitting any actual debug info yet and haven't had a chance to parse any
867 // embedded .file directives.)
Kevin Enderby6469fc22011-11-01 22:27:22 +0000868 if (getContext().getGenDwarfForAssembly()) {
Eric Christopher445c9522016-10-14 05:47:37 +0000869 MCSection *Sec = getStreamer().getCurrentSectionOnly();
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000870 if (!Sec->getBeginSymbol()) {
871 MCSymbol *SectionStartSym = getContext().createTempSymbol();
872 getStreamer().EmitLabel(SectionStartSym);
873 Sec->setBeginSymbol(SectionStartSym);
874 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000875 bool InsertResult = getContext().addGenDwarfSection(Sec);
876 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000877 (void)InsertResult;
Kevin Enderby6469fc22011-11-01 22:27:22 +0000878 }
879
Chris Lattner73f36112009-07-02 21:53:43 +0000880 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000881 while (Lexer.isNot(AsmToken::Eof)) {
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000882 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000883 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000884 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000885
Nirav Dave2364748a2016-09-16 18:30:20 +0000886 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
887 // for printing ErrMsg via Lex() only if no (presumably better) parser error
888 // exists.
889 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
Nirav Dave1180e6892016-06-02 17:15:05 +0000890 Lex();
891 }
892
Nirav Dave2364748a2016-09-16 18:30:20 +0000893 // parseStatement returned true so may need to emit an error.
894 printPendingErrors();
895
896 // Skipping to the next line if needed.
897 if (!getLexer().isAtStartOfStatement())
898 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000899 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000900
Nirav Dave2364748a2016-09-16 18:30:20 +0000901 // All errors should have been emitted.
902 assert(!hasPendingError() && "unexpected error from parseStatement");
903
Oliver Stannard21718282016-07-26 14:19:47 +0000904 getTargetParser().flushPendingInstructions(getStreamer());
905
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000906 if (TheCondState.TheCond != StartingCondState.TheCond ||
907 TheCondState.Ignore != StartingCondState.Ignore)
Nirav Dave2364748a2016-09-16 18:30:20 +0000908 printError(getTok().getLoc(), "unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000909 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000910 const auto &LineTables = getContext().getMCDwarfLineTables();
911 if (!LineTables.empty()) {
912 unsigned Index = 0;
913 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
914 if (File.Name.empty() && Index != 0)
Nirav Dave2364748a2016-09-16 18:30:20 +0000915 printError(getTok().getLoc(), "unassigned file number: " +
916 Twine(Index) +
917 " for .file directives");
David Blaikie8bf66c42014-04-01 07:35:52 +0000918 ++Index;
919 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000920 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000921
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000922 // Check to see that all assembler local symbols were actually defined.
923 // Targets that don't do subsections via symbols may not want this, though,
924 // so conservatively exclude them. Only do this if we're finalizing, though,
925 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000926 if (!NoFinalize) {
927 if (MAI.hasSubsectionsViaSymbols()) {
928 for (const auto &TableEntry : getContext().getSymbols()) {
929 MCSymbol *Sym = TableEntry.getValue();
930 // Variable symbols may not be marked as defined, so check those
931 // explicitly. If we know it's a variable, we have a definition for
932 // the purposes of this check.
933 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
934 // FIXME: We would really like to refer back to where the symbol was
935 // first referenced for a source location. We need to add something
936 // to track that. Currently, we just point to the end of the file.
Nirav Dave2364748a2016-09-16 18:30:20 +0000937 printError(getTok().getLoc(), "assembler local symbol '" +
938 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000939 }
940 }
941
942 // Temporary symbols like the ones for directional jumps don't go in the
943 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000944 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
945 if (std::get<2>(LocSym)->isUndefined()) {
946 // Reset the state of any "# line file" directives we've seen to the
947 // context as it was at the diagnostic site.
948 CppHashInfo = std::get<1>(LocSym);
Nirav Dave2364748a2016-09-16 18:30:20 +0000949 printError(std::get<0>(LocSym), "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000950 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000951 }
952 }
953
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000954 // Finalize the output stream if there are no errors and if the client wants
955 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000956 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000957 Out.Finish();
958
Oliver Stannard07b43d32015-11-17 09:58:07 +0000959 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000960}
961
Nirav Davef43cc9f2016-10-10 15:24:54 +0000962bool AsmParser::checkForValidSection() {
Eric Christopher445c9522016-10-14 05:47:37 +0000963 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000964 Out.InitSections(false);
Nirav Davef43cc9f2016-10-10 15:24:54 +0000965 return Error(getTok().getLoc(),
966 "expected section directive before assembly directive");
Daniel Dunbare5444a82010-09-09 22:42:59 +0000967 }
Nirav Davef43cc9f2016-10-10 15:24:54 +0000968 return false;
Daniel Dunbare5444a82010-09-09 22:42:59 +0000969}
970
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000971/// Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000972void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000973 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000974 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000975
Chris Lattnere5074c42009-06-22 01:29:09 +0000976 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000977 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000978 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000979}
980
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000981StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000982 const char *Start = getTok().getLoc().getPointer();
983
Jim Grosbach4b905842013-09-20 23:08:21 +0000984 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000985 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000986
987 const char *End = getTok().getLoc().getPointer();
988 return StringRef(Start, End - Start);
989}
Chris Lattner78db3622009-06-22 05:51:26 +0000990
Jim Grosbach4b905842013-09-20 23:08:21 +0000991StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000992 const char *Start = getTok().getLoc().getPointer();
993
994 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000995 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000996 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000997
998 const char *End = getTok().getLoc().getPointer();
999 return StringRef(Start, End - Start);
1000}
1001
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001002/// Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001003/// NOTE: This assumes the leading '(' has already been consumed.
1004///
1005/// parenexpr ::= expr)
1006///
Jim Grosbach4b905842013-09-20 23:08:21 +00001007bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1008 if (parseExpression(Res))
1009 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001010 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +00001011 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001012 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001013 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +00001014 return false;
1015}
Chris Lattner78db3622009-06-22 05:51:26 +00001016
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001017/// Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001018/// NOTE: This assumes the leading '[' has already been consumed.
1019///
1020/// bracketexpr ::= expr]
1021///
Jim Grosbach4b905842013-09-20 23:08:21 +00001022bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1023 if (parseExpression(Res))
1024 return true;
Nirav Davea645433c2016-07-18 15:24:03 +00001025 EndLoc = getTok().getEndLoc();
1026 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
1027 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001028 return false;
1029}
1030
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001031/// Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001032/// primaryexpr ::= (parenexpr
1033/// primaryexpr ::= symbol
1034/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +00001035/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +00001036/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +00001037bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001038 SMLoc FirstTokenLoc = getLexer().getLoc();
1039 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
1040 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +00001041 default:
1042 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +00001043 // If we have an error assume that we've already handled it.
1044 case AsmToken::Error:
1045 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001046 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001047 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001048 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001049 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001050 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001051 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +00001052 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +00001053 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00001054 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +00001055 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +00001056 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001057 if (parseIdentifier(Identifier)) {
Nirav Daved0463322016-10-12 13:58:07 +00001058 // We may have failed but $ may be a valid token.
1059 if (getTok().is(AsmToken::Dollar)) {
David Majnemer0c58bc62013-09-25 10:47:21 +00001060 if (Lexer.getMAI().getDollarIsPC()) {
Nirav Daved0463322016-10-12 13:58:07 +00001061 Lex();
David Majnemer0c58bc62013-09-25 10:47:21 +00001062 // This is a '$' reference, which references the current PC. Emit a
1063 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001064 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +00001065 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001066 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +00001067 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +00001068 EndLoc = FirstTokenLoc;
1069 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +00001070 }
1071 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +00001072 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001073 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001074 // Parse symbol variant
1075 std::pair<StringRef, StringRef> Split;
1076 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +00001077 if (FirstTokenKind == AsmToken::String) {
1078 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +00001079 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +00001080 SMLoc AtLoc = getLexer().getLoc();
1081 StringRef VName;
1082 if (parseIdentifier(VName))
1083 return Error(AtLoc, "expected symbol variant after '@'");
1084
1085 Split = std::make_pair(Identifier, VName);
1086 }
1087 } else {
1088 Split = Identifier.split('@');
1089 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001090 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +00001091 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +00001092 StringRef VName;
1093 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +00001094 // eat ')'.
1095 if (parseToken(AsmToken::RParen,
1096 "unexpected token in variant, expected ')'"))
1097 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +00001098 Split = std::make_pair(Identifier, VName);
1099 }
Daniel Dunbar24764322010-08-24 19:13:42 +00001100
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001101 EndLoc = SMLoc::getFromPointer(Identifier.end());
1102
Daniel Dunbard20cda02009-10-16 01:34:54 +00001103 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +00001104 StringRef SymbolName = Identifier;
Weiming Zhaocf26d562016-12-01 18:00:36 +00001105 if (SymbolName.empty())
Francis Visoiu Mistrih627d1462018-10-08 10:28:11 +00001106 return Error(getLexer().getLoc(), "expected a symbol reference");
Weiming Zhaocf26d562016-12-01 18:00:36 +00001107
Hans Wennborgce69d772013-10-18 20:46:28 +00001108 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +00001109
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001110 // Lookup the symbol variant if used.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001111 if (!Split.second.empty()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001112 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +00001113 if (Variant != MCSymbolRefExpr::VK_Invalid) {
1114 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +00001115 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +00001116 Variant = MCSymbolRefExpr::VK_None;
1117 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +00001118 return Error(SMLoc::getFromPointer(Split.second.begin()),
1119 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001120 }
1121 }
Daniel Dunbar55992562010-03-15 23:51:06 +00001122
Jim Grosbach6f482002015-05-18 18:43:14 +00001123 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +00001124
Daniel Dunbard20cda02009-10-16 01:34:54 +00001125 // If this is an absolute variable reference, substitute it now to preserve
1126 // semantics in the face of reassignment.
Nirav Dave05b58912018-06-05 15:13:39 +00001127 if (Sym->isVariable()) {
1128 auto V = Sym->getVariableValue(/*SetUsed*/ false);
Nirav Daveb1f9e4d2018-09-17 20:34:26 +00001129 bool DoInline = isa<MCConstantExpr>(V) && !Variant;
Nirav Dave05b58912018-06-05 15:13:39 +00001130 if (auto TV = dyn_cast<MCTargetExpr>(V))
1131 DoInline = TV->inlineAssignedExpr();
1132 if (DoInline) {
1133 if (Variant)
1134 return Error(EndLoc, "unexpected modifier on variable reference");
1135 Res = Sym->getVariableValue(/*SetUsed*/ false);
1136 return false;
1137 }
Daniel Dunbard20cda02009-10-16 01:34:54 +00001138 }
1139
1140 // Otherwise create a symbol ref.
Chad Rosier9245e122017-01-19 20:06:32 +00001141 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
Chris Lattner78db3622009-06-22 05:51:26 +00001142 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001143 }
David Woodhousef42a6662014-02-01 16:20:54 +00001144 case AsmToken::BigNum:
1145 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001146 case AsmToken::Integer: {
1147 SMLoc Loc = getTok().getLoc();
1148 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001149 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001150 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001151 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001152 // Look for 'b' or 'f' following an Integer as a directional label
1153 if (Lexer.getKind() == AsmToken::Identifier) {
1154 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001155 // Lookup the symbol variant if used.
1156 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1157 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1158 if (Split.first.size() != IDVal.size()) {
1159 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001160 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001161 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001162 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001163 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001164 if (IDVal == "f" || IDVal == "b") {
1165 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001166 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001167 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001168 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001169 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001170 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001171 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001172 Lex(); // Eat identifier.
1173 }
1174 }
Chris Lattner78db3622009-06-22 05:51:26 +00001175 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001176 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001177 case AsmToken::Real: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001178 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001179 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001180 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001181 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001182 Lex(); // Eat token.
1183 return false;
1184 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001185 case AsmToken::Dot: {
1186 // This is a '.' reference, which references the current PC. Emit a
1187 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001188 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001189 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001190 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001191 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001192 Lex(); // Eat identifier.
1193 return false;
1194 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001195 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001196 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001197 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001198 case AsmToken::LBrac:
1199 if (!PlatformParser->HasBracketExpressions())
1200 return TokError("brackets expression not supported on this target");
1201 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001202 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001203 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001204 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001205 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001206 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001207 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001208 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001209 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001210 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001211 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001212 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001213 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001214 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001215 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001216 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001217 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001218 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001219 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001220 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001221 // MIPS unary expression operators. The lexer won't generate these tokens if
1222 // MCAsmInfo::HasMipsExpressions is false for the target.
1223 case AsmToken::PercentCall16:
1224 case AsmToken::PercentCall_Hi:
1225 case AsmToken::PercentCall_Lo:
1226 case AsmToken::PercentDtprel_Hi:
1227 case AsmToken::PercentDtprel_Lo:
1228 case AsmToken::PercentGot:
1229 case AsmToken::PercentGot_Disp:
1230 case AsmToken::PercentGot_Hi:
1231 case AsmToken::PercentGot_Lo:
1232 case AsmToken::PercentGot_Ofst:
1233 case AsmToken::PercentGot_Page:
1234 case AsmToken::PercentGottprel:
1235 case AsmToken::PercentGp_Rel:
1236 case AsmToken::PercentHi:
1237 case AsmToken::PercentHigher:
1238 case AsmToken::PercentHighest:
1239 case AsmToken::PercentLo:
1240 case AsmToken::PercentNeg:
1241 case AsmToken::PercentPcrel_Hi:
1242 case AsmToken::PercentPcrel_Lo:
1243 case AsmToken::PercentTlsgd:
1244 case AsmToken::PercentTlsldm:
1245 case AsmToken::PercentTprel_Hi:
1246 case AsmToken::PercentTprel_Lo:
1247 Lex(); // Eat the operator.
1248 if (Lexer.isNot(AsmToken::LParen))
1249 return TokError("expected '(' after operator");
1250 Lex(); // Eat the operator.
1251 if (parseExpression(Res, EndLoc))
1252 return true;
1253 if (Lexer.isNot(AsmToken::RParen))
1254 return TokError("expected ')'");
1255 Lex(); // Eat the operator.
1256 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1257 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001258 }
1259}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001260
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001261bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001262 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001263 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001264}
1265
Daniel Dunbar55f16672010-09-17 02:47:07 +00001266const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001267AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001268 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001269 // Ask the target implementation about this expression first.
1270 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1271 if (NewE)
1272 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001273 // Recurse over the given expression, rebuilding it to apply the given variant
1274 // if there is exactly one symbol.
1275 switch (E->getKind()) {
1276 case MCExpr::Target:
1277 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001278 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001279
1280 case MCExpr::SymbolRef: {
1281 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1282
1283 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001284 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1285 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001286 return E;
1287 }
1288
Jim Grosbach13760bd2015-05-30 01:25:56 +00001289 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001290 }
1291
1292 case MCExpr::Unary: {
1293 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001294 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001295 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001296 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001297 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001298 }
1299
1300 case MCExpr::Binary: {
1301 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001302 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1303 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001304
1305 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001306 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001307
Jim Grosbach4b905842013-09-20 23:08:21 +00001308 if (!LHS)
1309 LHS = BE->getLHS();
1310 if (!RHS)
1311 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001312
Jim Grosbach13760bd2015-05-30 01:25:56 +00001313 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001314 }
1315 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001316
Craig Toppera2886c22012-02-07 05:05:23 +00001317 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001318}
1319
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001320/// This function checks if the next token is <string> type or arithmetic.
1321/// string that begin with character '<' must end with character '>'.
1322/// otherwise it is arithmetics.
1323/// If the function returns a 'true' value,
1324/// the End argument will be filled with the last location pointed to the '>'
1325/// character.
1326
Craig Topper3da977b2018-09-25 19:37:35 +00001327/// There is a gap between the AltMacro's documentation and the single quote
1328/// implementation. GCC does not fully support this feature and so we will not
1329/// support it.
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001330/// TODO: Adding single quote as a string.
Craig Topperd2aab832018-09-25 20:13:55 +00001331static bool isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc) {
Craig Topperc06ee832018-09-25 18:33:00 +00001332 assert((StrLoc.getPointer() != nullptr) &&
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001333 "Argument to the function cannot be a NULL value");
1334 const char *CharPtr = StrLoc.getPointer();
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001335 while ((*CharPtr != '>') && (*CharPtr != '\n') && (*CharPtr != '\r') &&
1336 (*CharPtr != '\0')) {
1337 if (*CharPtr == '!')
1338 CharPtr++;
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001339 CharPtr++;
1340 }
1341 if (*CharPtr == '>') {
1342 EndLoc = StrLoc.getFromPointer(CharPtr + 1);
1343 return true;
1344 }
1345 return false;
1346}
1347
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001348/// creating a string without the escape characters '!'.
Craig Topperd2aab832018-09-25 20:13:55 +00001349static std::string altMacroString(StringRef AltMacroStr) {
1350 std::string Res;
Michael Zuckermanff298792017-05-10 14:00:57 +00001351 for (size_t Pos = 0; Pos < AltMacroStr.size(); Pos++) {
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001352 if (AltMacroStr[Pos] == '!')
1353 Pos++;
1354 Res += AltMacroStr[Pos];
1355 }
Craig Topperd2aab832018-09-25 20:13:55 +00001356 return Res;
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001357}
1358
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001359/// Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001360///
Jim Grosbachbd164242011-08-20 16:24:13 +00001361/// expr ::= expr &&,|| expr -> lowest.
1362/// expr ::= expr |,^,&,! expr
1363/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1364/// expr ::= expr <<,>> expr
1365/// expr ::= expr +,- expr
1366/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001367/// expr ::= primaryexpr
1368///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001369bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001370 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001371 Res = nullptr;
Nirav Dave7fd992a2018-08-16 16:31:14 +00001372 if (getTargetParser().parsePrimaryExpr(Res, EndLoc) ||
1373 parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001374 return true;
1375
Daniel Dunbar55f16672010-09-17 02:47:07 +00001376 // As a special case, we support 'a op b @ modifier' by rewriting the
1377 // expression to include the modifier. This is inefficient, but in general we
1378 // expect users to use 'a@modifier op b'.
1379 if (Lexer.getKind() == AsmToken::At) {
1380 Lex();
1381
1382 if (Lexer.isNot(AsmToken::Identifier))
1383 return TokError("unexpected symbol modifier following '@'");
1384
1385 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001386 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001387 if (Variant == MCSymbolRefExpr::VK_Invalid)
1388 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1389
Jim Grosbach4b905842013-09-20 23:08:21 +00001390 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001391 if (!ModifiedRes) {
1392 return TokError("invalid modifier '" + getTok().getIdentifier() +
1393 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001394 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001395
Daniel Dunbar55f16672010-09-17 02:47:07 +00001396 Res = ModifiedRes;
1397 Lex();
1398 }
1399
Nirav Dave6c0665e2018-04-30 19:22:40 +00001400 // Try to constant fold it up front, if possible. Do not exploit
1401 // assembler here.
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001402 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001403 if (Res->evaluateAsAbsolute(Value))
1404 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001405
1406 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001407}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001408
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001409bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001410 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001411 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001412}
1413
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001414bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1415 SMLoc &EndLoc) {
1416 if (parseParenExpr(Res, EndLoc))
1417 return true;
1418
1419 for (; ParenDepth > 0; --ParenDepth) {
1420 if (parseBinOpRHS(1, Res, EndLoc))
1421 return true;
1422
1423 // We don't Lex() the last RParen.
1424 // This is the same behavior as parseParenExpression().
1425 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001426 EndLoc = getTok().getEndLoc();
1427 if (parseToken(AsmToken::RParen,
1428 "expected ')' in parentheses expression"))
1429 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001430 }
1431 }
1432 return false;
1433}
1434
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001435bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001436 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001437
Daniel Dunbar75630b32009-06-30 02:10:03 +00001438 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001439 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001440 return true;
1441
Nirav Dave6c0665e2018-04-30 19:22:40 +00001442 if (!Expr->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001443 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001444
1445 return false;
1446}
1447
David Majnemer0993e0b2015-10-26 03:15:34 +00001448static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1449 MCBinaryExpr::Opcode &Kind,
1450 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001451 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001452 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001453 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001454
Jim Grosbach4b905842013-09-20 23:08:21 +00001455 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001456 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001457 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001458 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001459 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001460 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001461 return 1;
1462
Jim Grosbach4b905842013-09-20 23:08:21 +00001463 // Low Precedence: |, &, ^
1464 //
1465 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001466 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001467 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001468 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001469 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001470 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001471 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001472 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001473 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001474 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001475
Jim Grosbach4b905842013-09-20 23:08:21 +00001476 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001477 case AsmToken::EqualEqual:
1478 Kind = MCBinaryExpr::EQ;
1479 return 3;
1480 case AsmToken::ExclaimEqual:
1481 case AsmToken::LessGreater:
1482 Kind = MCBinaryExpr::NE;
1483 return 3;
1484 case AsmToken::Less:
1485 Kind = MCBinaryExpr::LT;
1486 return 3;
1487 case AsmToken::LessEqual:
1488 Kind = MCBinaryExpr::LTE;
1489 return 3;
1490 case AsmToken::Greater:
1491 Kind = MCBinaryExpr::GT;
1492 return 3;
1493 case AsmToken::GreaterEqual:
1494 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001495 return 3;
1496
Jim Grosbach4b905842013-09-20 23:08:21 +00001497 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001498 case AsmToken::LessLess:
1499 Kind = MCBinaryExpr::Shl;
1500 return 4;
1501 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001502 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001503 return 4;
1504
Jim Grosbach4b905842013-09-20 23:08:21 +00001505 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001506 case AsmToken::Plus:
1507 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001508 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001509 case AsmToken::Minus:
1510 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001511 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001512
Jim Grosbach4b905842013-09-20 23:08:21 +00001513 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001514 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001515 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001516 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001517 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001518 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001519 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001520 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001521 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001522 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001523 }
1524}
1525
David Majnemer0993e0b2015-10-26 03:15:34 +00001526static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1527 MCBinaryExpr::Opcode &Kind,
1528 bool ShouldUseLogicalShr) {
1529 switch (K) {
1530 default:
1531 return 0; // not a binop.
1532
1533 // Lowest Precedence: &&, ||
1534 case AsmToken::AmpAmp:
1535 Kind = MCBinaryExpr::LAnd;
1536 return 2;
1537 case AsmToken::PipePipe:
1538 Kind = MCBinaryExpr::LOr;
1539 return 1;
1540
1541 // Low Precedence: ==, !=, <>, <, <=, >, >=
1542 case AsmToken::EqualEqual:
1543 Kind = MCBinaryExpr::EQ;
1544 return 3;
1545 case AsmToken::ExclaimEqual:
1546 case AsmToken::LessGreater:
1547 Kind = MCBinaryExpr::NE;
1548 return 3;
1549 case AsmToken::Less:
1550 Kind = MCBinaryExpr::LT;
1551 return 3;
1552 case AsmToken::LessEqual:
1553 Kind = MCBinaryExpr::LTE;
1554 return 3;
1555 case AsmToken::Greater:
1556 Kind = MCBinaryExpr::GT;
1557 return 3;
1558 case AsmToken::GreaterEqual:
1559 Kind = MCBinaryExpr::GTE;
1560 return 3;
1561
1562 // Low Intermediate Precedence: +, -
1563 case AsmToken::Plus:
1564 Kind = MCBinaryExpr::Add;
1565 return 4;
1566 case AsmToken::Minus:
1567 Kind = MCBinaryExpr::Sub;
1568 return 4;
1569
1570 // High Intermediate Precedence: |, &, ^
1571 //
1572 // FIXME: gas seems to support '!' as an infix operator?
1573 case AsmToken::Pipe:
1574 Kind = MCBinaryExpr::Or;
1575 return 5;
1576 case AsmToken::Caret:
1577 Kind = MCBinaryExpr::Xor;
1578 return 5;
1579 case AsmToken::Amp:
1580 Kind = MCBinaryExpr::And;
1581 return 5;
1582
1583 // Highest Precedence: *, /, %, <<, >>
1584 case AsmToken::Star:
1585 Kind = MCBinaryExpr::Mul;
1586 return 6;
1587 case AsmToken::Slash:
1588 Kind = MCBinaryExpr::Div;
1589 return 6;
1590 case AsmToken::Percent:
1591 Kind = MCBinaryExpr::Mod;
1592 return 6;
1593 case AsmToken::LessLess:
1594 Kind = MCBinaryExpr::Shl;
1595 return 6;
1596 case AsmToken::GreaterGreater:
1597 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1598 return 6;
1599 }
1600}
1601
1602unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1603 MCBinaryExpr::Opcode &Kind) {
1604 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1605 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1606 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1607}
1608
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001609/// Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001610/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001611bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001612 SMLoc &EndLoc) {
Chad Rosier9245e122017-01-19 20:06:32 +00001613 SMLoc StartLoc = Lexer.getLoc();
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001614 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001615 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001616 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001617
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001618 // If the next token is lower precedence than we are allowed to eat, return
1619 // successfully with what we ate already.
1620 if (TokPrec < Precedence)
1621 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001622
Sean Callanan686ed8d2010-01-19 20:22:31 +00001623 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001624
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001625 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001626 const MCExpr *RHS;
Nirav Dave7fd992a2018-08-16 16:31:14 +00001627 if (getTargetParser().parsePrimaryExpr(RHS, EndLoc))
Jim Grosbach4b905842013-09-20 23:08:21 +00001628 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001629
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001630 // If BinOp binds less tightly with RHS than the operator after RHS, let
1631 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001632 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001633 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001634 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1635 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001636
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001637 // Merge LHS and RHS according to operator.
Chad Rosier9245e122017-01-19 20:06:32 +00001638 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001639 }
1640}
1641
Chris Lattner36e02122009-06-21 20:54:55 +00001642/// ParseStatement:
1643/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001644/// ::= Label* Directive ...Operands... EndOfStatement
1645/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001646bool AsmParser::parseStatement(ParseStatementInfo &Info,
1647 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001648 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001649 // Eat initial spaces and comments
1650 while (Lexer.is(AsmToken::Space))
1651 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001652 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001653 // if this is a line comment we can drop it safely
Nirav Dave670109d2017-06-09 14:04:03 +00001654 if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
Nirav Davefd910412016-06-17 16:06:17 +00001655 getTok().getString().front() == '\n')
1656 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001657 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001658 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001659 }
Nirav Davefd910412016-06-17 16:06:17 +00001660 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001661 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001662 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001663 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001664 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001665 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001666 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001667 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001668 if (Lexer.is(AsmToken::Integer)) {
1669 LocalLabelVal = getTok().getIntVal();
1670 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001671 if (!TheCondState.Ignore) {
1672 Lex(); // always eat a token
1673 return Error(IDLoc, "unexpected token at start of statement");
1674 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001675 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001676 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001677 IDVal = getTok().getString();
1678 Lex(); // Consume the integer token to be used as an identifier token.
1679 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001680 if (!TheCondState.Ignore) {
1681 Lex(); // always eat a token
1682 return Error(IDLoc, "unexpected token at start of statement");
1683 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001684 }
1685 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001686 } else if (Lexer.is(AsmToken::Dot)) {
1687 // Treat '.' as a valid identifier in this context.
1688 Lex();
1689 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001690 } else if (Lexer.is(AsmToken::LCurly)) {
1691 // Treat '{' as a valid identifier in this context.
1692 Lex();
1693 IDVal = "{";
1694
1695 } else if (Lexer.is(AsmToken::RCurly)) {
1696 // Treat '}' as a valid identifier in this context.
1697 Lex();
1698 IDVal = "}";
Yonghong Song06ff6552017-09-12 17:55:23 +00001699 } else if (Lexer.is(AsmToken::Star) &&
1700 getTargetParser().starIsStartOfStatement()) {
1701 // Accept '*' as a valid start of statement.
1702 Lex();
1703 IDVal = "*";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001704 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001705 if (!TheCondState.Ignore) {
1706 Lex(); // always eat a token
1707 return Error(IDLoc, "unexpected token at start of statement");
1708 }
Chris Lattner926885c2010-04-17 18:14:27 +00001709 IDVal = "";
1710 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001711
Chris Lattner926885c2010-04-17 18:14:27 +00001712 // Handle conditional assembly here before checking for skipping. We
1713 // have to do this so that .endif isn't skipped in a ".if 0" block for
1714 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001715 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001716 DirectiveKindMap.find(IDVal);
1717 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1718 ? DK_NO_DIRECTIVE
1719 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001720 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001721 default:
1722 break;
1723 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001724 case DK_IFEQ:
1725 case DK_IFGE:
1726 case DK_IFGT:
1727 case DK_IFLE:
1728 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001729 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001730 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001731 case DK_IFB:
1732 return parseDirectiveIfb(IDLoc, true);
1733 case DK_IFNB:
1734 return parseDirectiveIfb(IDLoc, false);
1735 case DK_IFC:
1736 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001737 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001738 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001739 case DK_IFNC:
1740 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001741 case DK_IFNES:
1742 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001743 case DK_IFDEF:
1744 return parseDirectiveIfdef(IDLoc, true);
1745 case DK_IFNDEF:
1746 case DK_IFNOTDEF:
1747 return parseDirectiveIfdef(IDLoc, false);
1748 case DK_ELSEIF:
1749 return parseDirectiveElseIf(IDLoc);
1750 case DK_ELSE:
1751 return parseDirectiveElse(IDLoc);
1752 case DK_ENDIF:
1753 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001754 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001755
Eli Bendersky88024712013-01-16 19:32:36 +00001756 // Ignore the statement if in the middle of inactive conditional
1757 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001758 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001759 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001760 return false;
1761 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001762
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001763 // FIXME: Recurse on local labels?
1764
1765 // See what kind of statement we have.
1766 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001767 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001768 if (!getTargetParser().isLabel(ID))
1769 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001770 if (checkForValidSection())
1771 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001772
Chris Lattner36e02122009-06-21 20:54:55 +00001773 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001774 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001775
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001776 // Diagnose attempt to use '.' as a label.
1777 if (IDVal == ".")
1778 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1779
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001780 // Diagnose attempt to use a variable as a label.
1781 //
1782 // FIXME: Diagnostics. Note the location of the definition as a label.
1783 // FIXME: This doesn't diagnose assignment to a symbol which has been
1784 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001785 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001786 if (LocalLabelVal == -1) {
1787 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001788 StringRef RewrittenLabel =
1789 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001790 assert(!RewrittenLabel.empty() &&
Nico Weber67e715f2015-06-19 23:43:47 +00001791 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001792 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1793 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001794 IDVal = RewrittenLabel;
1795 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001796 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001797 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001798 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
Nirav Dave9263ae32016-08-02 19:17:54 +00001799 // End of Labels should be treated as end of line for lexing
1800 // purposes but that information is not available to the Lexer who
1801 // does not understand Labels. This may cause us to see a Hash
1802 // here instead of a preprocessor line comment.
1803 if (getTok().is(AsmToken::Hash)) {
1804 StringRef CommentStr = parseStringToEndOfStatement();
1805 Lexer.Lex();
1806 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1807 }
1808
Nirav Dave8ea792d2016-07-13 14:03:12 +00001809 // Consume any end of statement token, if present, to avoid spurious
1810 // AddBlankLine calls().
1811 if (getTok().is(AsmToken::EndOfStatement)) {
1812 Lex();
1813 }
1814
Maya Madhavanec1efe42018-09-20 05:11:42 +00001815 getTargetParser().doBeforeLabelEmit(Sym);
1816
Daniel Dunbare73b2672009-08-26 22:13:22 +00001817 // Emit the label.
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00001818 if (!getTargetParser().isParsingInlineAsm())
Rafael Espindolabe991572017-02-10 15:13:12 +00001819 Out.EmitLabel(Sym, IDLoc);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001820
Kevin Enderbye7739d42011-12-09 18:09:40 +00001821 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001822 // info to make a dwarf label entry for this label if needed.
Paul Robinson938d9a02018-03-22 15:48:01 +00001823 if (enabledGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001824 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1825 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001826
Tim Northover1744d0a2013-10-25 12:49:50 +00001827 getTargetParser().onLabelParsed(Sym);
1828
Eli Friedman0f4871d2012-10-22 23:58:19 +00001829 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001830 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001831
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001832 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001833 if (!getTargetParser().equalIsAsmAssignment())
1834 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001835 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001836 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001837
Nirav Dave7fd992a2018-08-16 16:31:14 +00001838 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001839
1840 default: // Normal instruction or directive.
1841 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001842 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001843
1844 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001845 if (areMacrosEnabled())
Rafael Espindola22c38a02018-02-14 16:34:27 +00001846 if (const MCAsmMacro *M = getContext().lookupMacro(IDVal)) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001847 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001848 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001849
Michael J. Spencer530ce852010-10-09 11:00:50 +00001850 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001851
Eli Bendersky17233942013-01-15 22:59:42 +00001852 // Directives start with "."
Ana Pazos353f67a2018-08-25 01:34:32 +00001853 if (IDVal.startswith(".") && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001854 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001855 //
Eli Bendersky17233942013-01-15 22:59:42 +00001856 // 1. The target-specific assembly parser. Some directives are target
1857 // specific or may potentially behave differently on certain targets.
1858 // 2. Asm parser extensions. For example, platform-specific parsers
1859 // (like the ELF parser) register themselves as extensions.
1860 // 3. The generic directive parser implemented by this class. These are
1861 // all the directives that behave in a target and platform independent
1862 // manner, or at least have a default behavior that's shared between
1863 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001864
Oliver Stannard21718282016-07-26 14:19:47 +00001865 getTargetParser().flushPendingInstructions(getStreamer());
1866
Nirav Dave2364748a2016-09-16 18:30:20 +00001867 SMLoc StartTokLoc = getTok().getLoc();
1868 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1869
1870 if (hasPendingError())
1871 return true;
1872 // Currently the return value should be true if we are
1873 // uninterested but as this is at odds with the standard parsing
1874 // convention (return true = error) we have instances of a parsed
1875 // directive that fails returning true as an error. Catch these
1876 // cases as best as possible errors here.
1877 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1878 return true;
1879 // Return if we did some parsing or believe we succeeded.
1880 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001881 return false;
1882
Alp Tokercb402912014-01-24 17:20:08 +00001883 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001884 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001885 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1886 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001887 if (Handler.first)
1888 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1889
1890 // Finally, if no one else is interested in this directive, it must be
1891 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001892 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001893 default:
1894 break;
1895 case DK_SET:
1896 case DK_EQU:
1897 return parseDirectiveSet(IDVal, true);
1898 case DK_EQUIV:
1899 return parseDirectiveSet(IDVal, false);
1900 case DK_ASCII:
1901 return parseDirectiveAscii(IDVal, false);
1902 case DK_ASCIZ:
1903 case DK_STRING:
1904 return parseDirectiveAscii(IDVal, true);
1905 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001906 case DK_DC_B:
1907 return parseDirectiveValue(IDVal, 1);
1908 case DK_DC:
1909 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001910 case DK_SHORT:
1911 case DK_VALUE:
1912 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001913 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001914 case DK_LONG:
1915 case DK_INT:
1916 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001917 case DK_DC_L:
1918 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001919 case DK_QUAD:
1920 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001921 return parseDirectiveValue(IDVal, 8);
1922 case DK_DC_A:
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001923 return parseDirectiveValue(
1924 IDVal, getContext().getAsmInfo()->getCodePointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001925 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001926 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001927 case DK_SINGLE:
1928 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001929 case DK_DC_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001930 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
Jim Grosbach4b905842013-09-20 23:08:21 +00001931 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001932 case DK_DC_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001933 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
Jim Grosbach4b905842013-09-20 23:08:21 +00001934 case DK_ALIGN: {
1935 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1936 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1937 }
1938 case DK_ALIGN32: {
1939 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1940 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1941 }
1942 case DK_BALIGN:
1943 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1944 case DK_BALIGNW:
1945 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1946 case DK_BALIGNL:
1947 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1948 case DK_P2ALIGN:
1949 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1950 case DK_P2ALIGNW:
1951 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1952 case DK_P2ALIGNL:
1953 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1954 case DK_ORG:
1955 return parseDirectiveOrg();
1956 case DK_FILL:
1957 return parseDirectiveFill();
1958 case DK_ZERO:
1959 return parseDirectiveZero();
1960 case DK_EXTERN:
1961 eatToEndOfStatement(); // .extern is the default, ignore it.
1962 return false;
1963 case DK_GLOBL:
1964 case DK_GLOBAL:
1965 return parseDirectiveSymbolAttribute(MCSA_Global);
1966 case DK_LAZY_REFERENCE:
1967 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1968 case DK_NO_DEAD_STRIP:
1969 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1970 case DK_SYMBOL_RESOLVER:
1971 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1972 case DK_PRIVATE_EXTERN:
1973 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1974 case DK_REFERENCE:
1975 return parseDirectiveSymbolAttribute(MCSA_Reference);
1976 case DK_WEAK_DEFINITION:
1977 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1978 case DK_WEAK_REFERENCE:
1979 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1980 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1981 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1982 case DK_COMM:
1983 case DK_COMMON:
1984 return parseDirectiveComm(/*IsLocal=*/false);
1985 case DK_LCOMM:
1986 return parseDirectiveComm(/*IsLocal=*/true);
1987 case DK_ABORT:
1988 return parseDirectiveAbort();
1989 case DK_INCLUDE:
1990 return parseDirectiveInclude();
1991 case DK_INCBIN:
1992 return parseDirectiveIncbin();
1993 case DK_CODE16:
1994 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001995 return TokError(Twine(IDVal) +
1996 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001997 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001998 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001999 case DK_IRP:
2000 return parseDirectiveIrp(IDLoc);
2001 case DK_IRPC:
2002 return parseDirectiveIrpc(IDLoc);
2003 case DK_ENDR:
2004 return parseDirectiveEndr(IDLoc);
2005 case DK_BUNDLE_ALIGN_MODE:
2006 return parseDirectiveBundleAlignMode();
2007 case DK_BUNDLE_LOCK:
2008 return parseDirectiveBundleLock();
2009 case DK_BUNDLE_UNLOCK:
2010 return parseDirectiveBundleUnlock();
2011 case DK_SLEB128:
2012 return parseDirectiveLEB128(true);
2013 case DK_ULEB128:
2014 return parseDirectiveLEB128(false);
2015 case DK_SPACE:
2016 case DK_SKIP:
2017 return parseDirectiveSpace(IDVal);
2018 case DK_FILE:
2019 return parseDirectiveFile(IDLoc);
2020 case DK_LINE:
2021 return parseDirectiveLine();
2022 case DK_LOC:
2023 return parseDirectiveLoc();
2024 case DK_STABS:
2025 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002026 case DK_CV_FILE:
2027 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00002028 case DK_CV_FUNC_ID:
2029 return parseDirectiveCVFuncId();
2030 case DK_CV_INLINE_SITE_ID:
2031 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002032 case DK_CV_LOC:
2033 return parseDirectiveCVLoc();
2034 case DK_CV_LINETABLE:
2035 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00002036 case DK_CV_INLINE_LINETABLE:
2037 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00002038 case DK_CV_DEF_RANGE:
2039 return parseDirectiveCVDefRange();
Reid Kleckner06d02d02018-09-07 21:30:52 +00002040 case DK_CV_STRING:
2041 return parseDirectiveCVString();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002042 case DK_CV_STRINGTABLE:
2043 return parseDirectiveCVStringTable();
2044 case DK_CV_FILECHECKSUMS:
2045 return parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00002046 case DK_CV_FILECHECKSUM_OFFSET:
2047 return parseDirectiveCVFileChecksumOffset();
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00002048 case DK_CV_FPO_DATA:
2049 return parseDirectiveCVFPOData();
Jim Grosbach4b905842013-09-20 23:08:21 +00002050 case DK_CFI_SECTIONS:
2051 return parseDirectiveCFISections();
2052 case DK_CFI_STARTPROC:
2053 return parseDirectiveCFIStartProc();
2054 case DK_CFI_ENDPROC:
2055 return parseDirectiveCFIEndProc();
2056 case DK_CFI_DEF_CFA:
2057 return parseDirectiveCFIDefCfa(IDLoc);
2058 case DK_CFI_DEF_CFA_OFFSET:
2059 return parseDirectiveCFIDefCfaOffset();
2060 case DK_CFI_ADJUST_CFA_OFFSET:
2061 return parseDirectiveCFIAdjustCfaOffset();
2062 case DK_CFI_DEF_CFA_REGISTER:
2063 return parseDirectiveCFIDefCfaRegister(IDLoc);
2064 case DK_CFI_OFFSET:
2065 return parseDirectiveCFIOffset(IDLoc);
2066 case DK_CFI_REL_OFFSET:
2067 return parseDirectiveCFIRelOffset(IDLoc);
2068 case DK_CFI_PERSONALITY:
2069 return parseDirectiveCFIPersonalityOrLsda(true);
2070 case DK_CFI_LSDA:
2071 return parseDirectiveCFIPersonalityOrLsda(false);
2072 case DK_CFI_REMEMBER_STATE:
2073 return parseDirectiveCFIRememberState();
2074 case DK_CFI_RESTORE_STATE:
2075 return parseDirectiveCFIRestoreState();
2076 case DK_CFI_SAME_VALUE:
2077 return parseDirectiveCFISameValue(IDLoc);
2078 case DK_CFI_RESTORE:
2079 return parseDirectiveCFIRestore(IDLoc);
2080 case DK_CFI_ESCAPE:
2081 return parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00002082 case DK_CFI_RETURN_COLUMN:
2083 return parseDirectiveCFIReturnColumn(IDLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +00002084 case DK_CFI_SIGNAL_FRAME:
2085 return parseDirectiveCFISignalFrame();
2086 case DK_CFI_UNDEFINED:
2087 return parseDirectiveCFIUndefined(IDLoc);
2088 case DK_CFI_REGISTER:
2089 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00002090 case DK_CFI_WINDOW_SAVE:
2091 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00002092 case DK_MACROS_ON:
2093 case DK_MACROS_OFF:
2094 return parseDirectiveMacrosOnOff(IDVal);
2095 case DK_MACRO:
2096 return parseDirectiveMacro(IDLoc);
Michael Zuckerman56704612017-05-01 13:20:12 +00002097 case DK_ALTMACRO:
2098 case DK_NOALTMACRO:
2099 return parseDirectiveAltmacro(IDVal);
Nico Weber155dccd12014-07-24 17:08:39 +00002100 case DK_EXITM:
2101 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00002102 case DK_ENDM:
2103 case DK_ENDMACRO:
2104 return parseDirectiveEndMacro(IDVal);
2105 case DK_PURGEM:
2106 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00002107 case DK_END:
2108 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00002109 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00002110 return parseDirectiveError(IDLoc, false);
2111 case DK_ERROR:
2112 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00002113 case DK_WARNING:
2114 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002115 case DK_RELOC:
2116 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002117 case DK_DCB:
2118 case DK_DCB_W:
2119 return parseDirectiveDCB(IDVal, 2);
2120 case DK_DCB_B:
2121 return parseDirectiveDCB(IDVal, 1);
2122 case DK_DCB_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002123 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002124 case DK_DCB_L:
2125 return parseDirectiveDCB(IDVal, 4);
2126 case DK_DCB_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002127 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
Petr Hosek731bb9c2016-08-23 21:34:53 +00002128 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002129 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00002130 return TokError(Twine(IDVal) +
2131 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00002132 case DK_DS:
2133 case DK_DS_W:
2134 return parseDirectiveDS(IDVal, 2);
2135 case DK_DS_B:
2136 return parseDirectiveDS(IDVal, 1);
2137 case DK_DS_D:
2138 return parseDirectiveDS(IDVal, 8);
2139 case DK_DS_L:
2140 case DK_DS_S:
2141 return parseDirectiveDS(IDVal, 4);
2142 case DK_DS_P:
2143 case DK_DS_X:
2144 return parseDirectiveDS(IDVal, 12);
Coby Tayree01e53202017-10-02 14:36:31 +00002145 case DK_PRINT:
2146 return parseDirectivePrint(IDLoc);
Peter Collingbourne3e227332018-07-17 22:17:18 +00002147 case DK_ADDRSIG:
2148 return parseDirectiveAddrsig();
2149 case DK_ADDRSIG_SYM:
2150 return parseDirectiveAddrsigSym();
Eli Friedman20b02642010-07-19 04:17:25 +00002151 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002152
Jim Grosbach758e0cc2012-05-01 18:38:27 +00002153 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00002154 }
Chris Lattner36e02122009-06-21 20:54:55 +00002155
Chad Rosierc7f552c2013-02-12 21:33:51 +00002156 // __asm _emit or __asm __emit
2157 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
2158 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002159 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00002160
2161 // __asm align
2162 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002163 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00002164
Coby Tayree3847be92017-04-04 17:57:23 +00002165 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
Michael Zuckerman02ecd432015-12-13 17:07:23 +00002166 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00002167 if (checkForValidSection())
2168 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00002169
Chris Lattner7cbfa442010-05-19 23:34:33 +00002170 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00002171 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00002172 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00002173 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
2174 Info.ParsedOperands);
2175 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00002176
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002177 // Dump the parsed representation, if requested.
2178 if (getShowParsedOperands()) {
2179 SmallString<256> Str;
2180 raw_svector_ostream OS(Str);
2181 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002182 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002183 if (i != 0)
2184 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002185 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002186 }
2187 OS << "]";
2188
Jim Grosbach4b905842013-09-20 23:08:21 +00002189 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002190 }
2191
Nirav Dave2364748a2016-09-16 18:30:20 +00002192 // Fail even if ParseInstruction erroneously returns false.
2193 if (hasPendingError() || ParseHadError)
2194 return true;
2195
Oliver Stannard8b273082014-06-19 15:52:37 +00002196 // If we are generating dwarf for the current section then generate a .loc
2197 // directive for the instruction.
Paul Robinson938d9a02018-03-22 15:48:01 +00002198 if (!ParseHadError && enabledGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002199 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002200 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002201 unsigned Line;
2202 if (ActiveMacros.empty())
2203 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2204 else
Frederic Riss16238d92015-06-25 21:57:33 +00002205 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2206 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002207
Eli Bendersky88024712013-01-16 19:32:36 +00002208 // If we previously parsed a cpp hash file line comment then make sure the
2209 // current Dwarf File is for the CppHashFilename if not then emit the
2210 // Dwarf File table for it and adjust the line number for the .loc.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00002211 if (!CppHashInfo.Filename.empty()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002212 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002213 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002214 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002215
Graydon Hoare54fe2082018-04-07 00:44:02 +00002216 unsigned CppHashLocLineNo =
2217 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Tim Northoverc0bef992016-04-13 19:46:54 +00002218 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002219 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002220
Jim Grosbach4b905842013-09-20 23:08:21 +00002221 getStreamer().EmitDwarfLocDirective(
2222 getContext().getGenDwarfFileNumber(), Line, 0,
2223 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2224 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002225 }
2226
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002227 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002228 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002229 uint64_t ErrorInfo;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00002230 if (getTargetParser().MatchAndEmitInstruction(
2231 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2232 getTargetParser().isParsingInlineAsm()))
Nirav Dave2364748a2016-09-16 18:30:20 +00002233 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002234 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002235 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002236}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002237
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002238// Parse and erase curly braces marking block start/end
Sam Cleggf009da22018-04-19 22:00:53 +00002239bool
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002240AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2241 // Identify curly brace marking block start/end
2242 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2243 return false;
2244
2245 SMLoc StartLoc = Lexer.getLoc();
2246 Lex(); // Eat the brace
2247 if (Lexer.is(AsmToken::EndOfStatement))
2248 Lex(); // Eat EndOfStatement following the brace
2249
2250 // Erase the block start/end brace from the output asm string
2251 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2252 StartLoc.getPointer());
2253 return true;
2254}
2255
Jim Grosbach4b905842013-09-20 23:08:21 +00002256/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002257/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002258bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002259 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002260 // Lexer only ever emits HashDirective if it fully formed if it's
2261 // done the checking already so this is an internal error.
2262 assert(getTok().is(AsmToken::Integer) &&
2263 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002264 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002265 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002266 assert(getTok().is(AsmToken::String) &&
2267 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002268 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002269 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002270
Kevin Enderby72553612011-09-13 23:45:18 +00002271 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002272 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002273
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002274 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002275 CppHashInfo.Loc = L;
2276 CppHashInfo.Filename = Filename;
2277 CppHashInfo.LineNumber = LineNumber;
2278 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002279 return false;
2280}
2281
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002282/// will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002283/// for the Filename and LineNo if any in the diagnostic.
2284void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002285 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002286 raw_ostream &OS = errs();
2287
2288 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002289 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002290 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2291 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002292 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002293
Jim Grosbach4b905842013-09-20 23:08:21 +00002294 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002295 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002296 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2297 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2298 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002299 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2300 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002301 }
2302
Eric Christophera7c32732012-12-18 00:30:54 +00002303 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002304 // manager changed or buffer changed (like in a nested include) then just
2305 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002306 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002307 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002308 if (Parser->SavedDiagHandler)
2309 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2310 else
Craig Topper353eda42014-04-24 06:44:33 +00002311 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002312 return;
2313 }
2314
Eric Christophera7c32732012-12-18 00:30:54 +00002315 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002316 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2317 // for the diagnostic.
2318 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002319
2320 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2321 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002322 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002323 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002324 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002325
Jim Grosbach4b905842013-09-20 23:08:21 +00002326 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2327 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002328 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002329
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002330 if (Parser->SavedDiagHandler)
2331 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2332 else
Craig Topper353eda42014-04-24 06:44:33 +00002333 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002334}
2335
Rafael Espindola2c064482012-08-21 18:29:30 +00002336// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2337// difference being that that function accepts '@' as part of identifiers and
2338// we can't do that. AsmLexer.cpp should probably be changed to handle
2339// '@' as a special case when needed.
2340static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002341 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2342 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002343}
2344
Rafael Espindola34b9c512012-06-03 23:57:14 +00002345bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002346 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002347 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002348 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002349 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002350 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002351 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002352 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002353
Preston Gurd05500642012-09-19 20:36:12 +00002354 // A macro without parameters is handled differently on Darwin:
2355 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002356 while (!Body.empty()) {
2357 // Scan for the next substitution.
2358 std::size_t End = Body.size(), Pos = 0;
2359 for (; Pos != End; ++Pos) {
2360 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002361 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002362 // This macro has no parameters, look for $0, $1, etc.
2363 if (Body[Pos] != '$' || Pos + 1 == End)
2364 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002365
Rafael Espindola1134ab232011-06-05 02:43:45 +00002366 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002367 if (Next == '$' || Next == 'n' ||
2368 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002369 break;
2370 } else {
2371 // This macro has parameters, look for \foo, \bar, etc.
2372 if (Body[Pos] == '\\' && Pos + 1 != End)
2373 break;
2374 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002375 }
2376
2377 // Add the prefix.
2378 OS << Body.slice(0, Pos);
2379
2380 // Check if we reached the end.
2381 if (Pos == End)
2382 break;
2383
Benjamin Kramer513e7442014-02-20 13:36:32 +00002384 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002385 switch (Body[Pos + 1]) {
2386 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002387 case '$':
2388 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002389 break;
2390
Jim Grosbach4b905842013-09-20 23:08:21 +00002391 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002392 case 'n':
2393 OS << A.size();
2394 break;
2395
Jim Grosbach4b905842013-09-20 23:08:21 +00002396 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002397 default: {
2398 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002399 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002400 if (Index >= A.size())
2401 break;
2402
2403 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002404 for (const AsmToken &Token : A[Index])
2405 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002406 break;
2407 }
2408 }
2409 Pos += 2;
2410 } else {
2411 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002412
2413 // Check for the \@ pseudo-variable.
2414 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002415 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002416 else
2417 while (isIdentifierChar(Body[I]) && I + 1 != End)
2418 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002419
Jim Grosbach4b905842013-09-20 23:08:21 +00002420 const char *Begin = Body.data() + Pos + 1;
2421 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002422 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002423
Toma Tabacu217116e2015-04-27 10:50:29 +00002424 if (Argument == "@") {
2425 OS << NumOfMacroInstantiations;
2426 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002427 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002428 for (; Index < NParameters; ++Index)
2429 if (Parameters[Index].Name == Argument)
2430 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002431
Toma Tabacu217116e2015-04-27 10:50:29 +00002432 if (Index == NParameters) {
2433 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2434 Pos += 3;
2435 else {
2436 OS << '\\' << Argument;
2437 Pos = I;
2438 }
2439 } else {
2440 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002441 for (const AsmToken &Token : A[Index])
Michael Zuckerman56704612017-05-01 13:20:12 +00002442 // For altmacro mode, you can write '%expr'.
2443 // The prefix '%' evaluates the expression 'expr'
Craig Topper3da977b2018-09-25 19:37:35 +00002444 // and uses the result as a string (e.g. replace %(1+2) with the
2445 // string "3").
Michael Zuckerman56704612017-05-01 13:20:12 +00002446 // Here, we identify the integer token which is the result of the
Craig Topper3da977b2018-09-25 19:37:35 +00002447 // absolute expression evaluation and replace it with its string
2448 // representation.
Craig Topperc81aff72018-09-25 20:55:55 +00002449 if (AltMacroMode && Token.getString().front() == '%' &&
Craig Topper3da977b2018-09-25 19:37:35 +00002450 Token.is(AsmToken::Integer))
Michael Zuckerman56704612017-05-01 13:20:12 +00002451 // Emit an integer value to the buffer.
2452 OS << Token.getIntVal();
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002453 // Only Token that was validated as a string and begins with '<'
2454 // is considered altMacroString!!!
Craig Topperc81aff72018-09-25 20:55:55 +00002455 else if (AltMacroMode && Token.getString().front() == '<' &&
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002456 Token.is(AsmToken::String)) {
Craig Topperd2aab832018-09-25 20:13:55 +00002457 OS << altMacroString(Token.getStringContents());
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002458 }
Toma Tabacu217116e2015-04-27 10:50:29 +00002459 // We expect no quotes around the string's contents when
2460 // parsing for varargs.
Michael Zuckerman56704612017-05-01 13:20:12 +00002461 else if (Token.isNot(AsmToken::String) || VarargParameter)
Craig Topper84008482015-10-10 05:38:14 +00002462 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002463 else
Craig Topper84008482015-10-10 05:38:14 +00002464 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002465
2466 Pos += 1 + Argument.size();
2467 }
Preston Gurd05500642012-09-19 20:36:12 +00002468 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002469 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002470 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002471 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002472 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002473
Rafael Espindola1134ab232011-06-05 02:43:45 +00002474 return false;
2475}
Daniel Dunbar43235712010-07-18 18:54:11 +00002476
Nico Weber2a8f9222014-07-24 16:29:04 +00002477MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002478 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002479 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002480 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002481
Jim Grosbach4b905842013-09-20 23:08:21 +00002482static bool isOperator(AsmToken::TokenKind kind) {
2483 switch (kind) {
2484 default:
2485 return false;
2486 case AsmToken::Plus:
2487 case AsmToken::Minus:
2488 case AsmToken::Tilde:
2489 case AsmToken::Slash:
2490 case AsmToken::Star:
2491 case AsmToken::Dot:
2492 case AsmToken::Equal:
2493 case AsmToken::EqualEqual:
2494 case AsmToken::Pipe:
2495 case AsmToken::PipePipe:
2496 case AsmToken::Caret:
2497 case AsmToken::Amp:
2498 case AsmToken::AmpAmp:
2499 case AsmToken::Exclaim:
2500 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002501 case AsmToken::Less:
2502 case AsmToken::LessEqual:
2503 case AsmToken::LessLess:
2504 case AsmToken::LessGreater:
2505 case AsmToken::Greater:
2506 case AsmToken::GreaterEqual:
2507 case AsmToken::GreaterGreater:
2508 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002509 }
2510}
2511
David Majnemer16252452014-01-29 00:07:39 +00002512namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002513
David Majnemer16252452014-01-29 00:07:39 +00002514class AsmLexerSkipSpaceRAII {
2515public:
2516 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2517 Lexer.setSkipSpace(SkipSpace);
2518 }
2519
2520 ~AsmLexerSkipSpaceRAII() {
2521 Lexer.setSkipSpace(true);
2522 }
2523
2524private:
2525 AsmLexer &Lexer;
2526};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002527
2528} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002529
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002530bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2531
2532 if (Vararg) {
2533 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2534 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002535 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002536 }
2537 return false;
2538 }
2539
Rafael Espindola768b41c2012-06-15 14:02:34 +00002540 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002541
David Majnemer16252452014-01-29 00:07:39 +00002542 // Darwin doesn't use spaces to delmit arguments.
2543 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002544
Scott Egertona1fa68a2016-02-11 13:48:49 +00002545 bool SpaceEaten;
2546
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002547 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002548 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002549 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002550 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002551
Scott Egertona1fa68a2016-02-11 13:48:49 +00002552 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002553
Scott Egertona1fa68a2016-02-11 13:48:49 +00002554 if (Lexer.is(AsmToken::Comma))
2555 break;
2556
2557 if (Lexer.is(AsmToken::Space)) {
2558 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002559 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002560 }
Preston Gurd05500642012-09-19 20:36:12 +00002561
2562 // Spaces can delimit parameters, but could also be part an expression.
2563 // If the token after a space is an operator, add the token and the next
2564 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002565 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002566 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002567 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002568 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002569
Scott Egertona1fa68a2016-02-11 13:48:49 +00002570 // Whitespace after an operator can be ignored.
2571 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002572 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002573
2574 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002575 }
2576 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002577 if (SpaceEaten)
2578 break;
Preston Gurd05500642012-09-19 20:36:12 +00002579 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002580
Jim Grosbach4b905842013-09-20 23:08:21 +00002581 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002582 // to be able to fill in the remaining default parameter values
2583 if (Lexer.is(AsmToken::EndOfStatement))
2584 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002585
2586 // Adjust the current parentheses level.
2587 if (Lexer.is(AsmToken::LParen))
2588 ++ParenLevel;
2589 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2590 --ParenLevel;
2591
2592 // Append the token to the current argument list.
2593 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002594 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002595 }
Preston Gurd05500642012-09-19 20:36:12 +00002596
Rafael Espindola768b41c2012-06-15 14:02:34 +00002597 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002598 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002599 return false;
2600}
2601
2602// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002603bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002604 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002605 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002606 bool NamedParametersFound = false;
2607 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002608
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002609 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002610 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002611
Rafael Espindola768b41c2012-06-15 14:02:34 +00002612 // Parse two kinds of macro invocations:
2613 // - macros defined without any parameters accept an arbitrary number of them
2614 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002615 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002616 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2617 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002618 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002619 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002620
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002621 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002622 if (parseIdentifier(FA.Name))
2623 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002624
Nirav Dave2364748a2016-09-16 18:30:20 +00002625 if (Lexer.isNot(AsmToken::Equal))
2626 return TokError("expected '=' after formal parameter identifier");
2627
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002628 Lex();
2629
2630 NamedParametersFound = true;
2631 }
Michael Zuckerman56704612017-05-01 13:20:12 +00002632 bool Vararg = HasVararg && Parameter == (NParameters - 1);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002633
Nirav Dave2364748a2016-09-16 18:30:20 +00002634 if (NamedParametersFound && FA.Name.empty())
2635 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002636
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002637 SMLoc StrLoc = Lexer.getLoc();
2638 SMLoc EndLoc;
Craig Topperc81aff72018-09-25 20:55:55 +00002639 if (AltMacroMode && Lexer.is(AsmToken::Percent)) {
Craig Topper3da977b2018-09-25 19:37:35 +00002640 const MCExpr *AbsoluteExp;
2641 int64_t Value;
2642 /// Eat '%'
2643 Lex();
2644 if (parseExpression(AbsoluteExp, EndLoc))
2645 return false;
2646 if (!AbsoluteExp->evaluateAsAbsolute(Value,
2647 getStreamer().getAssemblerPtr()))
2648 return Error(StrLoc, "expected absolute expression");
2649 const char *StrChar = StrLoc.getPointer();
2650 const char *EndChar = EndLoc.getPointer();
2651 AsmToken newToken(AsmToken::Integer,
2652 StringRef(StrChar, EndChar - StrChar), Value);
2653 FA.Value.push_back(newToken);
Craig Topperc81aff72018-09-25 20:55:55 +00002654 } else if (AltMacroMode && Lexer.is(AsmToken::Less) &&
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002655 isAltmacroString(StrLoc, EndLoc)) {
Craig Topper3da977b2018-09-25 19:37:35 +00002656 const char *StrChar = StrLoc.getPointer();
2657 const char *EndChar = EndLoc.getPointer();
2658 jumpToLoc(EndLoc, CurBuffer);
2659 /// Eat from '<' to '>'
2660 Lex();
2661 AsmToken newToken(AsmToken::String,
2662 StringRef(StrChar, EndChar - StrChar));
2663 FA.Value.push_back(newToken);
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002664 } else if(parseMacroArgument(FA.Value, Vararg))
Craig Topper3da977b2018-09-25 19:37:35 +00002665 return true;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002666
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002667 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002668 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002669 unsigned FAI = 0;
2670 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002671 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002672 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002673
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002674 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002675 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002676 return Error(IDLoc, "parameter named '" + FA.Name +
2677 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002678 }
2679 PI = FAI;
2680 }
2681
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002682 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002683 if (A.size() <= PI)
2684 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002685 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002686
2687 if (FALocs.size() <= PI)
2688 FALocs.resize(PI + 1);
2689
2690 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002691 }
Jim Grosbach206661622012-07-30 22:44:17 +00002692
Preston Gurd242ed3152012-09-19 20:29:04 +00002693 // At the end of the statement, fill in remaining arguments that have
2694 // default values. If there aren't any, then the next argument is
2695 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002696 if (Lexer.is(AsmToken::EndOfStatement)) {
2697 bool Failure = false;
2698 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2699 if (A[FAI].empty()) {
2700 if (M->Parameters[FAI].Required) {
2701 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2702 "missing value for required parameter "
2703 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2704 Failure = true;
2705 }
2706
2707 if (!M->Parameters[FAI].Value.empty())
2708 A[FAI] = M->Parameters[FAI].Value;
2709 }
2710 }
2711 return Failure;
2712 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002713
2714 if (Lexer.is(AsmToken::Comma))
2715 Lex();
2716 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002717
2718 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002719}
2720
Jim Grosbach4b905842013-09-20 23:08:21 +00002721bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002722 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2723 // eliminate this, although we should protect against infinite loops.
2724 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2725 if (ActiveMacros.size() == MaxNestingDepth) {
2726 std::ostringstream MaxNestingDepthError;
2727 MaxNestingDepthError << "macros cannot be nested more than "
2728 << MaxNestingDepth << " levels deep."
2729 << " Use -asm-macro-max-nesting-depth to increase "
2730 "this limit.";
2731 return TokError(MaxNestingDepthError.str());
2732 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002733
Eli Bendersky38274122013-01-14 23:22:36 +00002734 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002735 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002736 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002737
Rafael Espindola1134ab232011-06-05 02:43:45 +00002738 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2739 // to hold the macro body with substitutions.
2740 SmallString<256> Buf;
2741 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002742 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002743
Toma Tabacu217116e2015-04-27 10:50:29 +00002744 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002745 return true;
2746
Eli Bendersky38274122013-01-14 23:22:36 +00002747 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002748 // instantiation.
2749 OS << ".endmacro\n";
2750
Rafael Espindola3560ff22014-08-27 20:03:13 +00002751 std::unique_ptr<MemoryBuffer> Instantiation =
2752 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002753
Daniel Dunbar43235712010-07-18 18:54:11 +00002754 // Create the macro instantiation object and add to the current macro
2755 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002756 MacroInstantiation *MI = new MacroInstantiation(
2757 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002758 ActiveMacros.push_back(MI);
2759
Toma Tabacu217116e2015-04-27 10:50:29 +00002760 ++NumOfMacroInstantiations;
2761
Daniel Dunbar43235712010-07-18 18:54:11 +00002762 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002763 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002764 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002765 Lex();
2766
2767 return false;
2768}
2769
Jim Grosbach4b905842013-09-20 23:08:21 +00002770void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002771 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002772 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002773 Lex();
2774
2775 // Pop the instantiation entry.
2776 delete ActiveMacros.back();
2777 ActiveMacros.pop_back();
2778}
2779
Jim Grosbach4b905842013-09-20 23:08:21 +00002780bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Nirav Dave7fd992a2018-08-16 16:31:14 +00002781 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002782 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002783 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002784 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
Nirav Dave7fd992a2018-08-16 16:31:14 +00002785 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002786 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002787
Pete Cooper80d21cb2015-06-22 19:35:57 +00002788 if (!Sym) {
2789 // In the case where we parse an expression starting with a '.', we will
2790 // not generate an error, nor will we create a symbol. In this case we
2791 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002792 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002793 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002794
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002795 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002796 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002797 if (NoDeadStrip)
2798 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2799
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002800 return false;
2801}
2802
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002803/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002804/// ::= identifier
2805/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002806bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002807 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002808 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2809 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002810 // handle this as a context dependent token, instead we detect adjacent tokens
2811 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002812 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2813 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002814
Hans Wennborgce69d772013-10-18 20:46:28 +00002815 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002816
2817 AsmToken Buf[1];
2818 Lexer.peekTokens(Buf, false);
2819
2820 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002821 return true;
2822
Hans Wennborgce69d772013-10-18 20:46:28 +00002823 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002824 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002825 return true;
2826
Nirav Daved0463322016-10-12 13:58:07 +00002827 // eat $ or @
2828 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002829 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002830 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002831 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002832 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002833 return false;
2834 }
2835
Jim Grosbach4b905842013-09-20 23:08:21 +00002836 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002837 return true;
2838
Sean Callanan936b0d32010-01-19 21:44:56 +00002839 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002840
Sean Callanan686ed8d2010-01-19 20:22:31 +00002841 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002842
2843 return false;
2844}
2845
Jim Grosbach4b905842013-09-20 23:08:21 +00002846/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002847/// ::= .equ identifier ',' expression
2848/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002849/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002850bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002851 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002852 if (check(parseIdentifier(Name), "expected identifier") ||
2853 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2854 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2855 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002856}
2857
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002858bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002859 if (check(getTok().isNot(AsmToken::String), "expected string"))
2860 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002861
2862 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002863 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002864 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2865 if (Str[i] != '\\') {
2866 Data += Str[i];
2867 continue;
2868 }
2869
2870 // Recognize escaped characters. Note that this escape semantics currently
2871 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2872 ++i;
2873 if (i == e)
2874 return TokError("unexpected backslash at end of string");
2875
2876 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002877 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002878 // Consume up to three octal characters.
2879 unsigned Value = Str[i] - '0';
2880
Jim Grosbach4b905842013-09-20 23:08:21 +00002881 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002882 ++i;
2883 Value = Value * 8 + (Str[i] - '0');
2884
Jim Grosbach4b905842013-09-20 23:08:21 +00002885 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002886 ++i;
2887 Value = Value * 8 + (Str[i] - '0');
2888 }
2889 }
2890
2891 if (Value > 255)
2892 return TokError("invalid octal escape sequence (out of range)");
2893
Jim Grosbach4b905842013-09-20 23:08:21 +00002894 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002895 continue;
2896 }
2897
2898 // Otherwise recognize individual escapes.
2899 switch (Str[i]) {
2900 default:
2901 // Just reject invalid escape sequences for now.
2902 return TokError("invalid escape sequence (unrecognized character)");
2903
2904 case 'b': Data += '\b'; break;
2905 case 'f': Data += '\f'; break;
2906 case 'n': Data += '\n'; break;
2907 case 'r': Data += '\r'; break;
2908 case 't': Data += '\t'; break;
2909 case '"': Data += '"'; break;
2910 case '\\': Data += '\\'; break;
2911 }
2912 }
2913
Nirav Davea645433c2016-07-18 15:24:03 +00002914 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002915 return false;
2916}
2917
Jim Grosbach4b905842013-09-20 23:08:21 +00002918/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002919/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002920bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002921 auto parseOp = [&]() -> bool {
2922 std::string Data;
2923 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002924 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002925 getStreamer().EmitBytes(Data);
2926 if (ZeroTerminated)
2927 getStreamer().EmitBytes(StringRef("\0", 1));
2928 return false;
2929 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002930
Nirav Dave1a9044b2016-10-24 14:35:29 +00002931 if (parseMany(parseOp))
2932 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002933 return false;
2934}
2935
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002936/// parseDirectiveReloc
2937/// ::= .reloc expression , identifier [ , expression ]
2938bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2939 const MCExpr *Offset;
2940 const MCExpr *Expr = nullptr;
2941
2942 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00002943 int64_t OffsetValue;
2944 // We can only deal with constant expressions at the moment.
2945
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002946 if (parseExpression(Offset))
2947 return true;
2948
Nirav Dave6c0665e2018-04-30 19:22:40 +00002949 if (check(!Offset->evaluateAsAbsolute(OffsetValue,
2950 getStreamer().getAssemblerPtr()),
2951 OffsetLoc, "expression is not a constant value") ||
Nirav Davea645433c2016-07-18 15:24:03 +00002952 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2953 parseToken(AsmToken::Comma, "expected comma") ||
2954 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2955 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002956
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002957 SMLoc NameLoc = Lexer.getTok().getLoc();
2958 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002959 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002960
2961 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002962 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002963 SMLoc ExprLoc = Lexer.getLoc();
2964 if (parseExpression(Expr))
2965 return true;
2966
2967 MCValue Value;
2968 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2969 return Error(ExprLoc, "expression must be relocatable");
2970 }
2971
Nirav Davea645433c2016-07-18 15:24:03 +00002972 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002973 "unexpected token in .reloc directive"))
2974 return true;
2975
Peter Smith57f661b2018-06-06 09:40:06 +00002976 const MCTargetAsmParser &MCT = getTargetParser();
2977 const MCSubtargetInfo &STI = MCT.getSTI();
2978 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc, STI))
Nirav Dave1ab71992016-07-18 19:35:21 +00002979 return Error(NameLoc, "unknown relocation name");
2980
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002981 return false;
2982}
2983
Jim Grosbach4b905842013-09-20 23:08:21 +00002984/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002985/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002986bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2987 auto parseOp = [&]() -> bool {
2988 const MCExpr *Value;
2989 SMLoc ExprLoc = getLexer().getLoc();
2990 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002991 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002992 // Special case constant expressions to match code generator.
2993 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2994 assert(Size <= 8 && "Invalid size");
2995 uint64_t IntValue = MCE->getValue();
2996 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2997 return Error(ExprLoc, "out of range literal value");
2998 getStreamer().EmitIntValue(IntValue, Size);
2999 } else
3000 getStreamer().EmitValue(Value, Size, ExprLoc);
3001 return false;
3002 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00003003
Nirav Dave1a9044b2016-10-24 14:35:29 +00003004 if (parseMany(parseOp))
3005 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00003006 return false;
3007}
3008
Paul Robinson01954692018-04-11 15:14:05 +00003009static bool parseHexOcta(AsmParser &Asm, uint64_t &hi, uint64_t &lo) {
3010 if (Asm.getTok().isNot(AsmToken::Integer) &&
3011 Asm.getTok().isNot(AsmToken::BigNum))
3012 return Asm.TokError("unknown token in expression");
3013 SMLoc ExprLoc = Asm.getTok().getLoc();
3014 APInt IntValue = Asm.getTok().getAPIntVal();
3015 Asm.Lex();
3016 if (!IntValue.isIntN(128))
3017 return Asm.Error(ExprLoc, "out of range literal value");
3018 if (!IntValue.isIntN(64)) {
3019 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
3020 lo = IntValue.getLoBits(64).getZExtValue();
3021 } else {
3022 hi = 0;
3023 lo = IntValue.getZExtValue();
3024 }
3025 return false;
3026}
3027
David Woodhoused6de0d92014-02-01 16:20:59 +00003028/// ParseDirectiveOctaValue
3029/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003030
3031bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
3032 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00003033 if (checkForValidSection())
3034 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003035 uint64_t hi, lo;
Paul Robinson01954692018-04-11 15:14:05 +00003036 if (parseHexOcta(*this, hi, lo))
3037 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003038 if (MAI.isLittleEndian()) {
3039 getStreamer().EmitIntValue(lo, 8);
3040 getStreamer().EmitIntValue(hi, 8);
3041 } else {
3042 getStreamer().EmitIntValue(hi, 8);
3043 getStreamer().EmitIntValue(lo, 8);
3044 }
3045 return false;
3046 };
David Woodhoused6de0d92014-02-01 16:20:59 +00003047
Nirav Dave1a9044b2016-10-24 14:35:29 +00003048 if (parseMany(parseOp))
3049 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00003050 return false;
3051}
3052
Petr Hosek4cb08ce2016-09-23 19:25:15 +00003053bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
3054 // We don't truly support arithmetic on floating point expressions, so we
3055 // have to manually parse unary prefixes.
3056 bool IsNeg = false;
3057 if (getLexer().is(AsmToken::Minus)) {
3058 Lexer.Lex();
3059 IsNeg = true;
3060 } else if (getLexer().is(AsmToken::Plus))
3061 Lexer.Lex();
3062
3063 if (Lexer.is(AsmToken::Error))
3064 return TokError(Lexer.getErr());
3065 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
3066 Lexer.isNot(AsmToken::Identifier))
3067 return TokError("unexpected token in directive");
3068
3069 // Convert to an APFloat.
3070 APFloat Value(Semantics);
3071 StringRef IDVal = getTok().getString();
3072 if (getLexer().is(AsmToken::Identifier)) {
3073 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
3074 Value = APFloat::getInf(Semantics);
3075 else if (!IDVal.compare_lower("nan"))
3076 Value = APFloat::getNaN(Semantics, false, ~0);
3077 else
3078 return TokError("invalid floating point literal");
3079 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
3080 APFloat::opInvalidOp)
3081 return TokError("invalid floating point literal");
3082 if (IsNeg)
3083 Value.changeSign();
3084
3085 // Consume the numeric token.
3086 Lex();
3087
3088 Res = Value.bitcastToAPInt();
3089
3090 return false;
3091}
3092
Jim Grosbach4b905842013-09-20 23:08:21 +00003093/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00003094/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003095bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
3096 const fltSemantics &Semantics) {
3097 auto parseOp = [&]() -> bool {
3098 APInt AsInt;
3099 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00003100 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003101 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
3102 AsInt.getBitWidth() / 8);
3103 return false;
3104 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00003105
Nirav Dave1a9044b2016-10-24 14:35:29 +00003106 if (parseMany(parseOp))
3107 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00003108 return false;
3109}
3110
Jim Grosbach4b905842013-09-20 23:08:21 +00003111/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00003112/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003113bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003114 SMLoc NumBytesLoc = Lexer.getLoc();
3115 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003116 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00003117 return true;
3118
Rafael Espindolab91bac62010-10-05 19:42:57 +00003119 int64_t Val = 0;
3120 if (getLexer().is(AsmToken::Comma)) {
3121 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003122 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00003123 return true;
3124 }
3125
Nirav Davea645433c2016-07-18 15:24:03 +00003126 if (parseToken(AsmToken::EndOfStatement,
3127 "unexpected token in '.zero' directive"))
3128 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00003129 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00003130
3131 return false;
3132}
3133
Jim Grosbach4b905842013-09-20 23:08:21 +00003134/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00003135/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003136bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003137 SMLoc NumValuesLoc = Lexer.getLoc();
3138 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003139 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00003140 return true;
3141
Roman Divackye33098f2013-09-24 17:44:41 +00003142 int64_t FillSize = 1;
3143 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00003144
David Majnemer522d3db2014-02-01 07:19:38 +00003145 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003146
Nirav Dave1a9044b2016-10-24 14:35:29 +00003147 if (parseOptionalToken(AsmToken::Comma)) {
3148 SizeLoc = getTok().getLoc();
3149 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00003150 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003151 if (parseOptionalToken(AsmToken::Comma)) {
3152 ExprLoc = getTok().getLoc();
3153 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00003154 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00003155 }
3156 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003157 if (parseToken(AsmToken::EndOfStatement,
3158 "unexpected token in '.fill' directive"))
3159 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003160
David Majnemer522d3db2014-02-01 07:19:38 +00003161 if (FillSize < 0) {
3162 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00003163 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00003164 }
3165 if (FillSize > 8) {
3166 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
3167 FillSize = 8;
3168 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00003169
David Majnemer522d3db2014-02-01 07:19:38 +00003170 if (!isUInt<32>(FillExpr) && FillSize > 4)
3171 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
3172
Petr Hosek67a94a72016-05-28 05:57:48 +00003173 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00003174
3175 return false;
3176}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003177
Jim Grosbach4b905842013-09-20 23:08:21 +00003178/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003179/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003180bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00003181 const MCExpr *Offset;
Oliver Stannard268f42f2016-12-14 10:43:58 +00003182 SMLoc OffsetLoc = Lexer.getLoc();
Nirav Davef43cc9f2016-10-10 15:24:54 +00003183 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003184 return true;
3185
3186 // Parse optional fill expression.
3187 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003188 if (parseOptionalToken(AsmToken::Comma))
3189 if (parseAbsoluteExpression(FillExpr))
3190 return addErrorSuffix(" in '.org' directive");
3191 if (parseToken(AsmToken::EndOfStatement))
3192 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00003193
Oliver Stannard268f42f2016-12-14 10:43:58 +00003194 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003195 return false;
3196}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003197
Jim Grosbach4b905842013-09-20 23:08:21 +00003198/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003199/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00003200bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003201 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003202 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003203 SMLoc MaxBytesLoc;
3204 bool HasFillExpr = false;
3205 int64_t FillExpr = 0;
3206 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003207
3208 auto parseAlign = [&]() -> bool {
Coby Tayreed483a102017-08-02 17:36:10 +00003209 if (parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00003210 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003211 if (parseOptionalToken(AsmToken::Comma)) {
3212 // The fill expression can be omitted while specifying a maximum number of
3213 // alignment bytes, e.g:
3214 // .align 3,,4
3215 if (getTok().isNot(AsmToken::Comma)) {
3216 HasFillExpr = true;
3217 if (parseAbsoluteExpression(FillExpr))
3218 return true;
3219 }
3220 if (parseOptionalToken(AsmToken::Comma))
3221 if (parseTokenLoc(MaxBytesLoc) ||
3222 parseAbsoluteExpression(MaxBytesToFill))
3223 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003224 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003225 return parseToken(AsmToken::EndOfStatement);
3226 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003227
Coby Tayreed483a102017-08-02 17:36:10 +00003228 if (checkForValidSection())
3229 return addErrorSuffix(" in directive");
3230 // Ignore empty '.p2align' directives for GNU-as compatibility
3231 if (IsPow2 && (ValueSize == 1) && getTok().is(AsmToken::EndOfStatement)) {
3232 Warning(AlignmentLoc, "p2align directive with no operand(s) is ignored");
3233 return parseToken(AsmToken::EndOfStatement);
3234 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003235 if (parseAlign())
3236 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003237
Nirav Dave2364748a2016-09-16 18:30:20 +00003238 // Always emit an alignment here even if we thrown an error.
3239 bool ReturnVal = false;
3240
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003241 // Compute alignment in bytes.
3242 if (IsPow2) {
3243 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003244 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003245 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003246 Alignment = 31;
3247 }
3248
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003249 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003250 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003251 // Reject alignments that aren't either a power of two or zero,
3252 // for gas compatibility. Alignment of zero is silently rounded
3253 // up to one.
3254 if (Alignment == 0)
3255 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003256 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003257 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003258 }
3259
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003260 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003261 if (MaxBytesLoc.isValid()) {
3262 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003263 ReturnVal |= Error(MaxBytesLoc,
3264 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003265 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003266 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003267 }
3268
3269 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003270 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003271 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003272 MaxBytesToFill = 0;
3273 }
3274 }
3275
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003276 // Check whether we should use optimal code alignment for this .align
3277 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003278 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003279 assert(Section && "must have section to emit alignment");
3280 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003281 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3282 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003283 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003284 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003285 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003286 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3287 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003288 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003289
Nirav Dave2364748a2016-09-16 18:30:20 +00003290 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003291}
3292
Jim Grosbach4b905842013-09-20 23:08:21 +00003293/// parseDirectiveFile
Paul Robinson29f5f982018-01-09 23:31:48 +00003294/// ::= .file filename
Scott Linder16c7bda2018-02-23 23:01:06 +00003295/// ::= .file number [directory] filename [md5 checksum] [source source-text]
Jim Grosbach4b905842013-09-20 23:08:21 +00003296bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003297 // FIXME: I'm not sure what this is.
3298 int64_t FileNumber = -1;
Eli Bendersky17233942013-01-15 22:59:42 +00003299 if (getLexer().is(AsmToken::Integer)) {
3300 FileNumber = getTok().getIntVal();
3301 Lex();
3302
Paul Robinsonb271f312018-03-29 17:16:41 +00003303 if (FileNumber < 0)
3304 return TokError("negative file number");
Eli Bendersky17233942013-01-15 22:59:42 +00003305 }
3306
Paul Robinson37fbb922018-06-20 16:12:03 +00003307 std::string Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003308
3309 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003310 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003311 if (check(getTok().isNot(AsmToken::String),
3312 "unexpected token in '.file' directive") ||
3313 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003314 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003315
3316 StringRef Directory;
3317 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003318 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003319 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003320 if (check(FileNumber == -1,
3321 "explicit path specified, but no file number") ||
3322 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003323 return true;
3324 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003325 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003326 } else {
3327 Filename = Path;
3328 }
3329
Paul Robinson01954692018-04-11 15:14:05 +00003330 uint64_t MD5Hi, MD5Lo;
3331 bool HasMD5 = false;
Scott Linder16c7bda2018-02-23 23:01:06 +00003332
3333 Optional<StringRef> Source;
3334 bool HasSource = false;
3335 std::string SourceString;
3336
3337 while (!parseOptionalToken(AsmToken::EndOfStatement)) {
Paul Robinson29f5f982018-01-09 23:31:48 +00003338 StringRef Keyword;
3339 if (check(getTok().isNot(AsmToken::Identifier),
3340 "unexpected token in '.file' directive") ||
Scott Linder16c7bda2018-02-23 23:01:06 +00003341 parseIdentifier(Keyword))
Paul Robinson29f5f982018-01-09 23:31:48 +00003342 return true;
Scott Linder16c7bda2018-02-23 23:01:06 +00003343 if (Keyword == "md5") {
Paul Robinson01954692018-04-11 15:14:05 +00003344 HasMD5 = true;
Scott Linder16c7bda2018-02-23 23:01:06 +00003345 if (check(FileNumber == -1,
3346 "MD5 checksum specified, but no file number") ||
Paul Robinson01954692018-04-11 15:14:05 +00003347 parseHexOcta(*this, MD5Hi, MD5Lo))
Scott Linder16c7bda2018-02-23 23:01:06 +00003348 return true;
3349 } else if (Keyword == "source") {
3350 HasSource = true;
3351 if (check(FileNumber == -1,
3352 "source specified, but no file number") ||
3353 check(getTok().isNot(AsmToken::String),
3354 "unexpected token in '.file' directive") ||
3355 parseEscapedString(SourceString))
3356 return true;
3357 } else {
3358 return TokError("unexpected token in '.file' directive");
3359 }
Paul Robinson29f5f982018-01-09 23:31:48 +00003360 }
Eli Bendersky17233942013-01-15 22:59:42 +00003361
3362 if (FileNumber == -1)
3363 getStreamer().EmitFileDirective(Filename);
3364 else {
Brian Cain3e0ca572018-08-28 16:23:39 +00003365 // In case there is a -g option as well as debug info from directive .file,
3366 // we turn off the -g option, directly use the existing debug info instead.
3367 // Also reset any implicit ".file 0" for the assembler source.
3368 if (Ctx.getGenDwarfForAssembly()) {
3369 Ctx.getMCDwarfLineTable(0).resetRootFile();
3370 Ctx.setGenDwarfForAssembly(false);
3371 }
3372
Paul Robinson29f5f982018-01-09 23:31:48 +00003373 MD5::MD5Result *CKMem = nullptr;
Paul Robinson01954692018-04-11 15:14:05 +00003374 if (HasMD5) {
Paul Robinson29f5f982018-01-09 23:31:48 +00003375 CKMem = (MD5::MD5Result *)Ctx.allocate(sizeof(MD5::MD5Result), 1);
Paul Robinson01954692018-04-11 15:14:05 +00003376 for (unsigned i = 0; i != 8; ++i) {
3377 CKMem->Bytes[i] = uint8_t(MD5Hi >> ((7 - i) * 8));
3378 CKMem->Bytes[i + 8] = uint8_t(MD5Lo >> ((7 - i) * 8));
3379 }
Paul Robinson29f5f982018-01-09 23:31:48 +00003380 }
Scott Linder16c7bda2018-02-23 23:01:06 +00003381 if (HasSource) {
3382 char *SourceBuf = static_cast<char *>(Ctx.allocate(SourceString.size()));
3383 memcpy(SourceBuf, SourceString.data(), SourceString.size());
3384 Source = StringRef(SourceBuf, SourceString.size());
3385 }
Paul Robinson547adca2018-06-21 16:42:03 +00003386 if (FileNumber == 0) {
3387 if (Ctx.getDwarfVersion() < 5)
3388 return Warning(DirectiveLoc, "file 0 not supported prior to DWARF-5");
Paul Robinsonb271f312018-03-29 17:16:41 +00003389 getStreamer().emitDwarfFile0Directive(Directory, Filename, CKMem, Source);
Paul Robinson547adca2018-06-21 16:42:03 +00003390 } else {
Paul Robinsonb271f312018-03-29 17:16:41 +00003391 Expected<unsigned> FileNumOrErr = getStreamer().tryEmitDwarfFileDirective(
3392 FileNumber, Directory, Filename, CKMem, Source);
3393 if (!FileNumOrErr)
3394 return Error(DirectiveLoc, toString(FileNumOrErr.takeError()));
3395 FileNumber = FileNumOrErr.get();
3396 }
Paul Robinsoncc7344a2018-06-14 13:38:20 +00003397 // Alert the user if there are some .file directives with MD5 and some not.
3398 // But only do that once.
3399 if (!ReportedInconsistentMD5 && !Ctx.isDwarfMD5UsageConsistent(0)) {
3400 ReportedInconsistentMD5 = true;
3401 return Warning(DirectiveLoc, "inconsistent use of MD5 checksums");
3402 }
Eli Bendersky17233942013-01-15 22:59:42 +00003403 }
3404
3405 return false;
3406}
3407
Jim Grosbach4b905842013-09-20 23:08:21 +00003408/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003409/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003410bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003411 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003412 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003413 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3414 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003415 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003416 // FIXME: Do something with the .line.
3417 }
Nirav Davea645433c2016-07-18 15:24:03 +00003418 if (parseToken(AsmToken::EndOfStatement,
3419 "unexpected token in '.line' directive"))
3420 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003421
3422 return false;
3423}
3424
Jim Grosbach4b905842013-09-20 23:08:21 +00003425/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003426/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3427/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3428/// The first number is a file number, must have been previously assigned with
3429/// a .file directive, the second number is the line number and optionally the
3430/// third number is a column position (zero if not specified). The remaining
3431/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003432bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003433 int64_t FileNumber = 0, LineNumber = 0;
3434 SMLoc Loc = getTok().getLoc();
3435 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
Paul Robinson11539b02018-06-22 14:16:11 +00003436 check(FileNumber < 1 && Ctx.getDwarfVersion() < 5, Loc,
Nirav Davea645433c2016-07-18 15:24:03 +00003437 "file number less than one in '.loc' directive") ||
3438 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3439 "unassigned file number in '.loc' directive"))
3440 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003441
Nirav Davea645433c2016-07-18 15:24:03 +00003442 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003443 if (getLexer().is(AsmToken::Integer)) {
3444 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003445 if (LineNumber < 0)
3446 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003447 Lex();
3448 }
3449
3450 int64_t ColumnPos = 0;
3451 if (getLexer().is(AsmToken::Integer)) {
3452 ColumnPos = getTok().getIntVal();
3453 if (ColumnPos < 0)
3454 return TokError("column position less than zero in '.loc' directive");
3455 Lex();
3456 }
3457
3458 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3459 unsigned Isa = 0;
3460 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003461
Nirav Dave1a9044b2016-10-24 14:35:29 +00003462 auto parseLocOp = [&]() -> bool {
3463 StringRef Name;
3464 SMLoc Loc = getTok().getLoc();
3465 if (parseIdentifier(Name))
3466 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003467
Nirav Dave1a9044b2016-10-24 14:35:29 +00003468 if (Name == "basic_block")
3469 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3470 else if (Name == "prologue_end")
3471 Flags |= DWARF2_FLAG_PROLOGUE_END;
3472 else if (Name == "epilogue_begin")
3473 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3474 else if (Name == "is_stmt") {
3475 Loc = getTok().getLoc();
3476 const MCExpr *Value;
3477 if (parseExpression(Value))
3478 return true;
3479 // The expression must be the constant 0 or 1.
3480 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3481 int Value = MCE->getValue();
3482 if (Value == 0)
3483 Flags &= ~DWARF2_FLAG_IS_STMT;
3484 else if (Value == 1)
3485 Flags |= DWARF2_FLAG_IS_STMT;
3486 else
3487 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003488 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003489 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003490 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003491 } else if (Name == "isa") {
3492 Loc = getTok().getLoc();
3493 const MCExpr *Value;
3494 if (parseExpression(Value))
3495 return true;
3496 // The expression must be a constant greater or equal to 0.
3497 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3498 int Value = MCE->getValue();
3499 if (Value < 0)
3500 return Error(Loc, "isa number less than zero");
3501 Isa = Value;
3502 } else {
3503 return Error(Loc, "isa number not a constant value");
3504 }
3505 } else if (Name == "discriminator") {
3506 if (parseAbsoluteExpression(Discriminator))
3507 return true;
3508 } else {
3509 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003510 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003511 return false;
3512 };
3513
Nirav Davee2369aa2016-10-26 17:28:58 +00003514 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003515 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003516
3517 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3518 Isa, Discriminator, StringRef());
3519
3520 return false;
3521}
3522
Jim Grosbach4b905842013-09-20 23:08:21 +00003523/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003524/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003525bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003526 return TokError("unsupported directive '.stabs'");
3527}
3528
Reid Kleckner2214ed82016-01-29 00:49:42 +00003529/// parseDirectiveCVFile
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003530/// ::= .cv_file number filename [checksum] [checksumkind]
Reid Kleckner2214ed82016-01-29 00:49:42 +00003531bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003532 SMLoc FileNumberLoc = getTok().getLoc();
3533 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003534 std::string Filename;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003535 std::string Checksum;
3536 int64_t ChecksumKind = 0;
Nirav Davea645433c2016-07-18 15:24:03 +00003537
3538 if (parseIntToken(FileNumber,
3539 "expected file number in '.cv_file' directive") ||
3540 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3541 check(getTok().isNot(AsmToken::String),
3542 "unexpected token in '.cv_file' directive") ||
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003543 parseEscapedString(Filename))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003544 return true;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003545 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3546 if (check(getTok().isNot(AsmToken::String),
3547 "unexpected token in '.cv_file' directive") ||
3548 parseEscapedString(Checksum) ||
3549 parseIntToken(ChecksumKind,
3550 "expected checksum kind in '.cv_file' directive") ||
3551 parseToken(AsmToken::EndOfStatement,
3552 "unexpected token in '.cv_file' directive"))
3553 return true;
3554 }
Nirav Dave1ab71992016-07-18 19:35:21 +00003555
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003556 Checksum = fromHex(Checksum);
3557 void *CKMem = Ctx.allocate(Checksum.size(), 1);
3558 memcpy(CKMem, Checksum.data(), Checksum.size());
3559 ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem),
3560 Checksum.size());
3561
3562 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename, ChecksumAsBytes,
3563 static_cast<uint8_t>(ChecksumKind)))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003564 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003565
3566 return false;
3567}
3568
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003569bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3570 StringRef DirectiveName) {
3571 SMLoc Loc;
3572 return parseTokenLoc(Loc) ||
3573 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3574 "' directive") ||
3575 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3576 "expected function id within range [0, UINT_MAX)");
3577}
3578
3579bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3580 SMLoc Loc;
3581 return parseTokenLoc(Loc) ||
3582 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3583 "' directive") ||
3584 check(FileNumber < 1, Loc, "file number less than one in '" +
3585 DirectiveName + "' directive") ||
3586 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3587 "unassigned file number in '" + DirectiveName + "' directive");
3588}
3589
3590/// parseDirectiveCVFuncId
3591/// ::= .cv_func_id FunctionId
3592///
3593/// Introduces a function ID that can be used with .cv_loc.
3594bool AsmParser::parseDirectiveCVFuncId() {
3595 SMLoc FunctionIdLoc = getTok().getLoc();
3596 int64_t FunctionId;
3597
3598 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3599 parseToken(AsmToken::EndOfStatement,
3600 "unexpected token in '.cv_func_id' directive"))
3601 return true;
3602
3603 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003604 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003605
3606 return false;
3607}
3608
3609/// parseDirectiveCVInlineSiteId
3610/// ::= .cv_inline_site_id FunctionId
3611/// "within" IAFunc
3612/// "inlined_at" IAFile IALine [IACol]
3613///
3614/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3615/// at" source location information for use in the line table of the caller,
3616/// whether the caller is a real function or another inlined call site.
3617bool AsmParser::parseDirectiveCVInlineSiteId() {
3618 SMLoc FunctionIdLoc = getTok().getLoc();
3619 int64_t FunctionId;
3620 int64_t IAFunc;
3621 int64_t IAFile;
3622 int64_t IALine;
3623 int64_t IACol = 0;
3624
3625 // FunctionId
3626 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3627 return true;
3628
3629 // "within"
3630 if (check((getLexer().isNot(AsmToken::Identifier) ||
3631 getTok().getIdentifier() != "within"),
3632 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3633 return true;
3634 Lex();
3635
3636 // IAFunc
3637 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3638 return true;
3639
3640 // "inlined_at"
3641 if (check((getLexer().isNot(AsmToken::Identifier) ||
3642 getTok().getIdentifier() != "inlined_at"),
3643 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3644 "directive") )
3645 return true;
3646 Lex();
3647
3648 // IAFile IALine
3649 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3650 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3651 return true;
3652
3653 // [IACol]
3654 if (getLexer().is(AsmToken::Integer)) {
3655 IACol = getTok().getIntVal();
3656 Lex();
3657 }
3658
3659 if (parseToken(AsmToken::EndOfStatement,
3660 "unexpected token in '.cv_inline_site_id' directive"))
3661 return true;
3662
3663 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3664 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003665 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003666
3667 return false;
3668}
3669
Reid Kleckner2214ed82016-01-29 00:49:42 +00003670/// parseDirectiveCVLoc
3671/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3672/// [is_stmt VALUE]
3673/// The first number is a file number, must have been previously assigned with
3674/// a .file directive, the second number is the line number and optionally the
3675/// third number is a column position (zero if not specified). The remaining
3676/// optional items are .loc sub-directives.
3677bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003678 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003679 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003680 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3681 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003682 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003683
3684 int64_t LineNumber = 0;
3685 if (getLexer().is(AsmToken::Integer)) {
3686 LineNumber = getTok().getIntVal();
3687 if (LineNumber < 0)
3688 return TokError("line number less than zero in '.cv_loc' directive");
3689 Lex();
3690 }
3691
3692 int64_t ColumnPos = 0;
3693 if (getLexer().is(AsmToken::Integer)) {
3694 ColumnPos = getTok().getIntVal();
3695 if (ColumnPos < 0)
3696 return TokError("column position less than zero in '.cv_loc' directive");
3697 Lex();
3698 }
3699
3700 bool PrologueEnd = false;
3701 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003702
3703 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003704 StringRef Name;
3705 SMLoc Loc = getTok().getLoc();
3706 if (parseIdentifier(Name))
3707 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003708 if (Name == "prologue_end")
3709 PrologueEnd = true;
3710 else if (Name == "is_stmt") {
3711 Loc = getTok().getLoc();
3712 const MCExpr *Value;
3713 if (parseExpression(Value))
3714 return true;
3715 // The expression must be the constant 0 or 1.
3716 IsStmt = ~0ULL;
3717 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3718 IsStmt = MCE->getValue();
3719
3720 if (IsStmt > 1)
3721 return Error(Loc, "is_stmt value not 0 or 1");
3722 } else {
3723 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3724 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003725 return false;
3726 };
3727
3728 if (parseMany(parseOp, false /*hasComma*/))
3729 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003730
3731 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003732 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3733 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003734 return false;
3735}
3736
3737/// parseDirectiveCVLinetable
3738/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3739bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003740 int64_t FunctionId;
3741 StringRef FnStartName, FnEndName;
3742 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003743 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003744 parseToken(AsmToken::Comma,
3745 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003746 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3747 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003748 parseToken(AsmToken::Comma,
3749 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003750 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3751 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003752 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003753
3754 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3755 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3756
3757 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3758 return false;
3759}
3760
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003761/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003762/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003763bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003764 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3765 StringRef FnStartName, FnEndName;
3766 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003767 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003768 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003769 parseIntToken(
3770 SourceFileId,
3771 "expected SourceField in '.cv_inline_linetable' directive") ||
3772 check(SourceFileId <= 0, Loc,
3773 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003774 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003775 parseIntToken(
3776 SourceLineNum,
3777 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3778 check(SourceLineNum < 0, Loc,
3779 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003780 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3781 "expected identifier in directive") ||
3782 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3783 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003784 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003785
Nirav Davea645433c2016-07-18 15:24:03 +00003786 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3787 return true;
3788
3789 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3790 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003791 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3792 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003793 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003794 return false;
3795}
3796
David Majnemer408b5e62016-02-05 01:55:49 +00003797/// parseDirectiveCVDefRange
3798/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3799bool AsmParser::parseDirectiveCVDefRange() {
3800 SMLoc Loc;
3801 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3802 while (getLexer().is(AsmToken::Identifier)) {
3803 Loc = getLexer().getLoc();
3804 StringRef GapStartName;
3805 if (parseIdentifier(GapStartName))
3806 return Error(Loc, "expected identifier in directive");
3807 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3808
3809 Loc = getLexer().getLoc();
3810 StringRef GapEndName;
3811 if (parseIdentifier(GapEndName))
3812 return Error(Loc, "expected identifier in directive");
3813 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3814
3815 Ranges.push_back({GapStartSym, GapEndSym});
3816 }
3817
David Majnemer408b5e62016-02-05 01:55:49 +00003818 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003819 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3820 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003821 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003822
3823 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3824 return false;
3825}
3826
Reid Kleckner06d02d02018-09-07 21:30:52 +00003827/// parseDirectiveCVString
3828/// ::= .cv_stringtable "string"
3829bool AsmParser::parseDirectiveCVString() {
3830 std::string Data;
3831 if (checkForValidSection() || parseEscapedString(Data))
3832 return addErrorSuffix(" in '.cv_string' directive");
3833
3834 // Put the string in the table and emit the offset.
3835 std::pair<StringRef, unsigned> Insertion =
3836 getCVContext().addToStringTable(Data);
3837 getStreamer().EmitIntValue(Insertion.second, 4);
3838 return false;
3839}
3840
Reid Kleckner2214ed82016-01-29 00:49:42 +00003841/// parseDirectiveCVStringTable
3842/// ::= .cv_stringtable
3843bool AsmParser::parseDirectiveCVStringTable() {
3844 getStreamer().EmitCVStringTableDirective();
3845 return false;
3846}
3847
3848/// parseDirectiveCVFileChecksums
3849/// ::= .cv_filechecksums
3850bool AsmParser::parseDirectiveCVFileChecksums() {
3851 getStreamer().EmitCVFileChecksumsDirective();
3852 return false;
3853}
3854
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003855/// parseDirectiveCVFileChecksumOffset
3856/// ::= .cv_filechecksumoffset fileno
3857bool AsmParser::parseDirectiveCVFileChecksumOffset() {
3858 int64_t FileNo;
3859 if (parseIntToken(FileNo, "expected identifier in directive"))
3860 return true;
3861 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3862 return true;
3863 getStreamer().EmitCVFileChecksumOffsetDirective(FileNo);
3864 return false;
3865}
3866
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00003867/// parseDirectiveCVFPOData
3868/// ::= .cv_fpo_data procsym
3869bool AsmParser::parseDirectiveCVFPOData() {
3870 SMLoc DirLoc = getLexer().getLoc();
3871 StringRef ProcName;
3872 if (parseIdentifier(ProcName))
3873 return TokError("expected symbol name");
3874 if (parseEOL("unexpected tokens"))
3875 return addErrorSuffix(" in '.cv_fpo_data' directive");
3876 MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName);
3877 getStreamer().EmitCVFPOData(ProcSym, DirLoc);
3878 return false;
3879}
3880
Jim Grosbach4b905842013-09-20 23:08:21 +00003881/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003882/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003883bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003884 StringRef Name;
3885 bool EH = false;
3886 bool Debug = false;
3887
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003888 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003889 return TokError("Expected an identifier");
3890
3891 if (Name == ".eh_frame")
3892 EH = true;
3893 else if (Name == ".debug_frame")
3894 Debug = true;
3895
3896 if (getLexer().is(AsmToken::Comma)) {
3897 Lex();
3898
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003899 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003900 return TokError("Expected an identifier");
3901
3902 if (Name == ".eh_frame")
3903 EH = true;
3904 else if (Name == ".debug_frame")
3905 Debug = true;
3906 }
3907
3908 getStreamer().EmitCFISections(EH, Debug);
3909 return false;
3910}
3911
Jim Grosbach4b905842013-09-20 23:08:21 +00003912/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003913/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003914bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003915 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003916 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3917 if (check(parseIdentifier(Simple) || Simple != "simple",
3918 "unexpected token") ||
3919 parseToken(AsmToken::EndOfStatement))
3920 return addErrorSuffix(" in '.cfi_startproc' directive");
3921 }
Kristina Brooks1a41a112018-10-19 12:14:30 +00003922
3923 // TODO(kristina): Deal with a corner case of incorrect diagnostic context
3924 // being produced if this directive is emitted as part of preprocessor macro
3925 // expansion which can *ONLY* happen if Clang's cc1as is the API consumer.
3926 // Tools like llvm-mc on the other hand are not affected by it, and report
3927 // correct context information.
3928 getStreamer().EmitCFIStartProc(!Simple.empty(), Lexer.getLoc());
Eli Bendersky17233942013-01-15 22:59:42 +00003929 return false;
3930}
3931
Jim Grosbach4b905842013-09-20 23:08:21 +00003932/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003933/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003934bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003935 getStreamer().EmitCFIEndProc();
3936 return false;
3937}
3938
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003939/// parse register name or number.
Jim Grosbach4b905842013-09-20 23:08:21 +00003940bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003941 SMLoc DirectiveLoc) {
3942 unsigned RegNo;
3943
3944 if (getLexer().isNot(AsmToken::Integer)) {
3945 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3946 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003947 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003948 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003949 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003950
3951 return false;
3952}
3953
Jim Grosbach4b905842013-09-20 23:08:21 +00003954/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003955/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003956bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003957 int64_t Register = 0, Offset = 0;
3958 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3959 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3960 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003961 return true;
3962
3963 getStreamer().EmitCFIDefCfa(Register, Offset);
3964 return false;
3965}
3966
Jim Grosbach4b905842013-09-20 23:08:21 +00003967/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003968/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003969bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003970 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003971 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003972 return true;
3973
3974 getStreamer().EmitCFIDefCfaOffset(Offset);
3975 return false;
3976}
3977
Jim Grosbach4b905842013-09-20 23:08:21 +00003978/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003979/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003980bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003981 int64_t Register1 = 0, Register2 = 0;
3982 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3983 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3984 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003985 return true;
3986
3987 getStreamer().EmitCFIRegister(Register1, Register2);
3988 return false;
3989}
3990
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003991/// parseDirectiveCFIWindowSave
3992/// ::= .cfi_window_save
3993bool AsmParser::parseDirectiveCFIWindowSave() {
3994 getStreamer().EmitCFIWindowSave();
3995 return false;
3996}
3997
Jim Grosbach4b905842013-09-20 23:08:21 +00003998/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003999/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00004000bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00004001 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004002 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00004003 return true;
4004
4005 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
4006 return false;
4007}
4008
Jim Grosbach4b905842013-09-20 23:08:21 +00004009/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00004010/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00004011bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004012 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00004013 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004014 return true;
4015
4016 getStreamer().EmitCFIDefCfaRegister(Register);
4017 return false;
4018}
4019
Jim Grosbach4b905842013-09-20 23:08:21 +00004020/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00004021/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00004022bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004023 int64_t Register = 0;
4024 int64_t Offset = 0;
4025
Nirav Davea645433c2016-07-18 15:24:03 +00004026 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
4027 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4028 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00004029 return true;
4030
4031 getStreamer().EmitCFIOffset(Register, Offset);
4032 return false;
4033}
4034
Jim Grosbach4b905842013-09-20 23:08:21 +00004035/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00004036/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00004037bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004038 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00004039
Nirav Davea645433c2016-07-18 15:24:03 +00004040 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
4041 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4042 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00004043 return true;
4044
4045 getStreamer().EmitCFIRelOffset(Register, Offset);
4046 return false;
4047}
4048
4049static bool isValidEncoding(int64_t Encoding) {
4050 if (Encoding & ~0xff)
4051 return false;
4052
4053 if (Encoding == dwarf::DW_EH_PE_omit)
4054 return true;
4055
4056 const unsigned Format = Encoding & 0xf;
4057 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
4058 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
4059 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
4060 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
4061 return false;
4062
4063 const unsigned Application = Encoding & 0x70;
4064 if (Application != dwarf::DW_EH_PE_absptr &&
4065 Application != dwarf::DW_EH_PE_pcrel)
4066 return false;
4067
4068 return true;
4069}
4070
Jim Grosbach4b905842013-09-20 23:08:21 +00004071/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00004072/// IsPersonality true for cfi_personality, false for cfi_lsda
4073/// ::= .cfi_personality encoding, [symbol_name]
4074/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00004075bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00004076 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004077 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00004078 return true;
4079 if (Encoding == dwarf::DW_EH_PE_omit)
4080 return false;
4081
Eli Bendersky17233942013-01-15 22:59:42 +00004082 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004083 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
4084 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4085 check(parseIdentifier(Name), "expected identifier in directive"))
4086 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004087
Jim Grosbach6f482002015-05-18 18:43:14 +00004088 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004089
4090 if (IsPersonality)
4091 getStreamer().EmitCFIPersonality(Sym, Encoding);
4092 else
4093 getStreamer().EmitCFILsda(Sym, Encoding);
4094 return false;
4095}
4096
Jim Grosbach4b905842013-09-20 23:08:21 +00004097/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00004098/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004099bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004100 getStreamer().EmitCFIRememberState();
4101 return false;
4102}
4103
Jim Grosbach4b905842013-09-20 23:08:21 +00004104/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00004105/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004106bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004107 getStreamer().EmitCFIRestoreState();
4108 return false;
4109}
4110
Jim Grosbach4b905842013-09-20 23:08:21 +00004111/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00004112/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00004113bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004114 int64_t Register = 0;
4115
Jim Grosbach4b905842013-09-20 23:08:21 +00004116 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004117 return true;
4118
4119 getStreamer().EmitCFISameValue(Register);
4120 return false;
4121}
4122
Jim Grosbach4b905842013-09-20 23:08:21 +00004123/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00004124/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00004125bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004126 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00004127 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004128 return true;
4129
4130 getStreamer().EmitCFIRestore(Register);
4131 return false;
4132}
4133
Jim Grosbach4b905842013-09-20 23:08:21 +00004134/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00004135/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004136bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00004137 std::string Values;
4138 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004139 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004140 return true;
4141
4142 Values.push_back((uint8_t)CurrValue);
4143
4144 while (getLexer().is(AsmToken::Comma)) {
4145 Lex();
4146
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004147 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004148 return true;
4149
4150 Values.push_back((uint8_t)CurrValue);
4151 }
4152
4153 getStreamer().EmitCFIEscape(Values);
4154 return false;
4155}
4156
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00004157/// parseDirectiveCFIReturnColumn
4158/// ::= .cfi_return_column register
4159bool AsmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc) {
4160 int64_t Register = 0;
4161 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4162 return true;
4163 getStreamer().EmitCFIReturnColumn(Register);
4164 return false;
4165}
4166
Jim Grosbach4b905842013-09-20 23:08:21 +00004167/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00004168/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00004169bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00004170 if (parseToken(AsmToken::EndOfStatement,
4171 "unexpected token in '.cfi_signal_frame'"))
4172 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004173
4174 getStreamer().EmitCFISignalFrame();
4175 return false;
4176}
4177
Jim Grosbach4b905842013-09-20 23:08:21 +00004178/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00004179/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00004180bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004181 int64_t Register = 0;
4182
Jim Grosbach4b905842013-09-20 23:08:21 +00004183 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004184 return true;
4185
4186 getStreamer().EmitCFIUndefined(Register);
4187 return false;
4188}
4189
Michael Zuckerman56704612017-05-01 13:20:12 +00004190/// parseDirectiveAltmacro
4191/// ::= .altmacro
4192/// ::= .noaltmacro
4193bool AsmParser::parseDirectiveAltmacro(StringRef Directive) {
4194 if (getLexer().isNot(AsmToken::EndOfStatement))
4195 return TokError("unexpected token in '" + Directive + "' directive");
Craig Topperc81aff72018-09-25 20:55:55 +00004196 AltMacroMode = (Directive == ".altmacro");
Michael Zuckerman56704612017-05-01 13:20:12 +00004197 return false;
4198}
4199
Jim Grosbach4b905842013-09-20 23:08:21 +00004200/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00004201/// ::= .macros_on
4202/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00004203bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004204 if (parseToken(AsmToken::EndOfStatement,
4205 "unexpected token in '" + Directive + "' directive"))
4206 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004207
Jim Grosbach4b905842013-09-20 23:08:21 +00004208 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00004209 return false;
4210}
4211
Jim Grosbach4b905842013-09-20 23:08:21 +00004212/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004213/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00004214bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004215 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004216 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00004217 return TokError("expected identifier in '.macro' directive");
4218
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004219 if (getLexer().is(AsmToken::Comma))
4220 Lex();
4221
Eli Bendersky17233942013-01-15 22:59:42 +00004222 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00004223 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004224
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00004225 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004226 return Error(Lexer.getLoc(),
4227 "Vararg parameter '" + Parameters.back().Name +
4228 "' should be last one in the list of parameters.");
4229
David Majnemer91fc4c22014-01-29 18:57:46 +00004230 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004231 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00004232 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004233
Coby Tayreebedaae02017-04-08 20:29:03 +00004234 // Emit an error if two (or more) named parameters share the same name
4235 for (const MCAsmMacroParameter& CurrParam : Parameters)
4236 if (CurrParam.Name.equals(Parameter.Name))
4237 return TokError("macro '" + Name + "' has multiple parameters"
4238 " named '" + Parameter.Name + "'");
4239
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004240 if (Lexer.is(AsmToken::Colon)) {
4241 Lex(); // consume ':'
4242
4243 SMLoc QualLoc;
4244 StringRef Qualifier;
4245
4246 QualLoc = Lexer.getLoc();
4247 if (parseIdentifier(Qualifier))
4248 return Error(QualLoc, "missing parameter qualifier for "
4249 "'" + Parameter.Name + "' in macro '" + Name + "'");
4250
4251 if (Qualifier == "req")
4252 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00004253 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004254 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004255 else
4256 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
4257 "for '" + Parameter.Name + "' in macro '" + Name + "'");
4258 }
4259
David Majnemer91fc4c22014-01-29 18:57:46 +00004260 if (getLexer().is(AsmToken::Equal)) {
4261 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004262
4263 SMLoc ParamLoc;
4264
4265 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004266 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00004267 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004268
4269 if (Parameter.Required)
4270 Warning(ParamLoc, "pointless default value for required parameter "
4271 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00004272 }
David Majnemer91fc4c22014-01-29 18:57:46 +00004273
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00004274 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00004275
4276 if (getLexer().is(AsmToken::Comma))
4277 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004278 }
4279
Nirav Dave1180e6892016-06-02 17:15:05 +00004280 // Eat just the end of statement.
4281 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004282
Nirav Dave1180e6892016-06-02 17:15:05 +00004283 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00004284 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004285 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00004286 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004287 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00004288 // Ignore Lexing errors in macros.
4289 while (Lexer.is(AsmToken::Error)) {
4290 Lexer.Lex();
4291 }
4292
Eli Bendersky17233942013-01-15 22:59:42 +00004293 // Check whether we have reached the end of the file.
4294 if (getLexer().is(AsmToken::Eof))
4295 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
4296
4297 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004298 if (getLexer().is(AsmToken::Identifier)) {
4299 if (getTok().getIdentifier() == ".endm" ||
4300 getTok().getIdentifier() == ".endmacro") {
4301 if (MacroDepth == 0) { // Outermost macro.
4302 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00004303 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004304 if (getLexer().isNot(AsmToken::EndOfStatement))
4305 return TokError("unexpected token in '" + EndToken.getIdentifier() +
4306 "' directive");
4307 break;
4308 } else {
4309 // Otherwise we just found the end of an inner macro.
4310 --MacroDepth;
4311 }
4312 } else if (getTok().getIdentifier() == ".macro") {
4313 // We allow nested macros. Those aren't instantiated until the outermost
4314 // macro is expanded so just ignore them for now.
4315 ++MacroDepth;
4316 }
Eli Bendersky17233942013-01-15 22:59:42 +00004317 }
4318
4319 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004320 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00004321 }
4322
Rafael Espindola22c38a02018-02-14 16:34:27 +00004323 if (getContext().lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00004324 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
4325 }
4326
4327 const char *BodyStart = StartToken.getLoc().getPointer();
4328 const char *BodyEnd = EndToken.getLoc().getPointer();
4329 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00004330 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Oliver Stannardc3e7c6d2018-03-06 15:32:34 +00004331 MCAsmMacro Macro(Name, Body, std::move(Parameters));
4332 DEBUG_WITH_TYPE("asm-macros", dbgs() << "Defining new macro:\n";
4333 Macro.dump());
4334 getContext().defineMacro(Name, std::move(Macro));
Eli Bendersky17233942013-01-15 22:59:42 +00004335 return false;
4336}
4337
Jim Grosbach4b905842013-09-20 23:08:21 +00004338/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00004339///
4340/// With the support added for named parameters there may be code out there that
4341/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00004342/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00004343/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00004344/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00004345/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4346/// warning that the positional parameter found in body which have no effect.
4347/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00004348/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00004349/// intended or change the macro to use the named parameters. It is possible
4350/// this warning will trigger when the none of the named parameters are used
4351/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00004352void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00004353 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004354 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00004355 // If this macro is not defined with named parameters the warning we are
4356 // checking for here doesn't apply.
4357 unsigned NParameters = Parameters.size();
4358 if (NParameters == 0)
4359 return;
4360
4361 bool NamedParametersFound = false;
4362 bool PositionalParametersFound = false;
4363
4364 // Look at the body of the macro for use of both the named parameters and what
4365 // are likely to be positional parameters. This is what expandMacro() is
4366 // doing when it finds the parameters in the body.
4367 while (!Body.empty()) {
4368 // Scan for the next possible parameter.
4369 std::size_t End = Body.size(), Pos = 0;
4370 for (; Pos != End; ++Pos) {
4371 // Check for a substitution or escape.
4372 // This macro is defined with parameters, look for \foo, \bar, etc.
4373 if (Body[Pos] == '\\' && Pos + 1 != End)
4374 break;
4375
4376 // This macro should have parameters, but look for $0, $1, ..., $n too.
4377 if (Body[Pos] != '$' || Pos + 1 == End)
4378 continue;
4379 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004380 if (Next == '$' || Next == 'n' ||
4381 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004382 break;
4383 }
4384
4385 // Check if we reached the end.
4386 if (Pos == End)
4387 break;
4388
4389 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004390 switch (Body[Pos + 1]) {
4391 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004392 case '$':
4393 break;
4394
Jim Grosbach4b905842013-09-20 23:08:21 +00004395 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004396 case 'n':
4397 PositionalParametersFound = true;
4398 break;
4399
Jim Grosbach4b905842013-09-20 23:08:21 +00004400 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004401 default: {
4402 PositionalParametersFound = true;
4403 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004404 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004405 }
4406 Pos += 2;
4407 } else {
4408 unsigned I = Pos + 1;
4409 while (isIdentifierChar(Body[I]) && I + 1 != End)
4410 ++I;
4411
Jim Grosbach4b905842013-09-20 23:08:21 +00004412 const char *Begin = Body.data() + Pos + 1;
4413 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004414 unsigned Index = 0;
4415 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004416 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004417 break;
4418
4419 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004420 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4421 Pos += 3;
4422 else {
4423 Pos = I;
4424 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004425 } else {
4426 NamedParametersFound = true;
4427 Pos += 1 + Argument.size();
4428 }
4429 }
4430 // Update the scan point.
4431 Body = Body.substr(Pos);
4432 }
4433
4434 if (!NamedParametersFound && PositionalParametersFound)
4435 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4436 "used in macro body, possible positional parameter "
4437 "found in body which will have no effect");
4438}
4439
Nico Weber155dccd12014-07-24 17:08:39 +00004440/// parseDirectiveExitMacro
4441/// ::= .exitm
4442bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004443 if (parseToken(AsmToken::EndOfStatement,
4444 "unexpected token in '" + Directive + "' directive"))
4445 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004446
4447 if (!isInsideMacroInstantiation())
4448 return TokError("unexpected '" + Directive + "' in file, "
4449 "no current macro definition");
4450
4451 // Exit all conditionals that are active in the current macro.
4452 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4453 TheCondState = TheCondStack.back();
4454 TheCondStack.pop_back();
4455 }
4456
4457 handleMacroExit();
4458 return false;
4459}
4460
Jim Grosbach4b905842013-09-20 23:08:21 +00004461/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004462/// ::= .endm
4463/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004464bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004465 if (getLexer().isNot(AsmToken::EndOfStatement))
4466 return TokError("unexpected token in '" + Directive + "' directive");
4467
4468 // If we are inside a macro instantiation, terminate the current
4469 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004470 if (isInsideMacroInstantiation()) {
4471 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004472 return false;
4473 }
4474
4475 // Otherwise, this .endmacro is a stray entry in the file; well formed
4476 // .endmacro directives are handled during the macro definition parsing.
4477 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004478 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004479}
4480
Jim Grosbach4b905842013-09-20 23:08:21 +00004481/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004482/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004483bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004484 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004485 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004486 if (parseTokenLoc(Loc) ||
4487 check(parseIdentifier(Name), Loc,
4488 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004489 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004490 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004491 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004492
Rafael Espindola22c38a02018-02-14 16:34:27 +00004493 if (!getContext().lookupMacro(Name))
Nirav Dave1ab71992016-07-18 19:35:21 +00004494 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4495
Rafael Espindola22c38a02018-02-14 16:34:27 +00004496 getContext().undefineMacro(Name);
Oliver Stannardc3e7c6d2018-03-06 15:32:34 +00004497 DEBUG_WITH_TYPE("asm-macros", dbgs()
4498 << "Un-defining macro: " << Name << "\n");
Eli Bendersky17233942013-01-15 22:59:42 +00004499 return false;
4500}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004501
Jim Grosbach4b905842013-09-20 23:08:21 +00004502/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004503/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004504bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004505 // Expect a single argument: an expression that evaluates to a constant
4506 // in the inclusive range 0-30.
4507 SMLoc ExprLoc = getLexer().getLoc();
4508 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004509 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004510 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4511 "in '.bundle_align_mode' "
4512 "directive") ||
4513 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4514 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004515 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004516
4517 // Because of AlignSizePow2's verified range we can safely truncate it to
4518 // unsigned.
4519 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4520 return false;
4521}
4522
Jim Grosbach4b905842013-09-20 23:08:21 +00004523/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004524/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004525bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004526 if (checkForValidSection())
4527 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004528 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004529
Nirav Dave1a9044b2016-10-24 14:35:29 +00004530 StringRef Option;
4531 SMLoc Loc = getTok().getLoc();
4532 const char *kInvalidOptionError =
4533 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004534
Nirav Dave1a9044b2016-10-24 14:35:29 +00004535 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004536 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4537 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004538 parseToken(AsmToken::EndOfStatement,
4539 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004540 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004541 AlignToEnd = true;
4542 }
4543
Eli Bendersky802b6282013-01-07 21:51:08 +00004544 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004545 return false;
4546}
4547
Jim Grosbach4b905842013-09-20 23:08:21 +00004548/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004549/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004550bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004551 if (checkForValidSection() ||
4552 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004553 "unexpected token in '.bundle_unlock' directive"))
4554 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004555
4556 getStreamer().EmitBundleUnlock();
4557 return false;
4558}
4559
Jim Grosbach4b905842013-09-20 23:08:21 +00004560/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004561/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004562bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Petr Hosek67a94a72016-05-28 05:57:48 +00004563 SMLoc NumBytesLoc = Lexer.getLoc();
4564 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004565 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004566 return true;
4567
4568 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004569 if (parseOptionalToken(AsmToken::Comma))
4570 if (parseAbsoluteExpression(FillExpr))
4571 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4572 if (parseToken(AsmToken::EndOfStatement))
4573 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004574
Eli Bendersky17233942013-01-15 22:59:42 +00004575 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004576 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004577
4578 return false;
4579}
4580
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004581/// parseDirectiveDCB
4582/// ::= .dcb.{b, l, w} expression, expression
4583bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004584 SMLoc NumValuesLoc = Lexer.getLoc();
4585 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004586 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004587 return true;
4588
4589 if (NumValues < 0) {
4590 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4591 return false;
4592 }
4593
4594 if (parseToken(AsmToken::Comma,
4595 "unexpected token in '" + Twine(IDVal) + "' directive"))
4596 return true;
4597
4598 const MCExpr *Value;
4599 SMLoc ExprLoc = getLexer().getLoc();
4600 if (parseExpression(Value))
4601 return true;
4602
4603 // Special case constant expressions to match code generator.
4604 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4605 assert(Size <= 8 && "Invalid size");
4606 uint64_t IntValue = MCE->getValue();
4607 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4608 return Error(ExprLoc, "literal value out of range for directive");
4609 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4610 getStreamer().EmitIntValue(IntValue, Size);
4611 } else {
4612 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4613 getStreamer().EmitValue(Value, Size, ExprLoc);
4614 }
4615
4616 if (parseToken(AsmToken::EndOfStatement,
4617 "unexpected token in '" + Twine(IDVal) + "' directive"))
4618 return true;
4619
4620 return false;
4621}
4622
4623/// parseDirectiveRealDCB
4624/// ::= .dcb.{d, s} expression, expression
4625bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004626 SMLoc NumValuesLoc = Lexer.getLoc();
4627 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004628 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004629 return true;
4630
4631 if (NumValues < 0) {
4632 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4633 return false;
4634 }
4635
4636 if (parseToken(AsmToken::Comma,
4637 "unexpected token in '" + Twine(IDVal) + "' directive"))
4638 return true;
4639
4640 APInt AsInt;
4641 if (parseRealValue(Semantics, AsInt))
4642 return true;
4643
4644 if (parseToken(AsmToken::EndOfStatement,
4645 "unexpected token in '" + Twine(IDVal) + "' directive"))
4646 return true;
4647
4648 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4649 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4650 AsInt.getBitWidth() / 8);
4651
4652 return false;
4653}
4654
Petr Hosek85b2f672016-09-23 21:53:36 +00004655/// parseDirectiveDS
4656/// ::= .ds.{b, d, l, p, s, w, x} expression
4657bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004658 SMLoc NumValuesLoc = Lexer.getLoc();
4659 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004660 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004661 return true;
4662
4663 if (NumValues < 0) {
4664 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4665 return false;
4666 }
4667
4668 if (parseToken(AsmToken::EndOfStatement,
4669 "unexpected token in '" + Twine(IDVal) + "' directive"))
4670 return true;
4671
4672 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4673 getStreamer().emitFill(Size, 0);
4674
4675 return false;
4676}
4677
Jim Grosbach4b905842013-09-20 23:08:21 +00004678/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004679/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004680bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004681 if (checkForValidSection())
4682 return true;
4683
Nirav Dave1a9044b2016-10-24 14:35:29 +00004684 auto parseOp = [&]() -> bool {
4685 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004686 if (parseExpression(Value))
4687 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004688 if (Signed)
4689 getStreamer().EmitSLEB128Value(Value);
4690 else
4691 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004692 return false;
4693 };
Eli Bendersky17233942013-01-15 22:59:42 +00004694
Nirav Dave1a9044b2016-10-24 14:35:29 +00004695 if (parseMany(parseOp))
4696 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004697
4698 return false;
4699}
4700
Jim Grosbach4b905842013-09-20 23:08:21 +00004701/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004702/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004703bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004704 auto parseOp = [&]() -> bool {
4705 StringRef Name;
4706 SMLoc Loc = getTok().getLoc();
4707 if (parseIdentifier(Name))
4708 return Error(Loc, "expected identifier");
4709 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004710
Nirav Dave1a9044b2016-10-24 14:35:29 +00004711 // Assembler local symbols don't make any sense here. Complain loudly.
4712 if (Sym->isTemporary())
4713 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004714
Nirav Dave1a9044b2016-10-24 14:35:29 +00004715 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4716 return Error(Loc, "unable to emit symbol attribute");
4717 return false;
4718 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004719
Nirav Dave1a9044b2016-10-24 14:35:29 +00004720 if (parseMany(parseOp))
4721 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004722 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004723}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004724
Jim Grosbach4b905842013-09-20 23:08:21 +00004725/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004726/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004727bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004728 if (checkForValidSection())
4729 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004730
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004731 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004732 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004733 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004734 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004735
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004736 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004737 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004738
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004739 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004740 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004741 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004742
4743 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004744 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004745 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004746 return true;
4747
4748 int64_t Pow2Alignment = 0;
4749 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004750 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004751 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004752 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004753 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004754 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004755
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004756 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4757 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004758 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4759
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004760 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004761 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4762 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004763 if (!isPowerOf2_64(Pow2Alignment))
4764 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4765 Pow2Alignment = Log2_64(Pow2Alignment);
4766 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004767 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004768
Nirav Dave1a9044b2016-10-24 14:35:29 +00004769 if (parseToken(AsmToken::EndOfStatement,
4770 "unexpected token in '.comm' or '.lcomm' directive"))
4771 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004772
Chris Lattner28ad7542009-07-09 17:25:12 +00004773 // NOTE: a size of zero for a .comm should create a undefined symbol
4774 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004775 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004776 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004777 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004778
Eric Christopherbc818852010-05-14 01:38:54 +00004779 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004780 // may internally end up wanting an alignment in bytes.
4781 // FIXME: Diagnose overflow.
4782 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004783 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004784 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004785
Rafael Espindola13a79bb2017-02-02 21:26:06 +00004786 Sym->redefineIfPossible();
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004787 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004788 return Error(IDLoc, "invalid symbol redefinition");
4789
Chris Lattner28ad7542009-07-09 17:25:12 +00004790 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004791 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004792 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004793 return false;
4794 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004795
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004796 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004797 return false;
4798}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004799
Jim Grosbach4b905842013-09-20 23:08:21 +00004800/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004801/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004802bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004803 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004804 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004805
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004806 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004807 if (parseToken(AsmToken::EndOfStatement,
4808 "unexpected token in '.abort' directive"))
4809 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004810
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004811 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004812 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004813 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004814 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004815 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004816
4817 return false;
4818}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004819
Jim Grosbach4b905842013-09-20 23:08:21 +00004820/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004821/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004822bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004823 // Allow the strings to have escaped octal character sequence.
4824 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004825 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004826
Nirav Davea645433c2016-07-18 15:24:03 +00004827 if (check(getTok().isNot(AsmToken::String),
4828 "expected string in '.include' directive") ||
4829 parseEscapedString(Filename) ||
4830 check(getTok().isNot(AsmToken::EndOfStatement),
4831 "unexpected token in '.include' directive") ||
4832 // Attempt to switch the lexer to the included file before consuming the
4833 // end of statement to avoid losing it when we switch.
4834 check(enterIncludeFile(Filename), IncludeLoc,
4835 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004836 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004837
4838 return false;
4839}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004840
Jim Grosbach4b905842013-09-20 23:08:21 +00004841/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004842/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004843bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004844 // Allow the strings to have escaped octal character sequence.
4845 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004846 SMLoc IncbinLoc = getTok().getLoc();
4847 if (check(getTok().isNot(AsmToken::String),
4848 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00004849 parseEscapedString(Filename))
4850 return true;
4851
4852 int64_t Skip = 0;
4853 const MCExpr *Count = nullptr;
4854 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004855 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00004856 // The skip expression can be omitted while specifying the count, e.g:
4857 // .incbin "filename",,4
4858 if (getTok().isNot(AsmToken::Comma)) {
4859 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4860 return true;
4861 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00004862 if (parseOptionalToken(AsmToken::Comma)) {
4863 CountLoc = getTok().getLoc();
4864 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00004865 return true;
4866 }
4867 }
4868
4869 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004870 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004871 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004872
Petr Hosek2f4ac442016-09-23 00:41:06 +00004873 if (check(Skip < 0, SkipLoc, "skip is negative"))
4874 return true;
4875
Nirav Dave1ab71992016-07-18 19:35:21 +00004876 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00004877 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00004878 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004879 return false;
4880}
4881
Jim Grosbach4b905842013-09-20 23:08:21 +00004882/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004883/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4884bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004885 TheCondStack.push_back(TheCondState);
4886 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004887 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004888 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004889 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004890 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004891 if (parseAbsoluteExpression(ExprValue) ||
4892 parseToken(AsmToken::EndOfStatement,
4893 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004894 return true;
4895
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004896 switch (DirKind) {
4897 default:
4898 llvm_unreachable("unsupported directive");
4899 case DK_IF:
4900 case DK_IFNE:
4901 break;
4902 case DK_IFEQ:
4903 ExprValue = ExprValue == 0;
4904 break;
4905 case DK_IFGE:
4906 ExprValue = ExprValue >= 0;
4907 break;
4908 case DK_IFGT:
4909 ExprValue = ExprValue > 0;
4910 break;
4911 case DK_IFLE:
4912 ExprValue = ExprValue <= 0;
4913 break;
4914 case DK_IFLT:
4915 ExprValue = ExprValue < 0;
4916 break;
4917 }
4918
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004919 TheCondState.CondMet = ExprValue;
4920 TheCondState.Ignore = !TheCondState.CondMet;
4921 }
4922
4923 return false;
4924}
4925
Jim Grosbach4b905842013-09-20 23:08:21 +00004926/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004927/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004928bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004929 TheCondStack.push_back(TheCondState);
4930 TheCondState.TheCond = AsmCond::IfCond;
4931
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004932 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004933 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004934 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004935 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004936
Nirav Davea645433c2016-07-18 15:24:03 +00004937 if (parseToken(AsmToken::EndOfStatement,
4938 "unexpected token in '.ifb' directive"))
4939 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004940
4941 TheCondState.CondMet = ExpectBlank == Str.empty();
4942 TheCondState.Ignore = !TheCondState.CondMet;
4943 }
4944
4945 return false;
4946}
4947
Jim Grosbach4b905842013-09-20 23:08:21 +00004948/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004949/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004950/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004951bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004952 TheCondStack.push_back(TheCondState);
4953 TheCondState.TheCond = AsmCond::IfCond;
4954
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004955 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004956 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004957 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004958 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004959
Nirav Davea645433c2016-07-18 15:24:03 +00004960 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4961 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004962
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004963 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004964
Nirav Davea645433c2016-07-18 15:24:03 +00004965 if (parseToken(AsmToken::EndOfStatement,
4966 "unexpected token in '.ifc' directive"))
4967 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004968
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004969 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004970 TheCondState.Ignore = !TheCondState.CondMet;
4971 }
4972
4973 return false;
4974}
4975
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004976/// parseDirectiveIfeqs
4977/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004978bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004979 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004980 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004981 return TokError("expected string parameter for '.ifeqs' directive");
4982 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004983 }
4984
4985 StringRef String1 = getTok().getStringContents();
4986 Lex();
4987
4988 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004989 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004990 return TokError(
4991 "expected comma after first string for '.ifeqs' directive");
4992 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004993 }
4994
4995 Lex();
4996
4997 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004998 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004999 return TokError("expected string parameter for '.ifeqs' directive");
5000 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005001 }
5002
5003 StringRef String2 = getTok().getStringContents();
5004 Lex();
5005
5006 TheCondStack.push_back(TheCondState);
5007 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00005008 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005009 TheCondState.Ignore = !TheCondState.CondMet;
5010
5011 return false;
5012}
5013
Jim Grosbach4b905842013-09-20 23:08:21 +00005014/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00005015/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00005016bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005017 StringRef Name;
5018 TheCondStack.push_back(TheCondState);
5019 TheCondState.TheCond = AsmCond::IfCond;
5020
5021 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005022 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005023 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00005024 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
5025 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
5026 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005027
Jim Grosbach6f482002015-05-18 18:43:14 +00005028 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005029
5030 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00005031 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005032 else
Craig Topper353eda42014-04-24 06:44:33 +00005033 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005034 TheCondState.Ignore = !TheCondState.CondMet;
5035 }
5036
5037 return false;
5038}
5039
Jim Grosbach4b905842013-09-20 23:08:21 +00005040/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005041/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00005042bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005043 if (TheCondState.TheCond != AsmCond::IfCond &&
5044 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00005045 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
5046 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005047 TheCondState.TheCond = AsmCond::ElseIfCond;
5048
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005049 bool LastIgnoreState = false;
5050 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00005051 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005052 if (LastIgnoreState || TheCondState.CondMet) {
5053 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005054 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00005055 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005056 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005057 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005058 return true;
5059
Nirav Dave1a9044b2016-10-24 14:35:29 +00005060 if (parseToken(AsmToken::EndOfStatement,
5061 "unexpected token in '.elseif' directive"))
5062 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00005063
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005064 TheCondState.CondMet = ExprValue;
5065 TheCondState.Ignore = !TheCondState.CondMet;
5066 }
5067
5068 return false;
5069}
5070
Jim Grosbach4b905842013-09-20 23:08:21 +00005071/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005072/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00005073bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005074 if (parseToken(AsmToken::EndOfStatement,
5075 "unexpected token in '.else' directive"))
5076 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005077
5078 if (TheCondState.TheCond != AsmCond::IfCond &&
5079 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00005080 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
5081 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005082 TheCondState.TheCond = AsmCond::ElseCond;
5083 bool LastIgnoreState = false;
5084 if (!TheCondStack.empty())
5085 LastIgnoreState = TheCondStack.back().Ignore;
5086 if (LastIgnoreState || TheCondState.CondMet)
5087 TheCondState.Ignore = true;
5088 else
5089 TheCondState.Ignore = false;
5090
5091 return false;
5092}
5093
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005094/// parseDirectiveEnd
5095/// ::= .end
5096bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005097 if (parseToken(AsmToken::EndOfStatement,
5098 "unexpected token in '.end' directive"))
5099 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005100
5101 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00005102 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005103
5104 return false;
5105}
5106
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005107/// parseDirectiveError
5108/// ::= .err
5109/// ::= .error [string]
5110bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
5111 if (!TheCondStack.empty()) {
5112 if (TheCondStack.back().Ignore) {
5113 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005114 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005115 }
5116 }
5117
5118 if (!WithMessage)
5119 return Error(L, ".err encountered");
5120
5121 StringRef Message = ".error directive invoked in source file";
5122 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005123 if (Lexer.isNot(AsmToken::String))
5124 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005125
5126 Message = getTok().getStringContents();
5127 Lex();
5128 }
5129
Nirav Dave2364748a2016-09-16 18:30:20 +00005130 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005131}
5132
Nico Weber404012b2014-07-24 16:26:06 +00005133/// parseDirectiveWarning
5134/// ::= .warning [string]
5135bool AsmParser::parseDirectiveWarning(SMLoc L) {
5136 if (!TheCondStack.empty()) {
5137 if (TheCondStack.back().Ignore) {
5138 eatToEndOfStatement();
5139 return false;
5140 }
5141 }
5142
5143 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00005144
5145 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005146 if (Lexer.isNot(AsmToken::String))
5147 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00005148
5149 Message = getTok().getStringContents();
5150 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00005151 if (parseToken(AsmToken::EndOfStatement,
5152 "expected end of statement in '.warning' directive"))
5153 return true;
Nico Weber404012b2014-07-24 16:26:06 +00005154 }
5155
Nirav Dave2364748a2016-09-16 18:30:20 +00005156 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00005157}
5158
Jim Grosbach4b905842013-09-20 23:08:21 +00005159/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005160/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00005161bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005162 if (parseToken(AsmToken::EndOfStatement,
5163 "unexpected token in '.endif' directive"))
5164 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005165
Jim Grosbach4b905842013-09-20 23:08:21 +00005166 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00005167 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
5168 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005169 if (!TheCondStack.empty()) {
5170 TheCondState = TheCondStack.back();
5171 TheCondStack.pop_back();
5172 }
5173
5174 return false;
5175}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00005176
Eli Bendersky17233942013-01-15 22:59:42 +00005177void AsmParser::initializeDirectiveKindMap() {
5178 DirectiveKindMap[".set"] = DK_SET;
5179 DirectiveKindMap[".equ"] = DK_EQU;
5180 DirectiveKindMap[".equiv"] = DK_EQUIV;
5181 DirectiveKindMap[".ascii"] = DK_ASCII;
5182 DirectiveKindMap[".asciz"] = DK_ASCIZ;
5183 DirectiveKindMap[".string"] = DK_STRING;
5184 DirectiveKindMap[".byte"] = DK_BYTE;
5185 DirectiveKindMap[".short"] = DK_SHORT;
5186 DirectiveKindMap[".value"] = DK_VALUE;
5187 DirectiveKindMap[".2byte"] = DK_2BYTE;
5188 DirectiveKindMap[".long"] = DK_LONG;
5189 DirectiveKindMap[".int"] = DK_INT;
5190 DirectiveKindMap[".4byte"] = DK_4BYTE;
5191 DirectiveKindMap[".quad"] = DK_QUAD;
5192 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00005193 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00005194 DirectiveKindMap[".single"] = DK_SINGLE;
5195 DirectiveKindMap[".float"] = DK_FLOAT;
5196 DirectiveKindMap[".double"] = DK_DOUBLE;
5197 DirectiveKindMap[".align"] = DK_ALIGN;
5198 DirectiveKindMap[".align32"] = DK_ALIGN32;
5199 DirectiveKindMap[".balign"] = DK_BALIGN;
5200 DirectiveKindMap[".balignw"] = DK_BALIGNW;
5201 DirectiveKindMap[".balignl"] = DK_BALIGNL;
5202 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
5203 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
5204 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
5205 DirectiveKindMap[".org"] = DK_ORG;
5206 DirectiveKindMap[".fill"] = DK_FILL;
5207 DirectiveKindMap[".zero"] = DK_ZERO;
5208 DirectiveKindMap[".extern"] = DK_EXTERN;
5209 DirectiveKindMap[".globl"] = DK_GLOBL;
5210 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00005211 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
5212 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
5213 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
5214 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
5215 DirectiveKindMap[".reference"] = DK_REFERENCE;
5216 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
5217 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
5218 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
5219 DirectiveKindMap[".comm"] = DK_COMM;
5220 DirectiveKindMap[".common"] = DK_COMMON;
5221 DirectiveKindMap[".lcomm"] = DK_LCOMM;
5222 DirectiveKindMap[".abort"] = DK_ABORT;
5223 DirectiveKindMap[".include"] = DK_INCLUDE;
5224 DirectiveKindMap[".incbin"] = DK_INCBIN;
5225 DirectiveKindMap[".code16"] = DK_CODE16;
5226 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
5227 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005228 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00005229 DirectiveKindMap[".irp"] = DK_IRP;
5230 DirectiveKindMap[".irpc"] = DK_IRPC;
5231 DirectiveKindMap[".endr"] = DK_ENDR;
5232 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
5233 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
5234 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
5235 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00005236 DirectiveKindMap[".ifeq"] = DK_IFEQ;
5237 DirectiveKindMap[".ifge"] = DK_IFGE;
5238 DirectiveKindMap[".ifgt"] = DK_IFGT;
5239 DirectiveKindMap[".ifle"] = DK_IFLE;
5240 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00005241 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00005242 DirectiveKindMap[".ifb"] = DK_IFB;
5243 DirectiveKindMap[".ifnb"] = DK_IFNB;
5244 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005245 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00005246 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00005247 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00005248 DirectiveKindMap[".ifdef"] = DK_IFDEF;
5249 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
5250 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
5251 DirectiveKindMap[".elseif"] = DK_ELSEIF;
5252 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005253 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00005254 DirectiveKindMap[".endif"] = DK_ENDIF;
5255 DirectiveKindMap[".skip"] = DK_SKIP;
5256 DirectiveKindMap[".space"] = DK_SPACE;
5257 DirectiveKindMap[".file"] = DK_FILE;
5258 DirectiveKindMap[".line"] = DK_LINE;
5259 DirectiveKindMap[".loc"] = DK_LOC;
5260 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005261 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005262 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005263 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
5264 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00005265 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005266 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00005267 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner06d02d02018-09-07 21:30:52 +00005268 DirectiveKindMap[".cv_string"] = DK_CV_STRING;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005269 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
5270 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00005271 DirectiveKindMap[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET;
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00005272 DirectiveKindMap[".cv_fpo_data"] = DK_CV_FPO_DATA;
Eli Bendersky17233942013-01-15 22:59:42 +00005273 DirectiveKindMap[".sleb128"] = DK_SLEB128;
5274 DirectiveKindMap[".uleb128"] = DK_ULEB128;
5275 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
5276 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
5277 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
5278 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
5279 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
5280 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
5281 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
5282 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
5283 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
5284 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
5285 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
5286 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
5287 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
5288 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
5289 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
5290 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00005291 DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN;
Eli Bendersky17233942013-01-15 22:59:42 +00005292 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
5293 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
5294 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00005295 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00005296 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
5297 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
5298 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00005299 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00005300 DirectiveKindMap[".endm"] = DK_ENDM;
5301 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
5302 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005303 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005304 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00005305 DirectiveKindMap[".warning"] = DK_WARNING;
Michael Zuckerman56704612017-05-01 13:20:12 +00005306 DirectiveKindMap[".altmacro"] = DK_ALTMACRO;
5307 DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00005308 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00005309 DirectiveKindMap[".dc"] = DK_DC;
5310 DirectiveKindMap[".dc.a"] = DK_DC_A;
5311 DirectiveKindMap[".dc.b"] = DK_DC_B;
5312 DirectiveKindMap[".dc.d"] = DK_DC_D;
5313 DirectiveKindMap[".dc.l"] = DK_DC_L;
5314 DirectiveKindMap[".dc.s"] = DK_DC_S;
5315 DirectiveKindMap[".dc.w"] = DK_DC_W;
5316 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00005317 DirectiveKindMap[".dcb"] = DK_DCB;
5318 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
5319 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
5320 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
5321 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
5322 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
5323 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00005324 DirectiveKindMap[".ds"] = DK_DS;
5325 DirectiveKindMap[".ds.b"] = DK_DS_B;
5326 DirectiveKindMap[".ds.d"] = DK_DS_D;
5327 DirectiveKindMap[".ds.l"] = DK_DS_L;
5328 DirectiveKindMap[".ds.p"] = DK_DS_P;
5329 DirectiveKindMap[".ds.s"] = DK_DS_S;
5330 DirectiveKindMap[".ds.w"] = DK_DS_W;
5331 DirectiveKindMap[".ds.x"] = DK_DS_X;
Coby Tayree01e53202017-10-02 14:36:31 +00005332 DirectiveKindMap[".print"] = DK_PRINT;
Peter Collingbourne3e227332018-07-17 22:17:18 +00005333 DirectiveKindMap[".addrsig"] = DK_ADDRSIG;
5334 DirectiveKindMap[".addrsig_sym"] = DK_ADDRSIG_SYM;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00005335}
5336
Jim Grosbach4b905842013-09-20 23:08:21 +00005337MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005338 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005339
Rafael Espindola34b9c512012-06-03 23:57:14 +00005340 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005341 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005342 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00005343 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005344 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00005345 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005346 }
5347
Rafael Espindola34b9c512012-06-03 23:57:14 +00005348 if (Lexer.is(AsmToken::Identifier) &&
Nirav Davee24fcd52018-07-18 16:17:03 +00005349 (getTok().getIdentifier() == ".rep" ||
5350 getTok().getIdentifier() == ".rept" ||
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00005351 getTok().getIdentifier() == ".irp" ||
5352 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005353 ++NestLevel;
5354 }
5355
5356 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00005357 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005358 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005359 EndToken = getTok();
5360 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005361 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005362 printError(getTok().getLoc(),
5363 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00005364 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005365 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005366 break;
5367 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005368 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005369 }
5370
Rafael Espindola34b9c512012-06-03 23:57:14 +00005371 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005372 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005373 }
5374
5375 const char *BodyStart = StartToken.getLoc().getPointer();
5376 const char *BodyEnd = EndToken.getLoc().getPointer();
5377 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5378
Rafael Espindola34b9c512012-06-03 23:57:14 +00005379 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005380 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00005381 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005382}
5383
Jim Grosbach4b905842013-09-20 23:08:21 +00005384void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005385 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005386 OS << ".endr\n";
5387
Rafael Espindola3560ff22014-08-27 20:03:13 +00005388 std::unique_ptr<MemoryBuffer> Instantiation =
5389 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005390
Rafael Espindola34b9c512012-06-03 23:57:14 +00005391 // Create the macro instantiation object and add to the current macro
5392 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005393 MacroInstantiation *MI = new MacroInstantiation(
5394 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005395 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005396
Rafael Espindola34b9c512012-06-03 23:57:14 +00005397 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005398 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005399 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005400 Lex();
5401}
5402
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005403/// parseDirectiveRept
5404/// ::= .rep | .rept count
5405bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005406 const MCExpr *CountExpr;
5407 SMLoc CountLoc = getTok().getLoc();
5408 if (parseExpression(CountExpr))
5409 return true;
5410
Rafael Espindola34b9c512012-06-03 23:57:14 +00005411 int64_t Count;
Nirav Dave6c0665e2018-04-30 19:22:40 +00005412 if (!CountExpr->evaluateAsAbsolute(Count, getStreamer().getAssemblerPtr())) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005413 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5414 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005415
Nirav Davea645433c2016-07-18 15:24:03 +00005416 if (check(Count < 0, CountLoc, "Count is negative") ||
5417 parseToken(AsmToken::EndOfStatement,
5418 "unexpected token in '" + Dir + "' directive"))
5419 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005420
5421 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005422 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005423 if (!M)
5424 return true;
5425
5426 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5427 // to hold the macro body with substitutions.
5428 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005429 raw_svector_ostream OS(Buf);
5430 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005431 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5432 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005433 return true;
5434 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005435 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005436
5437 return false;
5438}
5439
Jim Grosbach4b905842013-09-20 23:08:21 +00005440/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005441/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005442bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005443 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005444 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005445 if (check(parseIdentifier(Parameter.Name),
5446 "expected identifier in '.irp' directive") ||
5447 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5448 parseMacroArguments(nullptr, A) ||
5449 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005450 return true;
5451
Rafael Espindola768b41c2012-06-15 14:02:34 +00005452 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005453 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005454 if (!M)
5455 return true;
5456
5457 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5458 // to hold the macro body with substitutions.
5459 SmallString<256> Buf;
5460 raw_svector_ostream OS(Buf);
5461
Craig Topper84008482015-10-10 05:38:14 +00005462 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005463 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5464 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005465 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005466 return true;
5467 }
5468
Jim Grosbach4b905842013-09-20 23:08:21 +00005469 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005470
5471 return false;
5472}
5473
Jim Grosbach4b905842013-09-20 23:08:21 +00005474/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005475/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005476bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005477 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005478 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005479
5480 if (check(parseIdentifier(Parameter.Name),
5481 "expected identifier in '.irpc' directive") ||
5482 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5483 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005484 return true;
5485
5486 if (A.size() != 1 || A.front().size() != 1)
5487 return TokError("unexpected token in '.irpc' directive");
5488
5489 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005490 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5491 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005492
5493 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005494 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005495 if (!M)
5496 return true;
5497
5498 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5499 // to hold the macro body with substitutions.
5500 SmallString<256> Buf;
5501 raw_svector_ostream OS(Buf);
5502
5503 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005504 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005505 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005506 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005507
Toma Tabacu217116e2015-04-27 10:50:29 +00005508 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5509 // This is undocumented, but GAS seems to support it.
5510 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005511 return true;
5512 }
5513
Jim Grosbach4b905842013-09-20 23:08:21 +00005514 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005515
5516 return false;
5517}
5518
Jim Grosbach4b905842013-09-20 23:08:21 +00005519bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005520 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005521 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005522
5523 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005524 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005525 assert(getLexer().is(AsmToken::EndOfStatement));
5526
Jim Grosbach4b905842013-09-20 23:08:21 +00005527 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005528 return false;
5529}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005530
Jim Grosbach4b905842013-09-20 23:08:21 +00005531bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005532 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005533 const MCExpr *Value;
5534 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005535 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005536 return true;
5537 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5538 if (!MCE)
5539 return Error(ExprLoc, "unexpected expression in _emit");
5540 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005541 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005542 return Error(ExprLoc, "literal value out of range for directive");
5543
Craig Topper7d5b2312015-10-10 05:25:02 +00005544 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005545 return false;
5546}
5547
Jim Grosbach4b905842013-09-20 23:08:21 +00005548bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005549 const MCExpr *Value;
5550 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005551 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005552 return true;
5553 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5554 if (!MCE)
5555 return Error(ExprLoc, "unexpected expression in align");
5556 uint64_t IntValue = MCE->getValue();
5557 if (!isPowerOf2_64(IntValue))
5558 return Error(ExprLoc, "literal value not a power of two greater then zero");
5559
Craig Topper7d5b2312015-10-10 05:25:02 +00005560 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005561 return false;
5562}
5563
Coby Tayree01e53202017-10-02 14:36:31 +00005564bool AsmParser::parseDirectivePrint(SMLoc DirectiveLoc) {
5565 const AsmToken StrTok = getTok();
5566 Lex();
5567 if (StrTok.isNot(AsmToken::String) || StrTok.getString().front() != '"')
5568 return Error(DirectiveLoc, "expected double quoted string after .print");
5569 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5570 return true;
5571 llvm::outs() << StrTok.getStringContents() << '\n';
5572 return false;
5573}
5574
Peter Collingbourne3e227332018-07-17 22:17:18 +00005575bool AsmParser::parseDirectiveAddrsig() {
5576 getStreamer().EmitAddrsig();
5577 return false;
5578}
5579
5580bool AsmParser::parseDirectiveAddrsigSym() {
5581 StringRef Name;
5582 if (check(parseIdentifier(Name),
5583 "expected identifier in '.addrsig_sym' directive"))
5584 return true;
5585 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
5586 getStreamer().EmitAddrsigSym(Sym);
5587 return false;
5588}
5589
Chad Rosierf43fcf52013-02-13 21:27:17 +00005590// We are comparing pointers, but the pointers are relative to a single string.
5591// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005592static int rewritesSort(const AsmRewrite *AsmRewriteA,
5593 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005594 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5595 return -1;
5596 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5597 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005598
Chad Rosierfce4fab2013-04-08 17:43:47 +00005599 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5600 // rewrite to the same location. Make sure the SizeDirective rewrite is
5601 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5602 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005603 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5604 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005605 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005606
Jim Grosbach4b905842013-09-20 23:08:21 +00005607 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5608 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005609 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005610 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005611}
5612
Jim Grosbach4b905842013-09-20 23:08:21 +00005613bool AsmParser::parseMSInlineAsm(
5614 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00005615 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
Jim Grosbach4b905842013-09-20 23:08:21 +00005616 SmallVectorImpl<std::string> &Constraints,
5617 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5618 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005619 SmallVector<void *, 4> InputDecls;
5620 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005621 SmallVector<bool, 4> InputDeclsAddressOf;
5622 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005623 SmallVector<std::string, 4> InputConstraints;
5624 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005625 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005626
Benjamin Kramer1a136112013-02-15 20:37:21 +00005627 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005628
5629 // Prime the lexer.
5630 Lex();
5631
5632 // While we have input, parse each statement.
5633 unsigned InputIdx = 0;
5634 unsigned OutputIdx = 0;
5635 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005636 // Parse curly braces marking block start/end
5637 if (parseCurlyBlockScope(AsmStrRewrites))
5638 continue;
5639
Eli Friedman0f4871d2012-10-22 23:58:19 +00005640 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005641 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005642
Nirav Dave2364748a2016-09-16 18:30:20 +00005643 if (StatementErr || Info.ParseError) {
5644 // Emit pending errors if any exist.
5645 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005646 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005647 }
5648
5649 // No pending error should exist here.
5650 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005651
Benjamin Kramer1a136112013-02-15 20:37:21 +00005652 if (Info.Opcode == ~0U)
5653 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005654
Benjamin Kramer1a136112013-02-15 20:37:21 +00005655 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005656
Benjamin Kramer1a136112013-02-15 20:37:21 +00005657 // Build the list of clobbers, outputs and inputs.
5658 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005659 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005660
Benjamin Kramer1a136112013-02-15 20:37:21 +00005661 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005662 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005663 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005664
Benjamin Kramer1a136112013-02-15 20:37:21 +00005665 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005666 if (Operand.isReg() && !Operand.needAddressOf() &&
5667 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005668 unsigned NumDefs = Desc.getNumDefs();
5669 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005670 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5671 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005672 continue;
5673 }
5674
5675 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005676 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005677 if (SymName.empty())
5678 continue;
5679
David Blaikie960ea3f2014-06-08 16:18:35 +00005680 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005681 if (!OpDecl)
5682 continue;
5683
5684 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005685 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005686 if (isOutput) {
5687 ++InputIdx;
5688 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005689 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005690 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005691 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005692 } else {
5693 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005694 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5695 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005696 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005697 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005698 }
Reid Kleckneree088972013-12-10 18:27:32 +00005699
5700 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005701 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5702 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005703 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005704 }
5705
5706 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005707 NumOutputs = OutputDecls.size();
5708 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005709
5710 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005711 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5712 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5713 ClobberRegs.end());
5714 Clobbers.assign(ClobberRegs.size(), std::string());
5715 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5716 raw_string_ostream OS(Clobbers[I]);
5717 IP->printRegName(OS, ClobberRegs[I]);
5718 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005719
5720 // Merge the various outputs and inputs. Output are expected first.
5721 if (NumOutputs || NumInputs) {
5722 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005723 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005724 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005725 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005726 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005727 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005728 }
5729 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005730 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005731 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005732 }
5733 }
5734
5735 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005736 std::string AsmStringIR;
5737 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005738 StringRef ASMString =
5739 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5740 const char *AsmStart = ASMString.begin();
5741 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005742 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005743 for (const AsmRewrite &AR : AsmStrRewrites) {
5744 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005745
David Majnemer8114c1a2014-06-23 02:17:16 +00005746 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005747 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005748
Chad Rosier120eefd2013-03-19 17:32:17 +00005749 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005750 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005751 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005752
Chad Rosier37e755c2012-10-23 17:43:43 +00005753 // Skip the original expression.
5754 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005755 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005756 continue;
5757 }
5758
Chad Rosierff10ed12013-04-12 16:26:42 +00005759 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005760 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005761 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005762 default:
5763 break;
Coby Tayreed8912892017-08-24 08:46:25 +00005764 case AOK_IntelExpr:
5765 assert(AR.IntelExp.isValid() && "cannot write invalid intel expression");
5766 if (AR.IntelExp.NeedBracs)
5767 OS << "[";
5768 if (AR.IntelExp.hasBaseReg())
5769 OS << AR.IntelExp.BaseReg;
5770 if (AR.IntelExp.hasIndexReg())
5771 OS << (AR.IntelExp.hasBaseReg() ? " + " : "")
5772 << AR.IntelExp.IndexReg;
5773 if (AR.IntelExp.Scale > 1)
5774 OS << " * $$" << AR.IntelExp.Scale;
5775 if (AR.IntelExp.Imm || !AR.IntelExp.hasRegs())
5776 OS << (AR.IntelExp.hasRegs() ? " + $$" : "$$") << AR.IntelExp.Imm;
5777 if (AR.IntelExp.NeedBracs)
5778 OS << "]";
Chad Rosier8bce6642012-10-18 15:49:34 +00005779 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005780 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005781 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005782 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005783 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005784 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005785 break;
5786 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005787 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005788 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005789 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005790 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005791 default: break;
5792 case 8: OS << "byte ptr "; break;
5793 case 16: OS << "word ptr "; break;
5794 case 32: OS << "dword ptr "; break;
5795 case 64: OS << "qword ptr "; break;
5796 case 80: OS << "xword ptr "; break;
5797 case 128: OS << "xmmword ptr "; break;
5798 case 256: OS << "ymmword ptr "; break;
5799 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005800 break;
5801 case AOK_Emit:
5802 OS << ".byte";
5803 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005804 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005805 // MS alignment directives are measured in bytes. If the native assembler
5806 // measures alignment in bytes, we can pass it straight through.
5807 OS << ".align";
5808 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5809 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005810
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005811 // Alignment is in log2 form, so print that instead and skip the original
5812 // immediate.
5813 unsigned Val = AR.Val;
5814 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005815 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005816 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5817 break;
5818 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005819 case AOK_EVEN:
5820 OS << ".even";
5821 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005822 case AOK_EndOfStatement:
5823 OS << "\n\t";
5824 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005825 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005826
Chad Rosier8bce6642012-10-18 15:49:34 +00005827 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005828 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005829 }
5830
5831 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005832 if (AsmStart != AsmEnd)
5833 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005834
5835 AsmString = OS.str();
5836 return false;
5837}
5838
Pete Cooper80d21cb2015-06-22 19:35:57 +00005839namespace llvm {
5840namespace MCParserUtils {
5841
5842/// Returns whether the given symbol is used anywhere in the given expression,
5843/// or subexpressions.
5844static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5845 switch (Value->getKind()) {
5846 case MCExpr::Binary: {
5847 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5848 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5849 isSymbolUsedInExpression(Sym, BE->getRHS());
5850 }
5851 case MCExpr::Target:
5852 case MCExpr::Constant:
5853 return false;
5854 case MCExpr::SymbolRef: {
5855 const MCSymbol &S =
5856 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5857 if (S.isVariable())
5858 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5859 return &S == Sym;
5860 }
5861 case MCExpr::Unary:
5862 return isSymbolUsedInExpression(
5863 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5864 }
5865
5866 llvm_unreachable("Unknown expr kind!");
5867}
5868
5869bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5870 MCAsmParser &Parser, MCSymbol *&Sym,
Nirav Dave7fd992a2018-08-16 16:31:14 +00005871 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005872
5873 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005874 SMLoc EqualLoc = Parser.getTok().getLoc();
Nirav Dave7fd992a2018-08-16 16:31:14 +00005875 if (Parser.parseExpression(Value))
5876 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005877
5878 // Note: we don't count b as used in "a = b". This is to allow
5879 // a = b
5880 // b = c
5881
Nirav Dave1a9044b2016-10-24 14:35:29 +00005882 if (Parser.parseToken(AsmToken::EndOfStatement))
5883 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00005884
5885 // Validate that the LHS is allowed to be a variable (either it has not been
5886 // used as a symbol, or it is an absolute symbol).
5887 Sym = Parser.getContext().lookupSymbol(Name);
5888 if (Sym) {
5889 // Diagnose assignment to a label.
5890 //
5891 // FIXME: Diagnostics. Note the location of the definition as a label.
5892 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5893 if (isSymbolUsedInExpression(Sym, Value))
5894 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005895 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5896 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005897 ; // Allow redefinitions of undefined symbols only used in directives.
5898 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5899 ; // Allow redefinitions of variables that haven't yet been used.
5900 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5901 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5902 else if (!Sym->isVariable())
5903 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5904 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5905 return Parser.Error(EqualLoc,
5906 "invalid reassignment of non-absolute variable '" +
5907 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005908 } else if (Name == ".") {
Oliver Stannard268f42f2016-12-14 10:43:58 +00005909 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005910 return false;
5911 } else
5912 Sym = Parser.getContext().getOrCreateSymbol(Name);
5913
5914 Sym->setRedefinable(allow_redef);
5915
5916 return false;
5917}
5918
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005919} // end namespace MCParserUtils
5920} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005921
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005922/// Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005923MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
Sanne Wouda29338752017-02-08 14:48:05 +00005924 MCStreamer &Out, const MCAsmInfo &MAI,
5925 unsigned CB) {
5926 return new AsmParser(SM, C, Out, MAI, CB);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005927}