blob: 5c76c900c744d3887e395fafae4ce85f0a4a2d36 [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;
Reid Kleckner953bdce2018-10-24 20:23:57 +0000232 // When parsing MS inline asm, we must lex 0b1101 and 0ABCH as binary and
233 // hex integer literals.
234 Lexer.setLexMasmIntegers(V);
Yunzhong Gao27ea29b2016-09-02 23:15:29 +0000235 }
Craig Topper59be68f2014-03-08 07:14:16 +0000236 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000237
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000238 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000239 unsigned &NumOutputs, unsigned &NumInputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000240 SmallVectorImpl<std::pair<void *,bool>> &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000241 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000242 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000243 const MCInstrInfo *MII, const MCInstPrinter *IP,
244 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000245
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000246 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000247 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
248 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
249 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000250 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
251 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000252 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000253
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000254 /// Parse a floating point expression using the float \p Semantics
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000255 /// and set \p Res to the value.
256 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
257
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000258 /// Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000259 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000260 bool parseIdentifier(StringRef &Res) override;
261 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000262
Nirav Davef43cc9f2016-10-10 15:24:54 +0000263 bool checkForValidSection() override;
Nirav Davea645433c2016-07-18 15:24:03 +0000264
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000265 /// }
266
267private:
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000268 bool parseStatement(ParseStatementInfo &Info,
269 MCAsmParserSemaCallback *SI);
Marina Yatsina5f5de9f2016-03-07 18:11:16 +0000270 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
Craig Topper3c76c522015-09-20 23:35:59 +0000271 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000272
Jim Grosbach4b905842013-09-20 23:08:21 +0000273 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000274 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000275 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000276 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000277 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000278 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000279
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000280 /// Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000281 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000282
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000283 /// Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000284 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000285
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000286 /// Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000287 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000288
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000289 /// Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000290 ///
291 /// \param M The macro.
292 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000293 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000294
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000295 /// Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000296 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000297
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000298 /// Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000299 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000300
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000301 /// Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000302 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000303
Jim Grosbach4b905842013-09-20 23:08:21 +0000304 void printMacroInstantiations();
305 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Nirav Dave2364748a2016-09-16 18:30:20 +0000306 SMRange Range = None) const {
307 ArrayRef<SMRange> Ranges(Range);
Chris Lattner72845262011-10-16 05:47:55 +0000308 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000309 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000310 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000311
Paul Robinson938d9a02018-03-22 15:48:01 +0000312 /// Should we emit DWARF describing this assembler source? (Returns false if
313 /// the source has .file directives, which means we don't want to generate
314 /// info describing the assembler source itself.)
315 bool enabledGenDwarfForAssembly();
316
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000317 /// Enter the specified file. This returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000318 bool enterIncludeFile(const std::string &Filename);
319
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000320 /// Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000321 /// This returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000322 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
323 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
Daniel Dunbar43235712010-07-18 18:54:11 +0000324
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000325 /// Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000326 /// current token is not set; clients should ensure Lex() is called
327 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000328 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000329 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000330 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000331 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000332
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000333 /// Parse up to the end of statement and a return the contents from the
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000334 /// current token until the end of the statement; the current token on exit
335 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000336 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000337
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000338 /// Parse until the end of a statement or a comma is encountered,
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000339 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000340 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000341
Jim Grosbach4b905842013-09-20 23:08:21 +0000342 bool parseAssignment(StringRef Name, bool allow_redef,
Nirav Dave7fd992a2018-08-16 16:31:14 +0000343 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000344
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000345 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
346 MCBinaryExpr::Opcode &Kind);
347
Jim Grosbach4b905842013-09-20 23:08:21 +0000348 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
349 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
350 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000351
Jim Grosbach4b905842013-09-20 23:08:21 +0000352 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000353
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000354 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
355 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
356
Eli Bendersky17233942013-01-15 22:59:42 +0000357 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000358 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000359 DK_NO_DIRECTIVE, // Placeholder
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000360 DK_SET,
361 DK_EQU,
362 DK_EQUIV,
363 DK_ASCII,
364 DK_ASCIZ,
365 DK_STRING,
366 DK_BYTE,
367 DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000368 DK_RELOC,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000369 DK_VALUE,
370 DK_2BYTE,
371 DK_LONG,
372 DK_INT,
373 DK_4BYTE,
374 DK_QUAD,
375 DK_8BYTE,
376 DK_OCTA,
377 DK_DC,
378 DK_DC_A,
379 DK_DC_B,
380 DK_DC_D,
381 DK_DC_L,
382 DK_DC_S,
383 DK_DC_W,
384 DK_DC_X,
385 DK_DCB,
386 DK_DCB_B,
387 DK_DCB_D,
388 DK_DCB_L,
389 DK_DCB_S,
390 DK_DCB_W,
391 DK_DCB_X,
392 DK_DS,
393 DK_DS_B,
394 DK_DS_D,
395 DK_DS_L,
396 DK_DS_P,
397 DK_DS_S,
398 DK_DS_W,
399 DK_DS_X,
400 DK_SINGLE,
401 DK_FLOAT,
402 DK_DOUBLE,
403 DK_ALIGN,
404 DK_ALIGN32,
405 DK_BALIGN,
406 DK_BALIGNW,
407 DK_BALIGNL,
408 DK_P2ALIGN,
409 DK_P2ALIGNW,
410 DK_P2ALIGNL,
411 DK_ORG,
412 DK_FILL,
413 DK_ENDR,
414 DK_BUNDLE_ALIGN_MODE,
415 DK_BUNDLE_LOCK,
416 DK_BUNDLE_UNLOCK,
417 DK_ZERO,
418 DK_EXTERN,
419 DK_GLOBL,
420 DK_GLOBAL,
421 DK_LAZY_REFERENCE,
422 DK_NO_DEAD_STRIP,
423 DK_SYMBOL_RESOLVER,
424 DK_PRIVATE_EXTERN,
425 DK_REFERENCE,
426 DK_WEAK_DEFINITION,
427 DK_WEAK_REFERENCE,
428 DK_WEAK_DEF_CAN_BE_HIDDEN,
429 DK_COMM,
430 DK_COMMON,
431 DK_LCOMM,
432 DK_ABORT,
433 DK_INCLUDE,
434 DK_INCBIN,
435 DK_CODE16,
436 DK_CODE16GCC,
437 DK_REPT,
438 DK_IRP,
439 DK_IRPC,
440 DK_IF,
441 DK_IFEQ,
442 DK_IFGE,
443 DK_IFGT,
444 DK_IFLE,
445 DK_IFLT,
446 DK_IFNE,
447 DK_IFB,
448 DK_IFNB,
449 DK_IFC,
450 DK_IFEQS,
451 DK_IFNC,
452 DK_IFNES,
453 DK_IFDEF,
454 DK_IFNDEF,
455 DK_IFNOTDEF,
456 DK_ELSEIF,
457 DK_ELSE,
458 DK_ENDIF,
459 DK_SPACE,
460 DK_SKIP,
461 DK_FILE,
462 DK_LINE,
463 DK_LOC,
464 DK_STABS,
465 DK_CV_FILE,
466 DK_CV_FUNC_ID,
467 DK_CV_INLINE_SITE_ID,
468 DK_CV_LOC,
469 DK_CV_LINETABLE,
470 DK_CV_INLINE_LINETABLE,
471 DK_CV_DEF_RANGE,
472 DK_CV_STRINGTABLE,
Reid Kleckner06d02d02018-09-07 21:30:52 +0000473 DK_CV_STRING,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000474 DK_CV_FILECHECKSUMS,
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000475 DK_CV_FILECHECKSUM_OFFSET,
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000476 DK_CV_FPO_DATA,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000477 DK_CFI_SECTIONS,
478 DK_CFI_STARTPROC,
479 DK_CFI_ENDPROC,
480 DK_CFI_DEF_CFA,
481 DK_CFI_DEF_CFA_OFFSET,
482 DK_CFI_ADJUST_CFA_OFFSET,
483 DK_CFI_DEF_CFA_REGISTER,
484 DK_CFI_OFFSET,
485 DK_CFI_REL_OFFSET,
486 DK_CFI_PERSONALITY,
487 DK_CFI_LSDA,
488 DK_CFI_REMEMBER_STATE,
489 DK_CFI_RESTORE_STATE,
490 DK_CFI_SAME_VALUE,
491 DK_CFI_RESTORE,
492 DK_CFI_ESCAPE,
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000493 DK_CFI_RETURN_COLUMN,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000494 DK_CFI_SIGNAL_FRAME,
495 DK_CFI_UNDEFINED,
496 DK_CFI_REGISTER,
497 DK_CFI_WINDOW_SAVE,
Luke Cheeseman41a9e532018-12-21 10:45:08 +0000498 DK_CFI_B_KEY_FRAME,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000499 DK_MACROS_ON,
500 DK_MACROS_OFF,
501 DK_ALTMACRO,
502 DK_NOALTMACRO,
503 DK_MACRO,
504 DK_EXITM,
505 DK_ENDM,
506 DK_ENDMACRO,
507 DK_PURGEM,
508 DK_SLEB128,
509 DK_ULEB128,
510 DK_ERR,
511 DK_ERROR,
512 DK_WARNING,
Coby Tayree01e53202017-10-02 14:36:31 +0000513 DK_PRINT,
Peter Collingbourne3e227332018-07-17 22:17:18 +0000514 DK_ADDRSIG,
515 DK_ADDRSIG_SYM,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000516 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000517 };
518
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000519 /// Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000520 /// directives parsed by this class.
521 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000522
523 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000524 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000525 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Nirav Dave1a9044b2016-10-24 14:35:29 +0000526 bool parseDirectiveValue(StringRef IDVal,
527 unsigned Size); // ".byte", ".long", ...
528 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
529 bool parseDirectiveRealValue(StringRef IDVal,
530 const fltSemantics &); // ".single", ...
Jim Grosbach4b905842013-09-20 23:08:21 +0000531 bool parseDirectiveFill(); // ".fill"
532 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000533 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000534 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
535 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000536 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000537 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000538
Eli Bendersky17233942013-01-15 22:59:42 +0000539 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000540 bool parseDirectiveFile(SMLoc DirectiveLoc);
541 bool parseDirectiveLine();
542 bool parseDirectiveLoc();
543 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000544
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000545 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
Reid Kleckner06d02d02018-09-07 21:30:52 +0000546 // ".cv_inline_linetable", ".cv_def_range", ".cv_string"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000547 bool parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000548 bool parseDirectiveCVFuncId();
549 bool parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000550 bool parseDirectiveCVLoc();
551 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000552 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000553 bool parseDirectiveCVDefRange();
Reid Kleckner06d02d02018-09-07 21:30:52 +0000554 bool parseDirectiveCVString();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000555 bool parseDirectiveCVStringTable();
556 bool parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000557 bool parseDirectiveCVFileChecksumOffset();
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000558 bool parseDirectiveCVFPOData();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000559
Eli Bendersky17233942013-01-15 22:59:42 +0000560 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000561 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000562 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000563 bool parseDirectiveCFISections();
564 bool parseDirectiveCFIStartProc();
565 bool parseDirectiveCFIEndProc();
566 bool parseDirectiveCFIDefCfaOffset();
567 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
568 bool parseDirectiveCFIAdjustCfaOffset();
569 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
570 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
571 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
572 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
573 bool parseDirectiveCFIRememberState();
574 bool parseDirectiveCFIRestoreState();
575 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
576 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
577 bool parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000578 bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +0000579 bool parseDirectiveCFISignalFrame();
580 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000581
582 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000583 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000584 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000585 bool parseDirectiveEndMacro(StringRef Directive);
586 bool parseDirectiveMacro(SMLoc DirectiveLoc);
587 bool parseDirectiveMacrosOnOff(StringRef Directive);
Michael Zuckerman56704612017-05-01 13:20:12 +0000588 // alternate macro mode directives
589 bool parseDirectiveAltmacro(StringRef Directive);
Eli Benderskyf483ff92012-12-20 19:05:53 +0000590 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000591 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000592 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000593 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000594 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000595 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000596
Eli Bendersky17233942013-01-15 22:59:42 +0000597 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000598 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000599
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000600 // ".dcb"
601 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
602 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
Petr Hosek85b2f672016-09-23 21:53:36 +0000603 // ".ds"
604 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000605
Eli Bendersky17233942013-01-15 22:59:42 +0000606 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000607 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000608
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000609 /// Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000610 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000611 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000612
Jim Grosbach4b905842013-09-20 23:08:21 +0000613 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000614
Jim Grosbach4b905842013-09-20 23:08:21 +0000615 bool parseDirectiveAbort(); // ".abort"
616 bool parseDirectiveInclude(); // ".include"
617 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000618
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000619 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
620 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000621 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000622 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000623 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000624 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000625 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
626 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000627 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000628 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
629 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
630 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
631 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000632 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000633
Jim Grosbach4b905842013-09-20 23:08:21 +0000634 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000635 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000636
Rafael Espindola34b9c512012-06-03 23:57:14 +0000637 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000638 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
639 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000640 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000641 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000642 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
643 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
644 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000645
Chad Rosierc7f552c2013-02-12 21:33:51 +0000646 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000647 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000648 size_t Len);
649
650 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000651 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000652
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000653 // "end"
654 bool parseDirectiveEnd(SMLoc DirectiveLoc);
655
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000656 // ".err" or ".error"
657 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000658
Nico Weber404012b2014-07-24 16:26:06 +0000659 // ".warning"
660 bool parseDirectiveWarning(SMLoc DirectiveLoc);
661
Coby Tayree01e53202017-10-02 14:36:31 +0000662 // .print <double-quotes-string>
663 bool parseDirectivePrint(SMLoc DirectiveLoc);
664
Peter Collingbourne3e227332018-07-17 22:17:18 +0000665 // Directives to support address-significance tables.
666 bool parseDirectiveAddrsig();
667 bool parseDirectiveAddrsigSym();
668
Eli Bendersky17233942013-01-15 22:59:42 +0000669 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000670};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000671
672} // end anonymous namespace
Daniel Dunbar86033402010-07-12 17:54:38 +0000673
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000674namespace llvm {
675
676extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000677extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000678extern MCAsmParserExtension *createCOFFAsmParser();
Wouter van Oortmerssencc75e772018-11-12 20:15:01 +0000679extern MCAsmParserExtension *createWasmAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000680
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000681} // end namespace llvm
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000682
Chris Lattnerc35681b2010-01-19 19:46:13 +0000683enum { DEFAULT_ADDRSPACE = 0 };
684
David Blaikie9f380a32015-03-16 18:06:57 +0000685AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000686 const MCAsmInfo &MAI, unsigned CB = 0)
David Blaikie9f380a32015-03-16 18:06:57 +0000687 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000688 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
Nirav Dave2364748a2016-09-16 18:30:20 +0000689 HadError = false;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000690 // Save the old handler.
691 SavedDiagHandler = SrcMgr.getDiagHandler();
692 SavedDiagContext = SrcMgr.getDiagContext();
693 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000694 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000695 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000696
Daniel Dunbarc5011082010-07-12 18:12:02 +0000697 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000698 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
699 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000700 PlatformParser.reset(createCOFFAsmParser());
701 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000702 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000703 PlatformParser.reset(createDarwinAsmParser());
704 IsDarwin = true;
705 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000706 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000707 PlatformParser.reset(createELFAsmParser());
708 break;
Dan Gohman18eafb62017-02-22 01:23:18 +0000709 case MCObjectFileInfo::IsWasm:
Wouter van Oortmerssencc75e772018-11-12 20:15:01 +0000710 PlatformParser.reset(createWasmAsmParser());
Dan Gohman18eafb62017-02-22 01:23:18 +0000711 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000712 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000713
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000714 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000715 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000716
717 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000718}
719
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000720AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000721 assert((HadError || ActiveMacros.empty()) &&
722 "Unexpected active macro instantiation!");
Sanne Wouda29338752017-02-08 14:48:05 +0000723
724 // Restore the saved diagnostics handler and context for use during
725 // finalization.
726 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000727}
728
Jim Grosbach4b905842013-09-20 23:08:21 +0000729void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000730 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000731 for (std::vector<MacroInstantiation *>::const_reverse_iterator
732 it = ActiveMacros.rbegin(),
733 ie = ActiveMacros.rend();
734 it != ie; ++it)
735 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000736 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000737}
738
Nirav Dave2364748a2016-09-16 18:30:20 +0000739void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
740 printPendingErrors();
741 printMessage(L, SourceMgr::DK_Note, Msg, Range);
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000742 printMacroInstantiations();
743}
744
Nirav Dave2364748a2016-09-16 18:30:20 +0000745bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000746 if(getTargetParser().getTargetOptions().MCNoWarn)
747 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000748 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Nirav Dave2364748a2016-09-16 18:30:20 +0000749 return Error(L, Msg, Range);
750 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000751 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000752 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000753}
754
Nirav Dave2364748a2016-09-16 18:30:20 +0000755bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000756 HadError = true;
Nirav Dave2364748a2016-09-16 18:30:20 +0000757 printMessage(L, SourceMgr::DK_Error, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000758 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000759 return true;
760}
761
Jim Grosbach4b905842013-09-20 23:08:21 +0000762bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000763 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000764 unsigned NewBuf =
765 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
766 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000767 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000768
Sean Callanan7a77eae2010-01-21 00:19:58 +0000769 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000770 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000771 return false;
772}
Daniel Dunbar43235712010-07-18 18:54:11 +0000773
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000774/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000775/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000776/// returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000777bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
778 const MCExpr *Count, SMLoc Loc) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000779 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000780 unsigned NewBuf =
781 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
782 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000783 return true;
784
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000785 // Pick up the bytes from the file and emit them.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000786 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
787 Bytes = Bytes.drop_front(Skip);
788 if (Count) {
789 int64_t Res;
Nirav Dave6c0665e2018-04-30 19:22:40 +0000790 if (!Count->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
Petr Hosek2f4ac442016-09-23 00:41:06 +0000791 return Error(Loc, "expected absolute expression");
792 if (Res < 0)
793 return Warning(Loc, "negative count has no effect");
794 Bytes = Bytes.take_front(Res);
795 }
796 getStreamer().EmitBytes(Bytes);
Kevin Enderby109f25c2011-12-14 21:47:48 +0000797 return false;
798}
799
Alp Tokera55b95b2014-07-06 10:33:31 +0000800void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
801 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000802 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
803 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000804}
805
Sean Callanan7a77eae2010-01-21 00:19:58 +0000806const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000807 if (Lexer.getTok().is(AsmToken::Error))
808 Error(Lexer.getErrLoc(), Lexer.getErr());
809
Nirav Dave53a72f42016-07-11 12:42:14 +0000810 // if it's a end of statement with a comment in it
811 if (getTok().is(AsmToken::EndOfStatement)) {
812 // if this is a line comment output it.
Nirav Dave670109d2017-06-09 14:04:03 +0000813 if (!getTok().getString().empty() && getTok().getString().front() != '\n' &&
Nirav Dave53a72f42016-07-11 12:42:14 +0000814 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
815 Out.addExplicitComment(Twine(getTok().getString()));
816 }
817
Sean Callanan7a77eae2010-01-21 00:19:58 +0000818 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000819
820 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000821 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000822 if (MAI.preserveAsmComments())
823 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000824 tok = &Lexer.Lex();
825 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000826
Sean Callanan7a77eae2010-01-21 00:19:58 +0000827 if (tok->is(AsmToken::Eof)) {
828 // If this is the end of an included file, pop the parent file off the
829 // include stack.
830 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
831 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000832 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000833 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000834 }
835 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000836
Sean Callanan7a77eae2010-01-21 00:19:58 +0000837 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000838}
839
Paul Robinson938d9a02018-03-22 15:48:01 +0000840bool AsmParser::enabledGenDwarfForAssembly() {
841 // Check whether the user specified -g.
842 if (!getContext().getGenDwarfForAssembly())
843 return false;
844 // If we haven't encountered any .file directives (which would imply that
845 // the assembler source was produced with debug info already) then emit one
846 // describing the assembler source file itself.
847 if (getContext().getGenDwarfFileNumber() == 0)
848 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
849 0, StringRef(), getContext().getMainFileName()));
850 return true;
851}
852
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000853bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000854 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000855 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000856 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000857
Chris Lattner36e02122009-06-21 20:54:55 +0000858 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000859 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000860
861 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000862 AsmCond StartingCondState = TheCondState;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000863 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000864
Kevin Enderby6469fc22011-11-01 22:27:22 +0000865 // If we are generating dwarf for assembly source files save the initial text
Paul Robinson938d9a02018-03-22 15:48:01 +0000866 // section. (Don't use enabledGenDwarfForAssembly() here, as we aren't
867 // emitting any actual debug info yet and haven't had a chance to parse any
868 // embedded .file directives.)
Kevin Enderby6469fc22011-11-01 22:27:22 +0000869 if (getContext().getGenDwarfForAssembly()) {
Eric Christopher445c9522016-10-14 05:47:37 +0000870 MCSection *Sec = getStreamer().getCurrentSectionOnly();
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000871 if (!Sec->getBeginSymbol()) {
872 MCSymbol *SectionStartSym = getContext().createTempSymbol();
873 getStreamer().EmitLabel(SectionStartSym);
874 Sec->setBeginSymbol(SectionStartSym);
875 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000876 bool InsertResult = getContext().addGenDwarfSection(Sec);
877 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000878 (void)InsertResult;
Kevin Enderby6469fc22011-11-01 22:27:22 +0000879 }
880
Chris Lattner73f36112009-07-02 21:53:43 +0000881 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000882 while (Lexer.isNot(AsmToken::Eof)) {
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000883 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000884 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000885 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000886
Nirav Dave2364748a2016-09-16 18:30:20 +0000887 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
888 // for printing ErrMsg via Lex() only if no (presumably better) parser error
889 // exists.
890 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
Nirav Dave1180e6892016-06-02 17:15:05 +0000891 Lex();
892 }
893
Nirav Dave2364748a2016-09-16 18:30:20 +0000894 // parseStatement returned true so may need to emit an error.
895 printPendingErrors();
896
897 // Skipping to the next line if needed.
898 if (!getLexer().isAtStartOfStatement())
899 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000900 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000901
Nirav Dave2364748a2016-09-16 18:30:20 +0000902 // All errors should have been emitted.
903 assert(!hasPendingError() && "unexpected error from parseStatement");
904
Oliver Stannard21718282016-07-26 14:19:47 +0000905 getTargetParser().flushPendingInstructions(getStreamer());
906
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000907 if (TheCondState.TheCond != StartingCondState.TheCond ||
908 TheCondState.Ignore != StartingCondState.Ignore)
Nirav Dave2364748a2016-09-16 18:30:20 +0000909 printError(getTok().getLoc(), "unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000910 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000911 const auto &LineTables = getContext().getMCDwarfLineTables();
912 if (!LineTables.empty()) {
913 unsigned Index = 0;
914 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
915 if (File.Name.empty() && Index != 0)
Nirav Dave2364748a2016-09-16 18:30:20 +0000916 printError(getTok().getLoc(), "unassigned file number: " +
917 Twine(Index) +
918 " for .file directives");
David Blaikie8bf66c42014-04-01 07:35:52 +0000919 ++Index;
920 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000921 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000922
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000923 // Check to see that all assembler local symbols were actually defined.
924 // Targets that don't do subsections via symbols may not want this, though,
925 // so conservatively exclude them. Only do this if we're finalizing, though,
926 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000927 if (!NoFinalize) {
928 if (MAI.hasSubsectionsViaSymbols()) {
929 for (const auto &TableEntry : getContext().getSymbols()) {
930 MCSymbol *Sym = TableEntry.getValue();
931 // Variable symbols may not be marked as defined, so check those
932 // explicitly. If we know it's a variable, we have a definition for
933 // the purposes of this check.
934 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
935 // FIXME: We would really like to refer back to where the symbol was
936 // first referenced for a source location. We need to add something
937 // to track that. Currently, we just point to the end of the file.
Nirav Dave2364748a2016-09-16 18:30:20 +0000938 printError(getTok().getLoc(), "assembler local symbol '" +
939 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000940 }
941 }
942
943 // Temporary symbols like the ones for directional jumps don't go in the
944 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000945 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
946 if (std::get<2>(LocSym)->isUndefined()) {
947 // Reset the state of any "# line file" directives we've seen to the
948 // context as it was at the diagnostic site.
949 CppHashInfo = std::get<1>(LocSym);
Nirav Dave2364748a2016-09-16 18:30:20 +0000950 printError(std::get<0>(LocSym), "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000951 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000952 }
953 }
954
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000955 // Finalize the output stream if there are no errors and if the client wants
956 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000957 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000958 Out.Finish();
959
Oliver Stannard07b43d32015-11-17 09:58:07 +0000960 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000961}
962
Nirav Davef43cc9f2016-10-10 15:24:54 +0000963bool AsmParser::checkForValidSection() {
Eric Christopher445c9522016-10-14 05:47:37 +0000964 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000965 Out.InitSections(false);
Nirav Davef43cc9f2016-10-10 15:24:54 +0000966 return Error(getTok().getLoc(),
967 "expected section directive before assembly directive");
Daniel Dunbare5444a82010-09-09 22:42:59 +0000968 }
Nirav Davef43cc9f2016-10-10 15:24:54 +0000969 return false;
Daniel Dunbare5444a82010-09-09 22:42:59 +0000970}
971
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000972/// Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000973void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000974 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000975 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000976
Chris Lattnere5074c42009-06-22 01:29:09 +0000977 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000978 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000979 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000980}
981
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000982StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000983 const char *Start = getTok().getLoc().getPointer();
984
Jim Grosbach4b905842013-09-20 23:08:21 +0000985 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000986 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000987
988 const char *End = getTok().getLoc().getPointer();
989 return StringRef(Start, End - Start);
990}
Chris Lattner78db3622009-06-22 05:51:26 +0000991
Jim Grosbach4b905842013-09-20 23:08:21 +0000992StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000993 const char *Start = getTok().getLoc().getPointer();
994
995 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000996 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000997 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000998
999 const char *End = getTok().getLoc().getPointer();
1000 return StringRef(Start, End - Start);
1001}
1002
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001003/// Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001004/// NOTE: This assumes the leading '(' has already been consumed.
1005///
1006/// parenexpr ::= expr)
1007///
Jim Grosbach4b905842013-09-20 23:08:21 +00001008bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1009 if (parseExpression(Res))
1010 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001011 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +00001012 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001013 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001014 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +00001015 return false;
1016}
Chris Lattner78db3622009-06-22 05:51:26 +00001017
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001018/// Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001019/// NOTE: This assumes the leading '[' has already been consumed.
1020///
1021/// bracketexpr ::= expr]
1022///
Jim Grosbach4b905842013-09-20 23:08:21 +00001023bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1024 if (parseExpression(Res))
1025 return true;
Nirav Davea645433c2016-07-18 15:24:03 +00001026 EndLoc = getTok().getEndLoc();
1027 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
1028 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001029 return false;
1030}
1031
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001032/// Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001033/// primaryexpr ::= (parenexpr
1034/// primaryexpr ::= symbol
1035/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +00001036/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +00001037/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +00001038bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001039 SMLoc FirstTokenLoc = getLexer().getLoc();
1040 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
1041 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +00001042 default:
1043 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +00001044 // If we have an error assume that we've already handled it.
1045 case AsmToken::Error:
1046 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001047 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001048 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001049 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001050 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001051 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001052 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +00001053 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +00001054 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00001055 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +00001056 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +00001057 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001058 if (parseIdentifier(Identifier)) {
Nirav Daved0463322016-10-12 13:58:07 +00001059 // We may have failed but $ may be a valid token.
1060 if (getTok().is(AsmToken::Dollar)) {
David Majnemer0c58bc62013-09-25 10:47:21 +00001061 if (Lexer.getMAI().getDollarIsPC()) {
Nirav Daved0463322016-10-12 13:58:07 +00001062 Lex();
David Majnemer0c58bc62013-09-25 10:47:21 +00001063 // This is a '$' reference, which references the current PC. Emit a
1064 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001065 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +00001066 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001067 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +00001068 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +00001069 EndLoc = FirstTokenLoc;
1070 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +00001071 }
1072 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +00001073 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001074 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001075 // Parse symbol variant
1076 std::pair<StringRef, StringRef> Split;
1077 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +00001078 if (FirstTokenKind == AsmToken::String) {
1079 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +00001080 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +00001081 SMLoc AtLoc = getLexer().getLoc();
1082 StringRef VName;
1083 if (parseIdentifier(VName))
1084 return Error(AtLoc, "expected symbol variant after '@'");
1085
1086 Split = std::make_pair(Identifier, VName);
1087 }
1088 } else {
1089 Split = Identifier.split('@');
1090 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001091 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +00001092 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +00001093 StringRef VName;
1094 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +00001095 // eat ')'.
1096 if (parseToken(AsmToken::RParen,
1097 "unexpected token in variant, expected ')'"))
1098 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +00001099 Split = std::make_pair(Identifier, VName);
1100 }
Daniel Dunbar24764322010-08-24 19:13:42 +00001101
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001102 EndLoc = SMLoc::getFromPointer(Identifier.end());
1103
Daniel Dunbard20cda02009-10-16 01:34:54 +00001104 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +00001105 StringRef SymbolName = Identifier;
Weiming Zhaocf26d562016-12-01 18:00:36 +00001106 if (SymbolName.empty())
Francis Visoiu Mistrih627d1462018-10-08 10:28:11 +00001107 return Error(getLexer().getLoc(), "expected a symbol reference");
Weiming Zhaocf26d562016-12-01 18:00:36 +00001108
Hans Wennborgce69d772013-10-18 20:46:28 +00001109 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +00001110
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001111 // Lookup the symbol variant if used.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001112 if (!Split.second.empty()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001113 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +00001114 if (Variant != MCSymbolRefExpr::VK_Invalid) {
1115 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +00001116 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +00001117 Variant = MCSymbolRefExpr::VK_None;
1118 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +00001119 return Error(SMLoc::getFromPointer(Split.second.begin()),
1120 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001121 }
1122 }
Daniel Dunbar55992562010-03-15 23:51:06 +00001123
Jim Grosbach6f482002015-05-18 18:43:14 +00001124 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +00001125
Daniel Dunbard20cda02009-10-16 01:34:54 +00001126 // If this is an absolute variable reference, substitute it now to preserve
1127 // semantics in the face of reassignment.
Nirav Dave05b58912018-06-05 15:13:39 +00001128 if (Sym->isVariable()) {
1129 auto V = Sym->getVariableValue(/*SetUsed*/ false);
Nirav Daveb1f9e4d2018-09-17 20:34:26 +00001130 bool DoInline = isa<MCConstantExpr>(V) && !Variant;
Nirav Dave05b58912018-06-05 15:13:39 +00001131 if (auto TV = dyn_cast<MCTargetExpr>(V))
1132 DoInline = TV->inlineAssignedExpr();
1133 if (DoInline) {
1134 if (Variant)
1135 return Error(EndLoc, "unexpected modifier on variable reference");
1136 Res = Sym->getVariableValue(/*SetUsed*/ false);
1137 return false;
1138 }
Daniel Dunbard20cda02009-10-16 01:34:54 +00001139 }
1140
1141 // Otherwise create a symbol ref.
Chad Rosier9245e122017-01-19 20:06:32 +00001142 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
Chris Lattner78db3622009-06-22 05:51:26 +00001143 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001144 }
David Woodhousef42a6662014-02-01 16:20:54 +00001145 case AsmToken::BigNum:
1146 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001147 case AsmToken::Integer: {
1148 SMLoc Loc = getTok().getLoc();
1149 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001150 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001151 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001152 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001153 // Look for 'b' or 'f' following an Integer as a directional label
1154 if (Lexer.getKind() == AsmToken::Identifier) {
1155 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001156 // Lookup the symbol variant if used.
1157 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1158 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1159 if (Split.first.size() != IDVal.size()) {
1160 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001161 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001162 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001163 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001164 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001165 if (IDVal == "f" || IDVal == "b") {
1166 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001167 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001168 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001169 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001170 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001171 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001172 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001173 Lex(); // Eat identifier.
1174 }
1175 }
Chris Lattner78db3622009-06-22 05:51:26 +00001176 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001177 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001178 case AsmToken::Real: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001179 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001180 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001181 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001182 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001183 Lex(); // Eat token.
1184 return false;
1185 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001186 case AsmToken::Dot: {
1187 // This is a '.' reference, which references the current PC. Emit a
1188 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001189 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001190 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001191 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001192 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001193 Lex(); // Eat identifier.
1194 return false;
1195 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001196 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001197 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001198 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001199 case AsmToken::LBrac:
1200 if (!PlatformParser->HasBracketExpressions())
1201 return TokError("brackets expression not supported on this target");
1202 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001203 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001204 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001205 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001206 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001207 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001208 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001209 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001210 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001211 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001212 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001213 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001214 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001215 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001216 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001217 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001218 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001219 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001220 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001221 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001222 // MIPS unary expression operators. The lexer won't generate these tokens if
1223 // MCAsmInfo::HasMipsExpressions is false for the target.
1224 case AsmToken::PercentCall16:
1225 case AsmToken::PercentCall_Hi:
1226 case AsmToken::PercentCall_Lo:
1227 case AsmToken::PercentDtprel_Hi:
1228 case AsmToken::PercentDtprel_Lo:
1229 case AsmToken::PercentGot:
1230 case AsmToken::PercentGot_Disp:
1231 case AsmToken::PercentGot_Hi:
1232 case AsmToken::PercentGot_Lo:
1233 case AsmToken::PercentGot_Ofst:
1234 case AsmToken::PercentGot_Page:
1235 case AsmToken::PercentGottprel:
1236 case AsmToken::PercentGp_Rel:
1237 case AsmToken::PercentHi:
1238 case AsmToken::PercentHigher:
1239 case AsmToken::PercentHighest:
1240 case AsmToken::PercentLo:
1241 case AsmToken::PercentNeg:
1242 case AsmToken::PercentPcrel_Hi:
1243 case AsmToken::PercentPcrel_Lo:
1244 case AsmToken::PercentTlsgd:
1245 case AsmToken::PercentTlsldm:
1246 case AsmToken::PercentTprel_Hi:
1247 case AsmToken::PercentTprel_Lo:
1248 Lex(); // Eat the operator.
1249 if (Lexer.isNot(AsmToken::LParen))
1250 return TokError("expected '(' after operator");
1251 Lex(); // Eat the operator.
1252 if (parseExpression(Res, EndLoc))
1253 return true;
1254 if (Lexer.isNot(AsmToken::RParen))
1255 return TokError("expected ')'");
1256 Lex(); // Eat the operator.
1257 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1258 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001259 }
1260}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001261
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001262bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001263 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001264 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001265}
1266
Daniel Dunbar55f16672010-09-17 02:47:07 +00001267const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001268AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001269 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001270 // Ask the target implementation about this expression first.
1271 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1272 if (NewE)
1273 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001274 // Recurse over the given expression, rebuilding it to apply the given variant
1275 // if there is exactly one symbol.
1276 switch (E->getKind()) {
1277 case MCExpr::Target:
1278 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001279 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001280
1281 case MCExpr::SymbolRef: {
1282 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1283
1284 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001285 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1286 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001287 return E;
1288 }
1289
Jim Grosbach13760bd2015-05-30 01:25:56 +00001290 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001291 }
1292
1293 case MCExpr::Unary: {
1294 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001295 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001296 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001297 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001298 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001299 }
1300
1301 case MCExpr::Binary: {
1302 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001303 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1304 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001305
1306 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001307 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001308
Jim Grosbach4b905842013-09-20 23:08:21 +00001309 if (!LHS)
1310 LHS = BE->getLHS();
1311 if (!RHS)
1312 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001313
Jim Grosbach13760bd2015-05-30 01:25:56 +00001314 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001315 }
1316 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001317
Craig Toppera2886c22012-02-07 05:05:23 +00001318 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001319}
1320
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001321/// This function checks if the next token is <string> type or arithmetic.
1322/// string that begin with character '<' must end with character '>'.
1323/// otherwise it is arithmetics.
1324/// If the function returns a 'true' value,
1325/// the End argument will be filled with the last location pointed to the '>'
1326/// character.
1327
Craig Topper3da977b2018-09-25 19:37:35 +00001328/// There is a gap between the AltMacro's documentation and the single quote
1329/// implementation. GCC does not fully support this feature and so we will not
1330/// support it.
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001331/// TODO: Adding single quote as a string.
Craig Topperd2aab832018-09-25 20:13:55 +00001332static bool isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc) {
Craig Topperc06ee832018-09-25 18:33:00 +00001333 assert((StrLoc.getPointer() != nullptr) &&
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001334 "Argument to the function cannot be a NULL value");
1335 const char *CharPtr = StrLoc.getPointer();
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001336 while ((*CharPtr != '>') && (*CharPtr != '\n') && (*CharPtr != '\r') &&
1337 (*CharPtr != '\0')) {
1338 if (*CharPtr == '!')
1339 CharPtr++;
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001340 CharPtr++;
1341 }
1342 if (*CharPtr == '>') {
1343 EndLoc = StrLoc.getFromPointer(CharPtr + 1);
1344 return true;
1345 }
1346 return false;
1347}
1348
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001349/// creating a string without the escape characters '!'.
Craig Topperd2aab832018-09-25 20:13:55 +00001350static std::string altMacroString(StringRef AltMacroStr) {
1351 std::string Res;
Michael Zuckermanff298792017-05-10 14:00:57 +00001352 for (size_t Pos = 0; Pos < AltMacroStr.size(); Pos++) {
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001353 if (AltMacroStr[Pos] == '!')
1354 Pos++;
1355 Res += AltMacroStr[Pos];
1356 }
Craig Topperd2aab832018-09-25 20:13:55 +00001357 return Res;
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001358}
1359
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001360/// Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001361///
Jim Grosbachbd164242011-08-20 16:24:13 +00001362/// expr ::= expr &&,|| expr -> lowest.
1363/// expr ::= expr |,^,&,! expr
1364/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1365/// expr ::= expr <<,>> expr
1366/// expr ::= expr +,- expr
1367/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001368/// expr ::= primaryexpr
1369///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001370bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001371 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001372 Res = nullptr;
Nirav Dave7fd992a2018-08-16 16:31:14 +00001373 if (getTargetParser().parsePrimaryExpr(Res, EndLoc) ||
1374 parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001375 return true;
1376
Daniel Dunbar55f16672010-09-17 02:47:07 +00001377 // As a special case, we support 'a op b @ modifier' by rewriting the
1378 // expression to include the modifier. This is inefficient, but in general we
1379 // expect users to use 'a@modifier op b'.
1380 if (Lexer.getKind() == AsmToken::At) {
1381 Lex();
1382
1383 if (Lexer.isNot(AsmToken::Identifier))
1384 return TokError("unexpected symbol modifier following '@'");
1385
1386 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001387 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001388 if (Variant == MCSymbolRefExpr::VK_Invalid)
1389 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1390
Jim Grosbach4b905842013-09-20 23:08:21 +00001391 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001392 if (!ModifiedRes) {
1393 return TokError("invalid modifier '" + getTok().getIdentifier() +
1394 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001395 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001396
Daniel Dunbar55f16672010-09-17 02:47:07 +00001397 Res = ModifiedRes;
1398 Lex();
1399 }
1400
Nirav Dave6c0665e2018-04-30 19:22:40 +00001401 // Try to constant fold it up front, if possible. Do not exploit
1402 // assembler here.
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001403 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001404 if (Res->evaluateAsAbsolute(Value))
1405 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001406
1407 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001408}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001409
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001410bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001411 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001412 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001413}
1414
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001415bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1416 SMLoc &EndLoc) {
1417 if (parseParenExpr(Res, EndLoc))
1418 return true;
1419
1420 for (; ParenDepth > 0; --ParenDepth) {
1421 if (parseBinOpRHS(1, Res, EndLoc))
1422 return true;
1423
1424 // We don't Lex() the last RParen.
1425 // This is the same behavior as parseParenExpression().
1426 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001427 EndLoc = getTok().getEndLoc();
1428 if (parseToken(AsmToken::RParen,
1429 "expected ')' in parentheses expression"))
1430 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001431 }
1432 }
1433 return false;
1434}
1435
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001436bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001437 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001438
Daniel Dunbar75630b32009-06-30 02:10:03 +00001439 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001440 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001441 return true;
1442
Nirav Dave6c0665e2018-04-30 19:22:40 +00001443 if (!Expr->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001444 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001445
1446 return false;
1447}
1448
David Majnemer0993e0b2015-10-26 03:15:34 +00001449static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1450 MCBinaryExpr::Opcode &Kind,
1451 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001452 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001453 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001454 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001455
Jim Grosbach4b905842013-09-20 23:08:21 +00001456 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001457 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001458 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001459 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001460 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001461 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001462 return 1;
1463
Jim Grosbach4b905842013-09-20 23:08:21 +00001464 // Low Precedence: |, &, ^
1465 //
1466 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001467 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001468 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001469 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001470 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001471 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001472 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001473 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001474 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001475 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001476
Jim Grosbach4b905842013-09-20 23:08:21 +00001477 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001478 case AsmToken::EqualEqual:
1479 Kind = MCBinaryExpr::EQ;
1480 return 3;
1481 case AsmToken::ExclaimEqual:
1482 case AsmToken::LessGreater:
1483 Kind = MCBinaryExpr::NE;
1484 return 3;
1485 case AsmToken::Less:
1486 Kind = MCBinaryExpr::LT;
1487 return 3;
1488 case AsmToken::LessEqual:
1489 Kind = MCBinaryExpr::LTE;
1490 return 3;
1491 case AsmToken::Greater:
1492 Kind = MCBinaryExpr::GT;
1493 return 3;
1494 case AsmToken::GreaterEqual:
1495 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001496 return 3;
1497
Jim Grosbach4b905842013-09-20 23:08:21 +00001498 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001499 case AsmToken::LessLess:
1500 Kind = MCBinaryExpr::Shl;
1501 return 4;
1502 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001503 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001504 return 4;
1505
Jim Grosbach4b905842013-09-20 23:08:21 +00001506 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001507 case AsmToken::Plus:
1508 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001509 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001510 case AsmToken::Minus:
1511 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001512 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001513
Jim Grosbach4b905842013-09-20 23:08:21 +00001514 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001515 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001516 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001517 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001518 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001519 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001520 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001521 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001522 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001523 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001524 }
1525}
1526
David Majnemer0993e0b2015-10-26 03:15:34 +00001527static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1528 MCBinaryExpr::Opcode &Kind,
1529 bool ShouldUseLogicalShr) {
1530 switch (K) {
1531 default:
1532 return 0; // not a binop.
1533
1534 // Lowest Precedence: &&, ||
1535 case AsmToken::AmpAmp:
1536 Kind = MCBinaryExpr::LAnd;
1537 return 2;
1538 case AsmToken::PipePipe:
1539 Kind = MCBinaryExpr::LOr;
1540 return 1;
1541
1542 // Low Precedence: ==, !=, <>, <, <=, >, >=
1543 case AsmToken::EqualEqual:
1544 Kind = MCBinaryExpr::EQ;
1545 return 3;
1546 case AsmToken::ExclaimEqual:
1547 case AsmToken::LessGreater:
1548 Kind = MCBinaryExpr::NE;
1549 return 3;
1550 case AsmToken::Less:
1551 Kind = MCBinaryExpr::LT;
1552 return 3;
1553 case AsmToken::LessEqual:
1554 Kind = MCBinaryExpr::LTE;
1555 return 3;
1556 case AsmToken::Greater:
1557 Kind = MCBinaryExpr::GT;
1558 return 3;
1559 case AsmToken::GreaterEqual:
1560 Kind = MCBinaryExpr::GTE;
1561 return 3;
1562
1563 // Low Intermediate Precedence: +, -
1564 case AsmToken::Plus:
1565 Kind = MCBinaryExpr::Add;
1566 return 4;
1567 case AsmToken::Minus:
1568 Kind = MCBinaryExpr::Sub;
1569 return 4;
1570
1571 // High Intermediate Precedence: |, &, ^
1572 //
1573 // FIXME: gas seems to support '!' as an infix operator?
1574 case AsmToken::Pipe:
1575 Kind = MCBinaryExpr::Or;
1576 return 5;
1577 case AsmToken::Caret:
1578 Kind = MCBinaryExpr::Xor;
1579 return 5;
1580 case AsmToken::Amp:
1581 Kind = MCBinaryExpr::And;
1582 return 5;
1583
1584 // Highest Precedence: *, /, %, <<, >>
1585 case AsmToken::Star:
1586 Kind = MCBinaryExpr::Mul;
1587 return 6;
1588 case AsmToken::Slash:
1589 Kind = MCBinaryExpr::Div;
1590 return 6;
1591 case AsmToken::Percent:
1592 Kind = MCBinaryExpr::Mod;
1593 return 6;
1594 case AsmToken::LessLess:
1595 Kind = MCBinaryExpr::Shl;
1596 return 6;
1597 case AsmToken::GreaterGreater:
1598 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1599 return 6;
1600 }
1601}
1602
1603unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1604 MCBinaryExpr::Opcode &Kind) {
1605 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1606 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1607 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1608}
1609
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001610/// Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001611/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001612bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001613 SMLoc &EndLoc) {
Chad Rosier9245e122017-01-19 20:06:32 +00001614 SMLoc StartLoc = Lexer.getLoc();
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001615 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001616 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001617 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001618
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001619 // If the next token is lower precedence than we are allowed to eat, return
1620 // successfully with what we ate already.
1621 if (TokPrec < Precedence)
1622 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001623
Sean Callanan686ed8d2010-01-19 20:22:31 +00001624 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001625
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001626 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001627 const MCExpr *RHS;
Nirav Dave7fd992a2018-08-16 16:31:14 +00001628 if (getTargetParser().parsePrimaryExpr(RHS, EndLoc))
Jim Grosbach4b905842013-09-20 23:08:21 +00001629 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001630
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001631 // If BinOp binds less tightly with RHS than the operator after RHS, let
1632 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001633 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001634 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001635 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1636 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001637
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001638 // Merge LHS and RHS according to operator.
Chad Rosier9245e122017-01-19 20:06:32 +00001639 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001640 }
1641}
1642
Chris Lattner36e02122009-06-21 20:54:55 +00001643/// ParseStatement:
1644/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001645/// ::= Label* Directive ...Operands... EndOfStatement
1646/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001647bool AsmParser::parseStatement(ParseStatementInfo &Info,
1648 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001649 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001650 // Eat initial spaces and comments
1651 while (Lexer.is(AsmToken::Space))
1652 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001653 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001654 // if this is a line comment we can drop it safely
Nirav Dave670109d2017-06-09 14:04:03 +00001655 if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
Nirav Davefd910412016-06-17 16:06:17 +00001656 getTok().getString().front() == '\n')
1657 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001658 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001659 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001660 }
Nirav Davefd910412016-06-17 16:06:17 +00001661 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001662 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001663 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001664 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001665 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001666 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001667 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001668 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001669 if (Lexer.is(AsmToken::Integer)) {
1670 LocalLabelVal = getTok().getIntVal();
1671 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001672 if (!TheCondState.Ignore) {
1673 Lex(); // always eat a token
1674 return Error(IDLoc, "unexpected token at start of statement");
1675 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001676 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001677 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001678 IDVal = getTok().getString();
1679 Lex(); // Consume the integer token to be used as an identifier token.
1680 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001681 if (!TheCondState.Ignore) {
1682 Lex(); // always eat a token
1683 return Error(IDLoc, "unexpected token at start of statement");
1684 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001685 }
1686 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001687 } else if (Lexer.is(AsmToken::Dot)) {
1688 // Treat '.' as a valid identifier in this context.
1689 Lex();
1690 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001691 } else if (Lexer.is(AsmToken::LCurly)) {
1692 // Treat '{' as a valid identifier in this context.
1693 Lex();
1694 IDVal = "{";
1695
1696 } else if (Lexer.is(AsmToken::RCurly)) {
1697 // Treat '}' as a valid identifier in this context.
1698 Lex();
1699 IDVal = "}";
Yonghong Song06ff6552017-09-12 17:55:23 +00001700 } else if (Lexer.is(AsmToken::Star) &&
1701 getTargetParser().starIsStartOfStatement()) {
1702 // Accept '*' as a valid start of statement.
1703 Lex();
1704 IDVal = "*";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001705 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001706 if (!TheCondState.Ignore) {
1707 Lex(); // always eat a token
1708 return Error(IDLoc, "unexpected token at start of statement");
1709 }
Chris Lattner926885c2010-04-17 18:14:27 +00001710 IDVal = "";
1711 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001712
Chris Lattner926885c2010-04-17 18:14:27 +00001713 // Handle conditional assembly here before checking for skipping. We
1714 // have to do this so that .endif isn't skipped in a ".if 0" block for
1715 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001716 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001717 DirectiveKindMap.find(IDVal);
1718 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1719 ? DK_NO_DIRECTIVE
1720 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001721 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001722 default:
1723 break;
1724 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001725 case DK_IFEQ:
1726 case DK_IFGE:
1727 case DK_IFGT:
1728 case DK_IFLE:
1729 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001730 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001731 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001732 case DK_IFB:
1733 return parseDirectiveIfb(IDLoc, true);
1734 case DK_IFNB:
1735 return parseDirectiveIfb(IDLoc, false);
1736 case DK_IFC:
1737 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001738 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001739 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001740 case DK_IFNC:
1741 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001742 case DK_IFNES:
1743 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001744 case DK_IFDEF:
1745 return parseDirectiveIfdef(IDLoc, true);
1746 case DK_IFNDEF:
1747 case DK_IFNOTDEF:
1748 return parseDirectiveIfdef(IDLoc, false);
1749 case DK_ELSEIF:
1750 return parseDirectiveElseIf(IDLoc);
1751 case DK_ELSE:
1752 return parseDirectiveElse(IDLoc);
1753 case DK_ENDIF:
1754 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001755 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001756
Eli Bendersky88024712013-01-16 19:32:36 +00001757 // Ignore the statement if in the middle of inactive conditional
1758 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001759 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001760 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001761 return false;
1762 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001763
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001764 // FIXME: Recurse on local labels?
1765
1766 // See what kind of statement we have.
1767 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001768 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001769 if (!getTargetParser().isLabel(ID))
1770 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001771 if (checkForValidSection())
1772 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001773
Chris Lattner36e02122009-06-21 20:54:55 +00001774 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001775 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001776
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001777 // Diagnose attempt to use '.' as a label.
1778 if (IDVal == ".")
1779 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1780
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001781 // Diagnose attempt to use a variable as a label.
1782 //
1783 // FIXME: Diagnostics. Note the location of the definition as a label.
1784 // FIXME: This doesn't diagnose assignment to a symbol which has been
1785 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001786 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001787 if (LocalLabelVal == -1) {
1788 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001789 StringRef RewrittenLabel =
1790 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001791 assert(!RewrittenLabel.empty() &&
Nico Weber67e715f2015-06-19 23:43:47 +00001792 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001793 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1794 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001795 IDVal = RewrittenLabel;
1796 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001797 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001798 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001799 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
Nirav Dave9263ae32016-08-02 19:17:54 +00001800 // End of Labels should be treated as end of line for lexing
1801 // purposes but that information is not available to the Lexer who
1802 // does not understand Labels. This may cause us to see a Hash
1803 // here instead of a preprocessor line comment.
1804 if (getTok().is(AsmToken::Hash)) {
1805 StringRef CommentStr = parseStringToEndOfStatement();
1806 Lexer.Lex();
1807 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1808 }
1809
Nirav Dave8ea792d2016-07-13 14:03:12 +00001810 // Consume any end of statement token, if present, to avoid spurious
1811 // AddBlankLine calls().
1812 if (getTok().is(AsmToken::EndOfStatement)) {
1813 Lex();
1814 }
1815
Maya Madhavanec1efe42018-09-20 05:11:42 +00001816 getTargetParser().doBeforeLabelEmit(Sym);
1817
Daniel Dunbare73b2672009-08-26 22:13:22 +00001818 // Emit the label.
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00001819 if (!getTargetParser().isParsingInlineAsm())
Rafael Espindolabe991572017-02-10 15:13:12 +00001820 Out.EmitLabel(Sym, IDLoc);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001821
Kevin Enderbye7739d42011-12-09 18:09:40 +00001822 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001823 // info to make a dwarf label entry for this label if needed.
Paul Robinson938d9a02018-03-22 15:48:01 +00001824 if (enabledGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001825 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1826 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001827
Tim Northover1744d0a2013-10-25 12:49:50 +00001828 getTargetParser().onLabelParsed(Sym);
1829
Eli Friedman0f4871d2012-10-22 23:58:19 +00001830 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001831 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001832
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001833 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001834 if (!getTargetParser().equalIsAsmAssignment())
1835 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001836 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001837 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001838
Nirav Dave7fd992a2018-08-16 16:31:14 +00001839 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001840
1841 default: // Normal instruction or directive.
1842 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001843 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001844
1845 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001846 if (areMacrosEnabled())
Rafael Espindola22c38a02018-02-14 16:34:27 +00001847 if (const MCAsmMacro *M = getContext().lookupMacro(IDVal)) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001848 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001849 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001850
Michael J. Spencer530ce852010-10-09 11:00:50 +00001851 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001852
Eli Bendersky17233942013-01-15 22:59:42 +00001853 // Directives start with "."
Ana Pazos353f67a2018-08-25 01:34:32 +00001854 if (IDVal.startswith(".") && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001855 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001856 //
Eli Bendersky17233942013-01-15 22:59:42 +00001857 // 1. The target-specific assembly parser. Some directives are target
1858 // specific or may potentially behave differently on certain targets.
1859 // 2. Asm parser extensions. For example, platform-specific parsers
1860 // (like the ELF parser) register themselves as extensions.
1861 // 3. The generic directive parser implemented by this class. These are
1862 // all the directives that behave in a target and platform independent
1863 // manner, or at least have a default behavior that's shared between
1864 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001865
Oliver Stannard21718282016-07-26 14:19:47 +00001866 getTargetParser().flushPendingInstructions(getStreamer());
1867
Nirav Dave2364748a2016-09-16 18:30:20 +00001868 SMLoc StartTokLoc = getTok().getLoc();
1869 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1870
1871 if (hasPendingError())
1872 return true;
1873 // Currently the return value should be true if we are
1874 // uninterested but as this is at odds with the standard parsing
1875 // convention (return true = error) we have instances of a parsed
1876 // directive that fails returning true as an error. Catch these
1877 // cases as best as possible errors here.
1878 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1879 return true;
1880 // Return if we did some parsing or believe we succeeded.
1881 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001882 return false;
1883
Alp Tokercb402912014-01-24 17:20:08 +00001884 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001885 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001886 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1887 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001888 if (Handler.first)
1889 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1890
1891 // Finally, if no one else is interested in this directive, it must be
1892 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001893 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001894 default:
1895 break;
1896 case DK_SET:
1897 case DK_EQU:
1898 return parseDirectiveSet(IDVal, true);
1899 case DK_EQUIV:
1900 return parseDirectiveSet(IDVal, false);
1901 case DK_ASCII:
1902 return parseDirectiveAscii(IDVal, false);
1903 case DK_ASCIZ:
1904 case DK_STRING:
1905 return parseDirectiveAscii(IDVal, true);
1906 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001907 case DK_DC_B:
1908 return parseDirectiveValue(IDVal, 1);
1909 case DK_DC:
1910 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001911 case DK_SHORT:
1912 case DK_VALUE:
1913 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001914 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001915 case DK_LONG:
1916 case DK_INT:
1917 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001918 case DK_DC_L:
1919 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001920 case DK_QUAD:
1921 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001922 return parseDirectiveValue(IDVal, 8);
1923 case DK_DC_A:
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001924 return parseDirectiveValue(
1925 IDVal, getContext().getAsmInfo()->getCodePointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001926 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001927 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001928 case DK_SINGLE:
1929 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001930 case DK_DC_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001931 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
Jim Grosbach4b905842013-09-20 23:08:21 +00001932 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001933 case DK_DC_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001934 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
Jim Grosbach4b905842013-09-20 23:08:21 +00001935 case DK_ALIGN: {
1936 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1937 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1938 }
1939 case DK_ALIGN32: {
1940 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1941 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1942 }
1943 case DK_BALIGN:
1944 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1945 case DK_BALIGNW:
1946 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1947 case DK_BALIGNL:
1948 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1949 case DK_P2ALIGN:
1950 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1951 case DK_P2ALIGNW:
1952 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1953 case DK_P2ALIGNL:
1954 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1955 case DK_ORG:
1956 return parseDirectiveOrg();
1957 case DK_FILL:
1958 return parseDirectiveFill();
1959 case DK_ZERO:
1960 return parseDirectiveZero();
1961 case DK_EXTERN:
1962 eatToEndOfStatement(); // .extern is the default, ignore it.
1963 return false;
1964 case DK_GLOBL:
1965 case DK_GLOBAL:
1966 return parseDirectiveSymbolAttribute(MCSA_Global);
1967 case DK_LAZY_REFERENCE:
1968 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1969 case DK_NO_DEAD_STRIP:
1970 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1971 case DK_SYMBOL_RESOLVER:
1972 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1973 case DK_PRIVATE_EXTERN:
1974 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1975 case DK_REFERENCE:
1976 return parseDirectiveSymbolAttribute(MCSA_Reference);
1977 case DK_WEAK_DEFINITION:
1978 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1979 case DK_WEAK_REFERENCE:
1980 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1981 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1982 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1983 case DK_COMM:
1984 case DK_COMMON:
1985 return parseDirectiveComm(/*IsLocal=*/false);
1986 case DK_LCOMM:
1987 return parseDirectiveComm(/*IsLocal=*/true);
1988 case DK_ABORT:
1989 return parseDirectiveAbort();
1990 case DK_INCLUDE:
1991 return parseDirectiveInclude();
1992 case DK_INCBIN:
1993 return parseDirectiveIncbin();
1994 case DK_CODE16:
1995 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001996 return TokError(Twine(IDVal) +
1997 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001998 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001999 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00002000 case DK_IRP:
2001 return parseDirectiveIrp(IDLoc);
2002 case DK_IRPC:
2003 return parseDirectiveIrpc(IDLoc);
2004 case DK_ENDR:
2005 return parseDirectiveEndr(IDLoc);
2006 case DK_BUNDLE_ALIGN_MODE:
2007 return parseDirectiveBundleAlignMode();
2008 case DK_BUNDLE_LOCK:
2009 return parseDirectiveBundleLock();
2010 case DK_BUNDLE_UNLOCK:
2011 return parseDirectiveBundleUnlock();
2012 case DK_SLEB128:
2013 return parseDirectiveLEB128(true);
2014 case DK_ULEB128:
2015 return parseDirectiveLEB128(false);
2016 case DK_SPACE:
2017 case DK_SKIP:
2018 return parseDirectiveSpace(IDVal);
2019 case DK_FILE:
2020 return parseDirectiveFile(IDLoc);
2021 case DK_LINE:
2022 return parseDirectiveLine();
2023 case DK_LOC:
2024 return parseDirectiveLoc();
2025 case DK_STABS:
2026 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002027 case DK_CV_FILE:
2028 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00002029 case DK_CV_FUNC_ID:
2030 return parseDirectiveCVFuncId();
2031 case DK_CV_INLINE_SITE_ID:
2032 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002033 case DK_CV_LOC:
2034 return parseDirectiveCVLoc();
2035 case DK_CV_LINETABLE:
2036 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00002037 case DK_CV_INLINE_LINETABLE:
2038 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00002039 case DK_CV_DEF_RANGE:
2040 return parseDirectiveCVDefRange();
Reid Kleckner06d02d02018-09-07 21:30:52 +00002041 case DK_CV_STRING:
2042 return parseDirectiveCVString();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002043 case DK_CV_STRINGTABLE:
2044 return parseDirectiveCVStringTable();
2045 case DK_CV_FILECHECKSUMS:
2046 return parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00002047 case DK_CV_FILECHECKSUM_OFFSET:
2048 return parseDirectiveCVFileChecksumOffset();
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00002049 case DK_CV_FPO_DATA:
2050 return parseDirectiveCVFPOData();
Jim Grosbach4b905842013-09-20 23:08:21 +00002051 case DK_CFI_SECTIONS:
2052 return parseDirectiveCFISections();
2053 case DK_CFI_STARTPROC:
2054 return parseDirectiveCFIStartProc();
2055 case DK_CFI_ENDPROC:
2056 return parseDirectiveCFIEndProc();
2057 case DK_CFI_DEF_CFA:
2058 return parseDirectiveCFIDefCfa(IDLoc);
2059 case DK_CFI_DEF_CFA_OFFSET:
2060 return parseDirectiveCFIDefCfaOffset();
2061 case DK_CFI_ADJUST_CFA_OFFSET:
2062 return parseDirectiveCFIAdjustCfaOffset();
2063 case DK_CFI_DEF_CFA_REGISTER:
2064 return parseDirectiveCFIDefCfaRegister(IDLoc);
2065 case DK_CFI_OFFSET:
2066 return parseDirectiveCFIOffset(IDLoc);
2067 case DK_CFI_REL_OFFSET:
2068 return parseDirectiveCFIRelOffset(IDLoc);
2069 case DK_CFI_PERSONALITY:
2070 return parseDirectiveCFIPersonalityOrLsda(true);
2071 case DK_CFI_LSDA:
2072 return parseDirectiveCFIPersonalityOrLsda(false);
2073 case DK_CFI_REMEMBER_STATE:
2074 return parseDirectiveCFIRememberState();
2075 case DK_CFI_RESTORE_STATE:
2076 return parseDirectiveCFIRestoreState();
2077 case DK_CFI_SAME_VALUE:
2078 return parseDirectiveCFISameValue(IDLoc);
2079 case DK_CFI_RESTORE:
2080 return parseDirectiveCFIRestore(IDLoc);
2081 case DK_CFI_ESCAPE:
2082 return parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00002083 case DK_CFI_RETURN_COLUMN:
2084 return parseDirectiveCFIReturnColumn(IDLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +00002085 case DK_CFI_SIGNAL_FRAME:
2086 return parseDirectiveCFISignalFrame();
2087 case DK_CFI_UNDEFINED:
2088 return parseDirectiveCFIUndefined(IDLoc);
2089 case DK_CFI_REGISTER:
2090 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00002091 case DK_CFI_WINDOW_SAVE:
2092 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00002093 case DK_MACROS_ON:
2094 case DK_MACROS_OFF:
2095 return parseDirectiveMacrosOnOff(IDVal);
2096 case DK_MACRO:
2097 return parseDirectiveMacro(IDLoc);
Michael Zuckerman56704612017-05-01 13:20:12 +00002098 case DK_ALTMACRO:
2099 case DK_NOALTMACRO:
2100 return parseDirectiveAltmacro(IDVal);
Nico Weber155dccd12014-07-24 17:08:39 +00002101 case DK_EXITM:
2102 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00002103 case DK_ENDM:
2104 case DK_ENDMACRO:
2105 return parseDirectiveEndMacro(IDVal);
2106 case DK_PURGEM:
2107 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00002108 case DK_END:
2109 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00002110 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00002111 return parseDirectiveError(IDLoc, false);
2112 case DK_ERROR:
2113 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00002114 case DK_WARNING:
2115 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002116 case DK_RELOC:
2117 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002118 case DK_DCB:
2119 case DK_DCB_W:
2120 return parseDirectiveDCB(IDVal, 2);
2121 case DK_DCB_B:
2122 return parseDirectiveDCB(IDVal, 1);
2123 case DK_DCB_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002124 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002125 case DK_DCB_L:
2126 return parseDirectiveDCB(IDVal, 4);
2127 case DK_DCB_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002128 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
Petr Hosek731bb9c2016-08-23 21:34:53 +00002129 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002130 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00002131 return TokError(Twine(IDVal) +
2132 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00002133 case DK_DS:
2134 case DK_DS_W:
2135 return parseDirectiveDS(IDVal, 2);
2136 case DK_DS_B:
2137 return parseDirectiveDS(IDVal, 1);
2138 case DK_DS_D:
2139 return parseDirectiveDS(IDVal, 8);
2140 case DK_DS_L:
2141 case DK_DS_S:
2142 return parseDirectiveDS(IDVal, 4);
2143 case DK_DS_P:
2144 case DK_DS_X:
2145 return parseDirectiveDS(IDVal, 12);
Coby Tayree01e53202017-10-02 14:36:31 +00002146 case DK_PRINT:
2147 return parseDirectivePrint(IDLoc);
Peter Collingbourne3e227332018-07-17 22:17:18 +00002148 case DK_ADDRSIG:
2149 return parseDirectiveAddrsig();
2150 case DK_ADDRSIG_SYM:
2151 return parseDirectiveAddrsigSym();
Eli Friedman20b02642010-07-19 04:17:25 +00002152 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002153
Jim Grosbach758e0cc2012-05-01 18:38:27 +00002154 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00002155 }
Chris Lattner36e02122009-06-21 20:54:55 +00002156
Chad Rosierc7f552c2013-02-12 21:33:51 +00002157 // __asm _emit or __asm __emit
2158 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
2159 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002160 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00002161
2162 // __asm align
2163 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002164 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00002165
Coby Tayree3847be92017-04-04 17:57:23 +00002166 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
Michael Zuckerman02ecd432015-12-13 17:07:23 +00002167 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00002168 if (checkForValidSection())
2169 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00002170
Chris Lattner7cbfa442010-05-19 23:34:33 +00002171 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00002172 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00002173 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00002174 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
2175 Info.ParsedOperands);
2176 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00002177
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002178 // Dump the parsed representation, if requested.
2179 if (getShowParsedOperands()) {
2180 SmallString<256> Str;
2181 raw_svector_ostream OS(Str);
2182 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002183 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002184 if (i != 0)
2185 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002186 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002187 }
2188 OS << "]";
2189
Jim Grosbach4b905842013-09-20 23:08:21 +00002190 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002191 }
2192
Nirav Dave2364748a2016-09-16 18:30:20 +00002193 // Fail even if ParseInstruction erroneously returns false.
2194 if (hasPendingError() || ParseHadError)
2195 return true;
2196
Oliver Stannard8b273082014-06-19 15:52:37 +00002197 // If we are generating dwarf for the current section then generate a .loc
2198 // directive for the instruction.
Paul Robinson938d9a02018-03-22 15:48:01 +00002199 if (!ParseHadError && enabledGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002200 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002201 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002202 unsigned Line;
2203 if (ActiveMacros.empty())
2204 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2205 else
Frederic Riss16238d92015-06-25 21:57:33 +00002206 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2207 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002208
Eli Bendersky88024712013-01-16 19:32:36 +00002209 // If we previously parsed a cpp hash file line comment then make sure the
2210 // current Dwarf File is for the CppHashFilename if not then emit the
2211 // Dwarf File table for it and adjust the line number for the .loc.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00002212 if (!CppHashInfo.Filename.empty()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002213 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002214 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002215 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002216
Graydon Hoare54fe2082018-04-07 00:44:02 +00002217 unsigned CppHashLocLineNo =
2218 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Tim Northoverc0bef992016-04-13 19:46:54 +00002219 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002220 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002221
Jim Grosbach4b905842013-09-20 23:08:21 +00002222 getStreamer().EmitDwarfLocDirective(
2223 getContext().getGenDwarfFileNumber(), Line, 0,
2224 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2225 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002226 }
2227
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002228 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002229 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002230 uint64_t ErrorInfo;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00002231 if (getTargetParser().MatchAndEmitInstruction(
2232 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2233 getTargetParser().isParsingInlineAsm()))
Nirav Dave2364748a2016-09-16 18:30:20 +00002234 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002235 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002236 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002237}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002238
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002239// Parse and erase curly braces marking block start/end
Sam Cleggf009da22018-04-19 22:00:53 +00002240bool
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002241AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2242 // Identify curly brace marking block start/end
2243 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2244 return false;
2245
2246 SMLoc StartLoc = Lexer.getLoc();
2247 Lex(); // Eat the brace
2248 if (Lexer.is(AsmToken::EndOfStatement))
2249 Lex(); // Eat EndOfStatement following the brace
2250
2251 // Erase the block start/end brace from the output asm string
2252 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2253 StartLoc.getPointer());
2254 return true;
2255}
2256
Jim Grosbach4b905842013-09-20 23:08:21 +00002257/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002258/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002259bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002260 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002261 // Lexer only ever emits HashDirective if it fully formed if it's
2262 // done the checking already so this is an internal error.
2263 assert(getTok().is(AsmToken::Integer) &&
2264 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002265 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002266 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002267 assert(getTok().is(AsmToken::String) &&
2268 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002269 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002270 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002271
Kevin Enderby72553612011-09-13 23:45:18 +00002272 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002273 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002274
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002275 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002276 CppHashInfo.Loc = L;
2277 CppHashInfo.Filename = Filename;
2278 CppHashInfo.LineNumber = LineNumber;
2279 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002280 return false;
2281}
2282
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002283/// will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002284/// for the Filename and LineNo if any in the diagnostic.
2285void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002286 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002287 raw_ostream &OS = errs();
2288
2289 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002290 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002291 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2292 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002293 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002294
Jim Grosbach4b905842013-09-20 23:08:21 +00002295 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002296 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002297 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2298 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2299 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002300 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2301 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002302 }
2303
Eric Christophera7c32732012-12-18 00:30:54 +00002304 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002305 // manager changed or buffer changed (like in a nested include) then just
2306 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002307 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002308 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002309 if (Parser->SavedDiagHandler)
2310 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2311 else
Craig Topper353eda42014-04-24 06:44:33 +00002312 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002313 return;
2314 }
2315
Eric Christophera7c32732012-12-18 00:30:54 +00002316 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002317 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2318 // for the diagnostic.
2319 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002320
2321 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2322 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002323 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002324 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002325 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002326
Jim Grosbach4b905842013-09-20 23:08:21 +00002327 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2328 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002329 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002330
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002331 if (Parser->SavedDiagHandler)
2332 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2333 else
Craig Topper353eda42014-04-24 06:44:33 +00002334 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002335}
2336
Rafael Espindola2c064482012-08-21 18:29:30 +00002337// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2338// difference being that that function accepts '@' as part of identifiers and
2339// we can't do that. AsmLexer.cpp should probably be changed to handle
2340// '@' as a special case when needed.
2341static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002342 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2343 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002344}
2345
Rafael Espindola34b9c512012-06-03 23:57:14 +00002346bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002347 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002348 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002349 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002350 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002351 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002352 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002353 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002354
Preston Gurd05500642012-09-19 20:36:12 +00002355 // A macro without parameters is handled differently on Darwin:
2356 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002357 while (!Body.empty()) {
2358 // Scan for the next substitution.
2359 std::size_t End = Body.size(), Pos = 0;
2360 for (; Pos != End; ++Pos) {
2361 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002362 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002363 // This macro has no parameters, look for $0, $1, etc.
2364 if (Body[Pos] != '$' || Pos + 1 == End)
2365 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002366
Rafael Espindola1134ab232011-06-05 02:43:45 +00002367 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002368 if (Next == '$' || Next == 'n' ||
2369 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002370 break;
2371 } else {
2372 // This macro has parameters, look for \foo, \bar, etc.
2373 if (Body[Pos] == '\\' && Pos + 1 != End)
2374 break;
2375 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002376 }
2377
2378 // Add the prefix.
2379 OS << Body.slice(0, Pos);
2380
2381 // Check if we reached the end.
2382 if (Pos == End)
2383 break;
2384
Benjamin Kramer513e7442014-02-20 13:36:32 +00002385 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002386 switch (Body[Pos + 1]) {
2387 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002388 case '$':
2389 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002390 break;
2391
Jim Grosbach4b905842013-09-20 23:08:21 +00002392 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002393 case 'n':
2394 OS << A.size();
2395 break;
2396
Jim Grosbach4b905842013-09-20 23:08:21 +00002397 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002398 default: {
2399 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002400 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002401 if (Index >= A.size())
2402 break;
2403
2404 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002405 for (const AsmToken &Token : A[Index])
2406 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002407 break;
2408 }
2409 }
2410 Pos += 2;
2411 } else {
2412 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002413
2414 // Check for the \@ pseudo-variable.
2415 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002416 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002417 else
2418 while (isIdentifierChar(Body[I]) && I + 1 != End)
2419 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002420
Jim Grosbach4b905842013-09-20 23:08:21 +00002421 const char *Begin = Body.data() + Pos + 1;
2422 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002423 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002424
Toma Tabacu217116e2015-04-27 10:50:29 +00002425 if (Argument == "@") {
2426 OS << NumOfMacroInstantiations;
2427 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002428 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002429 for (; Index < NParameters; ++Index)
2430 if (Parameters[Index].Name == Argument)
2431 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002432
Toma Tabacu217116e2015-04-27 10:50:29 +00002433 if (Index == NParameters) {
2434 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2435 Pos += 3;
2436 else {
2437 OS << '\\' << Argument;
2438 Pos = I;
2439 }
2440 } else {
2441 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002442 for (const AsmToken &Token : A[Index])
Michael Zuckerman56704612017-05-01 13:20:12 +00002443 // For altmacro mode, you can write '%expr'.
2444 // The prefix '%' evaluates the expression 'expr'
Craig Topper3da977b2018-09-25 19:37:35 +00002445 // and uses the result as a string (e.g. replace %(1+2) with the
2446 // string "3").
Michael Zuckerman56704612017-05-01 13:20:12 +00002447 // Here, we identify the integer token which is the result of the
Craig Topper3da977b2018-09-25 19:37:35 +00002448 // absolute expression evaluation and replace it with its string
2449 // representation.
Craig Topperc81aff72018-09-25 20:55:55 +00002450 if (AltMacroMode && Token.getString().front() == '%' &&
Craig Topper3da977b2018-09-25 19:37:35 +00002451 Token.is(AsmToken::Integer))
Michael Zuckerman56704612017-05-01 13:20:12 +00002452 // Emit an integer value to the buffer.
2453 OS << Token.getIntVal();
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002454 // Only Token that was validated as a string and begins with '<'
2455 // is considered altMacroString!!!
Craig Topperc81aff72018-09-25 20:55:55 +00002456 else if (AltMacroMode && Token.getString().front() == '<' &&
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002457 Token.is(AsmToken::String)) {
Craig Topperd2aab832018-09-25 20:13:55 +00002458 OS << altMacroString(Token.getStringContents());
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002459 }
Toma Tabacu217116e2015-04-27 10:50:29 +00002460 // We expect no quotes around the string's contents when
2461 // parsing for varargs.
Michael Zuckerman56704612017-05-01 13:20:12 +00002462 else if (Token.isNot(AsmToken::String) || VarargParameter)
Craig Topper84008482015-10-10 05:38:14 +00002463 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002464 else
Craig Topper84008482015-10-10 05:38:14 +00002465 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002466
2467 Pos += 1 + Argument.size();
2468 }
Preston Gurd05500642012-09-19 20:36:12 +00002469 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002470 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002471 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002472 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002473 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002474
Rafael Espindola1134ab232011-06-05 02:43:45 +00002475 return false;
2476}
Daniel Dunbar43235712010-07-18 18:54:11 +00002477
Nico Weber2a8f9222014-07-24 16:29:04 +00002478MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002479 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002480 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002481 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002482
Jim Grosbach4b905842013-09-20 23:08:21 +00002483static bool isOperator(AsmToken::TokenKind kind) {
2484 switch (kind) {
2485 default:
2486 return false;
2487 case AsmToken::Plus:
2488 case AsmToken::Minus:
2489 case AsmToken::Tilde:
2490 case AsmToken::Slash:
2491 case AsmToken::Star:
2492 case AsmToken::Dot:
2493 case AsmToken::Equal:
2494 case AsmToken::EqualEqual:
2495 case AsmToken::Pipe:
2496 case AsmToken::PipePipe:
2497 case AsmToken::Caret:
2498 case AsmToken::Amp:
2499 case AsmToken::AmpAmp:
2500 case AsmToken::Exclaim:
2501 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002502 case AsmToken::Less:
2503 case AsmToken::LessEqual:
2504 case AsmToken::LessLess:
2505 case AsmToken::LessGreater:
2506 case AsmToken::Greater:
2507 case AsmToken::GreaterEqual:
2508 case AsmToken::GreaterGreater:
2509 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002510 }
2511}
2512
David Majnemer16252452014-01-29 00:07:39 +00002513namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002514
David Majnemer16252452014-01-29 00:07:39 +00002515class AsmLexerSkipSpaceRAII {
2516public:
2517 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2518 Lexer.setSkipSpace(SkipSpace);
2519 }
2520
2521 ~AsmLexerSkipSpaceRAII() {
2522 Lexer.setSkipSpace(true);
2523 }
2524
2525private:
2526 AsmLexer &Lexer;
2527};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002528
2529} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002530
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002531bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2532
2533 if (Vararg) {
2534 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2535 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002536 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002537 }
2538 return false;
2539 }
2540
Rafael Espindola768b41c2012-06-15 14:02:34 +00002541 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002542
David Majnemer16252452014-01-29 00:07:39 +00002543 // Darwin doesn't use spaces to delmit arguments.
2544 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002545
Scott Egertona1fa68a2016-02-11 13:48:49 +00002546 bool SpaceEaten;
2547
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002548 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002549 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002550 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002551 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002552
Scott Egertona1fa68a2016-02-11 13:48:49 +00002553 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002554
Scott Egertona1fa68a2016-02-11 13:48:49 +00002555 if (Lexer.is(AsmToken::Comma))
2556 break;
2557
2558 if (Lexer.is(AsmToken::Space)) {
2559 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002560 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002561 }
Preston Gurd05500642012-09-19 20:36:12 +00002562
2563 // Spaces can delimit parameters, but could also be part an expression.
2564 // If the token after a space is an operator, add the token and the next
2565 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002566 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002567 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002568 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002569 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002570
Scott Egertona1fa68a2016-02-11 13:48:49 +00002571 // Whitespace after an operator can be ignored.
2572 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002573 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002574
2575 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002576 }
2577 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002578 if (SpaceEaten)
2579 break;
Preston Gurd05500642012-09-19 20:36:12 +00002580 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002581
Jim Grosbach4b905842013-09-20 23:08:21 +00002582 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002583 // to be able to fill in the remaining default parameter values
2584 if (Lexer.is(AsmToken::EndOfStatement))
2585 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002586
2587 // Adjust the current parentheses level.
2588 if (Lexer.is(AsmToken::LParen))
2589 ++ParenLevel;
2590 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2591 --ParenLevel;
2592
2593 // Append the token to the current argument list.
2594 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002595 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002596 }
Preston Gurd05500642012-09-19 20:36:12 +00002597
Rafael Espindola768b41c2012-06-15 14:02:34 +00002598 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002599 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002600 return false;
2601}
2602
2603// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002604bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002605 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002606 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002607 bool NamedParametersFound = false;
2608 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002609
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002610 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002611 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002612
Rafael Espindola768b41c2012-06-15 14:02:34 +00002613 // Parse two kinds of macro invocations:
2614 // - macros defined without any parameters accept an arbitrary number of them
2615 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002616 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002617 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2618 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002619 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002620 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002621
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002622 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002623 if (parseIdentifier(FA.Name))
2624 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002625
Nirav Dave2364748a2016-09-16 18:30:20 +00002626 if (Lexer.isNot(AsmToken::Equal))
2627 return TokError("expected '=' after formal parameter identifier");
2628
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002629 Lex();
2630
2631 NamedParametersFound = true;
2632 }
Michael Zuckerman56704612017-05-01 13:20:12 +00002633 bool Vararg = HasVararg && Parameter == (NParameters - 1);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002634
Nirav Dave2364748a2016-09-16 18:30:20 +00002635 if (NamedParametersFound && FA.Name.empty())
2636 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002637
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002638 SMLoc StrLoc = Lexer.getLoc();
2639 SMLoc EndLoc;
Craig Topperc81aff72018-09-25 20:55:55 +00002640 if (AltMacroMode && Lexer.is(AsmToken::Percent)) {
Craig Topper3da977b2018-09-25 19:37:35 +00002641 const MCExpr *AbsoluteExp;
2642 int64_t Value;
2643 /// Eat '%'
2644 Lex();
2645 if (parseExpression(AbsoluteExp, EndLoc))
2646 return false;
2647 if (!AbsoluteExp->evaluateAsAbsolute(Value,
2648 getStreamer().getAssemblerPtr()))
2649 return Error(StrLoc, "expected absolute expression");
2650 const char *StrChar = StrLoc.getPointer();
2651 const char *EndChar = EndLoc.getPointer();
2652 AsmToken newToken(AsmToken::Integer,
2653 StringRef(StrChar, EndChar - StrChar), Value);
2654 FA.Value.push_back(newToken);
Craig Topperc81aff72018-09-25 20:55:55 +00002655 } else if (AltMacroMode && Lexer.is(AsmToken::Less) &&
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002656 isAltmacroString(StrLoc, EndLoc)) {
Craig Topper3da977b2018-09-25 19:37:35 +00002657 const char *StrChar = StrLoc.getPointer();
2658 const char *EndChar = EndLoc.getPointer();
2659 jumpToLoc(EndLoc, CurBuffer);
2660 /// Eat from '<' to '>'
2661 Lex();
2662 AsmToken newToken(AsmToken::String,
2663 StringRef(StrChar, EndChar - StrChar));
2664 FA.Value.push_back(newToken);
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002665 } else if(parseMacroArgument(FA.Value, Vararg))
Craig Topper3da977b2018-09-25 19:37:35 +00002666 return true;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002667
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002668 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002669 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002670 unsigned FAI = 0;
2671 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002672 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002673 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002674
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002675 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002676 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002677 return Error(IDLoc, "parameter named '" + FA.Name +
2678 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002679 }
2680 PI = FAI;
2681 }
2682
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002683 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002684 if (A.size() <= PI)
2685 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002686 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002687
2688 if (FALocs.size() <= PI)
2689 FALocs.resize(PI + 1);
2690
2691 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002692 }
Jim Grosbach206661622012-07-30 22:44:17 +00002693
Preston Gurd242ed3152012-09-19 20:29:04 +00002694 // At the end of the statement, fill in remaining arguments that have
2695 // default values. If there aren't any, then the next argument is
2696 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002697 if (Lexer.is(AsmToken::EndOfStatement)) {
2698 bool Failure = false;
2699 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2700 if (A[FAI].empty()) {
2701 if (M->Parameters[FAI].Required) {
2702 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2703 "missing value for required parameter "
2704 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2705 Failure = true;
2706 }
2707
2708 if (!M->Parameters[FAI].Value.empty())
2709 A[FAI] = M->Parameters[FAI].Value;
2710 }
2711 }
2712 return Failure;
2713 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002714
2715 if (Lexer.is(AsmToken::Comma))
2716 Lex();
2717 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002718
2719 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002720}
2721
Jim Grosbach4b905842013-09-20 23:08:21 +00002722bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002723 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2724 // eliminate this, although we should protect against infinite loops.
2725 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2726 if (ActiveMacros.size() == MaxNestingDepth) {
2727 std::ostringstream MaxNestingDepthError;
2728 MaxNestingDepthError << "macros cannot be nested more than "
2729 << MaxNestingDepth << " levels deep."
2730 << " Use -asm-macro-max-nesting-depth to increase "
2731 "this limit.";
2732 return TokError(MaxNestingDepthError.str());
2733 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002734
Eli Bendersky38274122013-01-14 23:22:36 +00002735 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002736 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002737 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002738
Rafael Espindola1134ab232011-06-05 02:43:45 +00002739 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2740 // to hold the macro body with substitutions.
2741 SmallString<256> Buf;
2742 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002743 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002744
Toma Tabacu217116e2015-04-27 10:50:29 +00002745 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002746 return true;
2747
Eli Bendersky38274122013-01-14 23:22:36 +00002748 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002749 // instantiation.
2750 OS << ".endmacro\n";
2751
Rafael Espindola3560ff22014-08-27 20:03:13 +00002752 std::unique_ptr<MemoryBuffer> Instantiation =
2753 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002754
Daniel Dunbar43235712010-07-18 18:54:11 +00002755 // Create the macro instantiation object and add to the current macro
2756 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002757 MacroInstantiation *MI = new MacroInstantiation(
2758 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002759 ActiveMacros.push_back(MI);
2760
Toma Tabacu217116e2015-04-27 10:50:29 +00002761 ++NumOfMacroInstantiations;
2762
Daniel Dunbar43235712010-07-18 18:54:11 +00002763 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002764 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002765 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002766 Lex();
2767
2768 return false;
2769}
2770
Jim Grosbach4b905842013-09-20 23:08:21 +00002771void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002772 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002773 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002774 Lex();
2775
2776 // Pop the instantiation entry.
2777 delete ActiveMacros.back();
2778 ActiveMacros.pop_back();
2779}
2780
Jim Grosbach4b905842013-09-20 23:08:21 +00002781bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Nirav Dave7fd992a2018-08-16 16:31:14 +00002782 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002783 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002784 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002785 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
Nirav Dave7fd992a2018-08-16 16:31:14 +00002786 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002787 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002788
Pete Cooper80d21cb2015-06-22 19:35:57 +00002789 if (!Sym) {
2790 // In the case where we parse an expression starting with a '.', we will
2791 // not generate an error, nor will we create a symbol. In this case we
2792 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002793 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002794 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002795
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002796 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002797 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002798 if (NoDeadStrip)
2799 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2800
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002801 return false;
2802}
2803
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002804/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002805/// ::= identifier
2806/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002807bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002808 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002809 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2810 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002811 // handle this as a context dependent token, instead we detect adjacent tokens
2812 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002813 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2814 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002815
Hans Wennborgce69d772013-10-18 20:46:28 +00002816 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002817
2818 AsmToken Buf[1];
2819 Lexer.peekTokens(Buf, false);
2820
2821 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002822 return true;
2823
Hans Wennborgce69d772013-10-18 20:46:28 +00002824 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002825 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002826 return true;
2827
Nirav Daved0463322016-10-12 13:58:07 +00002828 // eat $ or @
2829 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002830 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002831 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002832 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002833 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002834 return false;
2835 }
2836
Jim Grosbach4b905842013-09-20 23:08:21 +00002837 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002838 return true;
2839
Sean Callanan936b0d32010-01-19 21:44:56 +00002840 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002841
Sean Callanan686ed8d2010-01-19 20:22:31 +00002842 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002843
2844 return false;
2845}
2846
Jim Grosbach4b905842013-09-20 23:08:21 +00002847/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002848/// ::= .equ identifier ',' expression
2849/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002850/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002851bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002852 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002853 if (check(parseIdentifier(Name), "expected identifier") ||
2854 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2855 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2856 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002857}
2858
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002859bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002860 if (check(getTok().isNot(AsmToken::String), "expected string"))
2861 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002862
2863 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002864 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002865 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2866 if (Str[i] != '\\') {
2867 Data += Str[i];
2868 continue;
2869 }
2870
2871 // Recognize escaped characters. Note that this escape semantics currently
2872 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2873 ++i;
2874 if (i == e)
2875 return TokError("unexpected backslash at end of string");
2876
2877 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002878 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002879 // Consume up to three octal characters.
2880 unsigned Value = Str[i] - '0';
2881
Jim Grosbach4b905842013-09-20 23:08:21 +00002882 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002883 ++i;
2884 Value = Value * 8 + (Str[i] - '0');
2885
Jim Grosbach4b905842013-09-20 23:08:21 +00002886 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002887 ++i;
2888 Value = Value * 8 + (Str[i] - '0');
2889 }
2890 }
2891
2892 if (Value > 255)
2893 return TokError("invalid octal escape sequence (out of range)");
2894
Jim Grosbach4b905842013-09-20 23:08:21 +00002895 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002896 continue;
2897 }
2898
2899 // Otherwise recognize individual escapes.
2900 switch (Str[i]) {
2901 default:
2902 // Just reject invalid escape sequences for now.
2903 return TokError("invalid escape sequence (unrecognized character)");
2904
2905 case 'b': Data += '\b'; break;
2906 case 'f': Data += '\f'; break;
2907 case 'n': Data += '\n'; break;
2908 case 'r': Data += '\r'; break;
2909 case 't': Data += '\t'; break;
2910 case '"': Data += '"'; break;
2911 case '\\': Data += '\\'; break;
2912 }
2913 }
2914
Nirav Davea645433c2016-07-18 15:24:03 +00002915 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002916 return false;
2917}
2918
Jim Grosbach4b905842013-09-20 23:08:21 +00002919/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002920/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002921bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002922 auto parseOp = [&]() -> bool {
2923 std::string Data;
2924 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002925 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002926 getStreamer().EmitBytes(Data);
2927 if (ZeroTerminated)
2928 getStreamer().EmitBytes(StringRef("\0", 1));
2929 return false;
2930 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002931
Nirav Dave1a9044b2016-10-24 14:35:29 +00002932 if (parseMany(parseOp))
2933 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002934 return false;
2935}
2936
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002937/// parseDirectiveReloc
2938/// ::= .reloc expression , identifier [ , expression ]
2939bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2940 const MCExpr *Offset;
2941 const MCExpr *Expr = nullptr;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002942 int64_t OffsetValue;
Vladimir Stefanovic1d2714b2018-11-21 16:28:39 +00002943 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00002944
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002945 if (parseExpression(Offset))
2946 return true;
2947
Vladimir Stefanovic1d2714b2018-11-21 16:28:39 +00002948 if ((Offset->evaluateAsAbsolute(OffsetValue,
2949 getStreamer().getAssemblerPtr()) &&
2950 check(OffsetValue < 0, OffsetLoc, "expression is negative")) ||
2951 (check(Offset->getKind() != llvm::MCExpr::Constant &&
2952 Offset->getKind() != llvm::MCExpr::SymbolRef,
2953 OffsetLoc, "expected non-negative number or a label")) ||
2954 (parseToken(AsmToken::Comma, "expected comma") ||
2955 check(getTok().isNot(AsmToken::Identifier), "expected relocation name")))
Nirav Davea645433c2016-07-18 15:24:03 +00002956 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002957
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002958 SMLoc NameLoc = Lexer.getTok().getLoc();
2959 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002960 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002961
2962 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002963 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002964 SMLoc ExprLoc = Lexer.getLoc();
2965 if (parseExpression(Expr))
2966 return true;
2967
2968 MCValue Value;
2969 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2970 return Error(ExprLoc, "expression must be relocatable");
2971 }
2972
Nirav Davea645433c2016-07-18 15:24:03 +00002973 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002974 "unexpected token in .reloc directive"))
2975 return true;
2976
Peter Smith57f661b2018-06-06 09:40:06 +00002977 const MCTargetAsmParser &MCT = getTargetParser();
2978 const MCSubtargetInfo &STI = MCT.getSTI();
2979 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc, STI))
Nirav Dave1ab71992016-07-18 19:35:21 +00002980 return Error(NameLoc, "unknown relocation name");
2981
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002982 return false;
2983}
2984
Jim Grosbach4b905842013-09-20 23:08:21 +00002985/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002986/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002987bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2988 auto parseOp = [&]() -> bool {
2989 const MCExpr *Value;
2990 SMLoc ExprLoc = getLexer().getLoc();
2991 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002992 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002993 // Special case constant expressions to match code generator.
2994 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2995 assert(Size <= 8 && "Invalid size");
2996 uint64_t IntValue = MCE->getValue();
2997 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2998 return Error(ExprLoc, "out of range literal value");
2999 getStreamer().EmitIntValue(IntValue, Size);
3000 } else
3001 getStreamer().EmitValue(Value, Size, ExprLoc);
3002 return false;
3003 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00003004
Nirav Dave1a9044b2016-10-24 14:35:29 +00003005 if (parseMany(parseOp))
3006 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00003007 return false;
3008}
3009
Paul Robinson01954692018-04-11 15:14:05 +00003010static bool parseHexOcta(AsmParser &Asm, uint64_t &hi, uint64_t &lo) {
3011 if (Asm.getTok().isNot(AsmToken::Integer) &&
3012 Asm.getTok().isNot(AsmToken::BigNum))
3013 return Asm.TokError("unknown token in expression");
3014 SMLoc ExprLoc = Asm.getTok().getLoc();
3015 APInt IntValue = Asm.getTok().getAPIntVal();
3016 Asm.Lex();
3017 if (!IntValue.isIntN(128))
3018 return Asm.Error(ExprLoc, "out of range literal value");
3019 if (!IntValue.isIntN(64)) {
3020 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
3021 lo = IntValue.getLoBits(64).getZExtValue();
3022 } else {
3023 hi = 0;
3024 lo = IntValue.getZExtValue();
3025 }
3026 return false;
3027}
3028
David Woodhoused6de0d92014-02-01 16:20:59 +00003029/// ParseDirectiveOctaValue
3030/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003031
3032bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
3033 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00003034 if (checkForValidSection())
3035 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003036 uint64_t hi, lo;
Paul Robinson01954692018-04-11 15:14:05 +00003037 if (parseHexOcta(*this, hi, lo))
3038 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003039 if (MAI.isLittleEndian()) {
3040 getStreamer().EmitIntValue(lo, 8);
3041 getStreamer().EmitIntValue(hi, 8);
3042 } else {
3043 getStreamer().EmitIntValue(hi, 8);
3044 getStreamer().EmitIntValue(lo, 8);
3045 }
3046 return false;
3047 };
David Woodhoused6de0d92014-02-01 16:20:59 +00003048
Nirav Dave1a9044b2016-10-24 14:35:29 +00003049 if (parseMany(parseOp))
3050 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00003051 return false;
3052}
3053
Petr Hosek4cb08ce2016-09-23 19:25:15 +00003054bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
3055 // We don't truly support arithmetic on floating point expressions, so we
3056 // have to manually parse unary prefixes.
3057 bool IsNeg = false;
3058 if (getLexer().is(AsmToken::Minus)) {
3059 Lexer.Lex();
3060 IsNeg = true;
3061 } else if (getLexer().is(AsmToken::Plus))
3062 Lexer.Lex();
3063
3064 if (Lexer.is(AsmToken::Error))
3065 return TokError(Lexer.getErr());
3066 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
3067 Lexer.isNot(AsmToken::Identifier))
3068 return TokError("unexpected token in directive");
3069
3070 // Convert to an APFloat.
3071 APFloat Value(Semantics);
3072 StringRef IDVal = getTok().getString();
3073 if (getLexer().is(AsmToken::Identifier)) {
3074 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
3075 Value = APFloat::getInf(Semantics);
3076 else if (!IDVal.compare_lower("nan"))
3077 Value = APFloat::getNaN(Semantics, false, ~0);
3078 else
3079 return TokError("invalid floating point literal");
3080 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
3081 APFloat::opInvalidOp)
3082 return TokError("invalid floating point literal");
3083 if (IsNeg)
3084 Value.changeSign();
3085
3086 // Consume the numeric token.
3087 Lex();
3088
3089 Res = Value.bitcastToAPInt();
3090
3091 return false;
3092}
3093
Jim Grosbach4b905842013-09-20 23:08:21 +00003094/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00003095/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003096bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
3097 const fltSemantics &Semantics) {
3098 auto parseOp = [&]() -> bool {
3099 APInt AsInt;
3100 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00003101 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003102 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
3103 AsInt.getBitWidth() / 8);
3104 return false;
3105 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00003106
Nirav Dave1a9044b2016-10-24 14:35:29 +00003107 if (parseMany(parseOp))
3108 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00003109 return false;
3110}
3111
Jim Grosbach4b905842013-09-20 23:08:21 +00003112/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00003113/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003114bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003115 SMLoc NumBytesLoc = Lexer.getLoc();
3116 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003117 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00003118 return true;
3119
Rafael Espindolab91bac62010-10-05 19:42:57 +00003120 int64_t Val = 0;
3121 if (getLexer().is(AsmToken::Comma)) {
3122 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003123 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00003124 return true;
3125 }
3126
Nirav Davea645433c2016-07-18 15:24:03 +00003127 if (parseToken(AsmToken::EndOfStatement,
3128 "unexpected token in '.zero' directive"))
3129 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00003130 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00003131
3132 return false;
3133}
3134
Jim Grosbach4b905842013-09-20 23:08:21 +00003135/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00003136/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003137bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003138 SMLoc NumValuesLoc = Lexer.getLoc();
3139 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003140 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00003141 return true;
3142
Roman Divackye33098f2013-09-24 17:44:41 +00003143 int64_t FillSize = 1;
3144 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00003145
David Majnemer522d3db2014-02-01 07:19:38 +00003146 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003147
Nirav Dave1a9044b2016-10-24 14:35:29 +00003148 if (parseOptionalToken(AsmToken::Comma)) {
3149 SizeLoc = getTok().getLoc();
3150 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00003151 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003152 if (parseOptionalToken(AsmToken::Comma)) {
3153 ExprLoc = getTok().getLoc();
3154 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00003155 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00003156 }
3157 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003158 if (parseToken(AsmToken::EndOfStatement,
3159 "unexpected token in '.fill' directive"))
3160 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003161
David Majnemer522d3db2014-02-01 07:19:38 +00003162 if (FillSize < 0) {
3163 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00003164 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00003165 }
3166 if (FillSize > 8) {
3167 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
3168 FillSize = 8;
3169 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00003170
David Majnemer522d3db2014-02-01 07:19:38 +00003171 if (!isUInt<32>(FillExpr) && FillSize > 4)
3172 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
3173
Petr Hosek67a94a72016-05-28 05:57:48 +00003174 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00003175
3176 return false;
3177}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003178
Jim Grosbach4b905842013-09-20 23:08:21 +00003179/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003180/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003181bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00003182 const MCExpr *Offset;
Oliver Stannard268f42f2016-12-14 10:43:58 +00003183 SMLoc OffsetLoc = Lexer.getLoc();
Nirav Davef43cc9f2016-10-10 15:24:54 +00003184 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003185 return true;
3186
3187 // Parse optional fill expression.
3188 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003189 if (parseOptionalToken(AsmToken::Comma))
3190 if (parseAbsoluteExpression(FillExpr))
3191 return addErrorSuffix(" in '.org' directive");
3192 if (parseToken(AsmToken::EndOfStatement))
3193 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00003194
Oliver Stannard268f42f2016-12-14 10:43:58 +00003195 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003196 return false;
3197}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003198
Jim Grosbach4b905842013-09-20 23:08:21 +00003199/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003200/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00003201bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003202 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003203 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003204 SMLoc MaxBytesLoc;
3205 bool HasFillExpr = false;
3206 int64_t FillExpr = 0;
3207 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003208
3209 auto parseAlign = [&]() -> bool {
Coby Tayreed483a102017-08-02 17:36:10 +00003210 if (parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00003211 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003212 if (parseOptionalToken(AsmToken::Comma)) {
3213 // The fill expression can be omitted while specifying a maximum number of
3214 // alignment bytes, e.g:
3215 // .align 3,,4
3216 if (getTok().isNot(AsmToken::Comma)) {
3217 HasFillExpr = true;
3218 if (parseAbsoluteExpression(FillExpr))
3219 return true;
3220 }
3221 if (parseOptionalToken(AsmToken::Comma))
3222 if (parseTokenLoc(MaxBytesLoc) ||
3223 parseAbsoluteExpression(MaxBytesToFill))
3224 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003225 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003226 return parseToken(AsmToken::EndOfStatement);
3227 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003228
Coby Tayreed483a102017-08-02 17:36:10 +00003229 if (checkForValidSection())
3230 return addErrorSuffix(" in directive");
3231 // Ignore empty '.p2align' directives for GNU-as compatibility
3232 if (IsPow2 && (ValueSize == 1) && getTok().is(AsmToken::EndOfStatement)) {
3233 Warning(AlignmentLoc, "p2align directive with no operand(s) is ignored");
3234 return parseToken(AsmToken::EndOfStatement);
3235 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003236 if (parseAlign())
3237 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003238
Nirav Dave2364748a2016-09-16 18:30:20 +00003239 // Always emit an alignment here even if we thrown an error.
3240 bool ReturnVal = false;
3241
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003242 // Compute alignment in bytes.
3243 if (IsPow2) {
3244 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003245 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003246 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003247 Alignment = 31;
3248 }
3249
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003250 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003251 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003252 // Reject alignments that aren't either a power of two or zero,
3253 // for gas compatibility. Alignment of zero is silently rounded
3254 // up to one.
3255 if (Alignment == 0)
3256 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003257 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003258 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003259 }
3260
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003261 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003262 if (MaxBytesLoc.isValid()) {
3263 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003264 ReturnVal |= Error(MaxBytesLoc,
3265 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003266 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003267 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003268 }
3269
3270 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003271 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003272 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003273 MaxBytesToFill = 0;
3274 }
3275 }
3276
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003277 // Check whether we should use optimal code alignment for this .align
3278 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003279 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003280 assert(Section && "must have section to emit alignment");
3281 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003282 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3283 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003284 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003285 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003286 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003287 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3288 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003289 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003290
Nirav Dave2364748a2016-09-16 18:30:20 +00003291 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003292}
3293
Jim Grosbach4b905842013-09-20 23:08:21 +00003294/// parseDirectiveFile
Paul Robinson29f5f982018-01-09 23:31:48 +00003295/// ::= .file filename
Scott Linder16c7bda2018-02-23 23:01:06 +00003296/// ::= .file number [directory] filename [md5 checksum] [source source-text]
Jim Grosbach4b905842013-09-20 23:08:21 +00003297bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003298 // FIXME: I'm not sure what this is.
3299 int64_t FileNumber = -1;
Eli Bendersky17233942013-01-15 22:59:42 +00003300 if (getLexer().is(AsmToken::Integer)) {
3301 FileNumber = getTok().getIntVal();
3302 Lex();
3303
Paul Robinsonb271f312018-03-29 17:16:41 +00003304 if (FileNumber < 0)
3305 return TokError("negative file number");
Eli Bendersky17233942013-01-15 22:59:42 +00003306 }
3307
Paul Robinson37fbb922018-06-20 16:12:03 +00003308 std::string Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003309
3310 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003311 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003312 if (check(getTok().isNot(AsmToken::String),
3313 "unexpected token in '.file' directive") ||
3314 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003315 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003316
3317 StringRef Directory;
3318 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003319 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003320 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003321 if (check(FileNumber == -1,
3322 "explicit path specified, but no file number") ||
3323 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003324 return true;
3325 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003326 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003327 } else {
3328 Filename = Path;
3329 }
3330
Paul Robinson01954692018-04-11 15:14:05 +00003331 uint64_t MD5Hi, MD5Lo;
3332 bool HasMD5 = false;
Scott Linder16c7bda2018-02-23 23:01:06 +00003333
3334 Optional<StringRef> Source;
3335 bool HasSource = false;
3336 std::string SourceString;
3337
3338 while (!parseOptionalToken(AsmToken::EndOfStatement)) {
Paul Robinson29f5f982018-01-09 23:31:48 +00003339 StringRef Keyword;
3340 if (check(getTok().isNot(AsmToken::Identifier),
3341 "unexpected token in '.file' directive") ||
Scott Linder16c7bda2018-02-23 23:01:06 +00003342 parseIdentifier(Keyword))
Paul Robinson29f5f982018-01-09 23:31:48 +00003343 return true;
Scott Linder16c7bda2018-02-23 23:01:06 +00003344 if (Keyword == "md5") {
Paul Robinson01954692018-04-11 15:14:05 +00003345 HasMD5 = true;
Scott Linder16c7bda2018-02-23 23:01:06 +00003346 if (check(FileNumber == -1,
3347 "MD5 checksum specified, but no file number") ||
Paul Robinson01954692018-04-11 15:14:05 +00003348 parseHexOcta(*this, MD5Hi, MD5Lo))
Scott Linder16c7bda2018-02-23 23:01:06 +00003349 return true;
3350 } else if (Keyword == "source") {
3351 HasSource = true;
3352 if (check(FileNumber == -1,
3353 "source specified, but no file number") ||
3354 check(getTok().isNot(AsmToken::String),
3355 "unexpected token in '.file' directive") ||
3356 parseEscapedString(SourceString))
3357 return true;
3358 } else {
3359 return TokError("unexpected token in '.file' directive");
3360 }
Paul Robinson29f5f982018-01-09 23:31:48 +00003361 }
Eli Bendersky17233942013-01-15 22:59:42 +00003362
3363 if (FileNumber == -1)
3364 getStreamer().EmitFileDirective(Filename);
3365 else {
Brian Cain3e0ca572018-08-28 16:23:39 +00003366 // In case there is a -g option as well as debug info from directive .file,
3367 // we turn off the -g option, directly use the existing debug info instead.
3368 // Also reset any implicit ".file 0" for the assembler source.
3369 if (Ctx.getGenDwarfForAssembly()) {
3370 Ctx.getMCDwarfLineTable(0).resetRootFile();
3371 Ctx.setGenDwarfForAssembly(false);
3372 }
3373
Paul Robinson29f5f982018-01-09 23:31:48 +00003374 MD5::MD5Result *CKMem = nullptr;
Paul Robinson01954692018-04-11 15:14:05 +00003375 if (HasMD5) {
Paul Robinson29f5f982018-01-09 23:31:48 +00003376 CKMem = (MD5::MD5Result *)Ctx.allocate(sizeof(MD5::MD5Result), 1);
Paul Robinson01954692018-04-11 15:14:05 +00003377 for (unsigned i = 0; i != 8; ++i) {
3378 CKMem->Bytes[i] = uint8_t(MD5Hi >> ((7 - i) * 8));
3379 CKMem->Bytes[i + 8] = uint8_t(MD5Lo >> ((7 - i) * 8));
3380 }
Paul Robinson29f5f982018-01-09 23:31:48 +00003381 }
Scott Linder16c7bda2018-02-23 23:01:06 +00003382 if (HasSource) {
3383 char *SourceBuf = static_cast<char *>(Ctx.allocate(SourceString.size()));
3384 memcpy(SourceBuf, SourceString.data(), SourceString.size());
3385 Source = StringRef(SourceBuf, SourceString.size());
3386 }
Paul Robinson547adca2018-06-21 16:42:03 +00003387 if (FileNumber == 0) {
3388 if (Ctx.getDwarfVersion() < 5)
3389 return Warning(DirectiveLoc, "file 0 not supported prior to DWARF-5");
Paul Robinsonb271f312018-03-29 17:16:41 +00003390 getStreamer().emitDwarfFile0Directive(Directory, Filename, CKMem, Source);
Paul Robinson547adca2018-06-21 16:42:03 +00003391 } else {
Paul Robinsonb271f312018-03-29 17:16:41 +00003392 Expected<unsigned> FileNumOrErr = getStreamer().tryEmitDwarfFileDirective(
3393 FileNumber, Directory, Filename, CKMem, Source);
3394 if (!FileNumOrErr)
3395 return Error(DirectiveLoc, toString(FileNumOrErr.takeError()));
3396 FileNumber = FileNumOrErr.get();
3397 }
Paul Robinsoncc7344a2018-06-14 13:38:20 +00003398 // Alert the user if there are some .file directives with MD5 and some not.
3399 // But only do that once.
3400 if (!ReportedInconsistentMD5 && !Ctx.isDwarfMD5UsageConsistent(0)) {
3401 ReportedInconsistentMD5 = true;
3402 return Warning(DirectiveLoc, "inconsistent use of MD5 checksums");
3403 }
Eli Bendersky17233942013-01-15 22:59:42 +00003404 }
3405
3406 return false;
3407}
3408
Jim Grosbach4b905842013-09-20 23:08:21 +00003409/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003410/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003411bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003412 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003413 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003414 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3415 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003416 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003417 // FIXME: Do something with the .line.
3418 }
Nirav Davea645433c2016-07-18 15:24:03 +00003419 if (parseToken(AsmToken::EndOfStatement,
3420 "unexpected token in '.line' directive"))
3421 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003422
3423 return false;
3424}
3425
Jim Grosbach4b905842013-09-20 23:08:21 +00003426/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003427/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3428/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3429/// The first number is a file number, must have been previously assigned with
3430/// a .file directive, the second number is the line number and optionally the
3431/// third number is a column position (zero if not specified). The remaining
3432/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003433bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003434 int64_t FileNumber = 0, LineNumber = 0;
3435 SMLoc Loc = getTok().getLoc();
3436 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
Paul Robinson11539b02018-06-22 14:16:11 +00003437 check(FileNumber < 1 && Ctx.getDwarfVersion() < 5, Loc,
Nirav Davea645433c2016-07-18 15:24:03 +00003438 "file number less than one in '.loc' directive") ||
3439 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3440 "unassigned file number in '.loc' directive"))
3441 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003442
Nirav Davea645433c2016-07-18 15:24:03 +00003443 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003444 if (getLexer().is(AsmToken::Integer)) {
3445 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003446 if (LineNumber < 0)
3447 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003448 Lex();
3449 }
3450
3451 int64_t ColumnPos = 0;
3452 if (getLexer().is(AsmToken::Integer)) {
3453 ColumnPos = getTok().getIntVal();
3454 if (ColumnPos < 0)
3455 return TokError("column position less than zero in '.loc' directive");
3456 Lex();
3457 }
3458
3459 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3460 unsigned Isa = 0;
3461 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003462
Nirav Dave1a9044b2016-10-24 14:35:29 +00003463 auto parseLocOp = [&]() -> bool {
3464 StringRef Name;
3465 SMLoc Loc = getTok().getLoc();
3466 if (parseIdentifier(Name))
3467 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003468
Nirav Dave1a9044b2016-10-24 14:35:29 +00003469 if (Name == "basic_block")
3470 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3471 else if (Name == "prologue_end")
3472 Flags |= DWARF2_FLAG_PROLOGUE_END;
3473 else if (Name == "epilogue_begin")
3474 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3475 else if (Name == "is_stmt") {
3476 Loc = getTok().getLoc();
3477 const MCExpr *Value;
3478 if (parseExpression(Value))
3479 return true;
3480 // The expression must be the constant 0 or 1.
3481 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3482 int Value = MCE->getValue();
3483 if (Value == 0)
3484 Flags &= ~DWARF2_FLAG_IS_STMT;
3485 else if (Value == 1)
3486 Flags |= DWARF2_FLAG_IS_STMT;
3487 else
3488 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003489 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003490 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003491 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003492 } else if (Name == "isa") {
3493 Loc = getTok().getLoc();
3494 const MCExpr *Value;
3495 if (parseExpression(Value))
3496 return true;
3497 // The expression must be a constant greater or equal to 0.
3498 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3499 int Value = MCE->getValue();
3500 if (Value < 0)
3501 return Error(Loc, "isa number less than zero");
3502 Isa = Value;
3503 } else {
3504 return Error(Loc, "isa number not a constant value");
3505 }
3506 } else if (Name == "discriminator") {
3507 if (parseAbsoluteExpression(Discriminator))
3508 return true;
3509 } else {
3510 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003511 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003512 return false;
3513 };
3514
Nirav Davee2369aa2016-10-26 17:28:58 +00003515 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003516 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003517
3518 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3519 Isa, Discriminator, StringRef());
3520
3521 return false;
3522}
3523
Jim Grosbach4b905842013-09-20 23:08:21 +00003524/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003525/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003526bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003527 return TokError("unsupported directive '.stabs'");
3528}
3529
Reid Kleckner2214ed82016-01-29 00:49:42 +00003530/// parseDirectiveCVFile
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003531/// ::= .cv_file number filename [checksum] [checksumkind]
Reid Kleckner2214ed82016-01-29 00:49:42 +00003532bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003533 SMLoc FileNumberLoc = getTok().getLoc();
3534 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003535 std::string Filename;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003536 std::string Checksum;
3537 int64_t ChecksumKind = 0;
Nirav Davea645433c2016-07-18 15:24:03 +00003538
3539 if (parseIntToken(FileNumber,
3540 "expected file number in '.cv_file' directive") ||
3541 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3542 check(getTok().isNot(AsmToken::String),
3543 "unexpected token in '.cv_file' directive") ||
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003544 parseEscapedString(Filename))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003545 return true;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003546 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3547 if (check(getTok().isNot(AsmToken::String),
3548 "unexpected token in '.cv_file' directive") ||
3549 parseEscapedString(Checksum) ||
3550 parseIntToken(ChecksumKind,
3551 "expected checksum kind in '.cv_file' directive") ||
3552 parseToken(AsmToken::EndOfStatement,
3553 "unexpected token in '.cv_file' directive"))
3554 return true;
3555 }
Nirav Dave1ab71992016-07-18 19:35:21 +00003556
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003557 Checksum = fromHex(Checksum);
3558 void *CKMem = Ctx.allocate(Checksum.size(), 1);
3559 memcpy(CKMem, Checksum.data(), Checksum.size());
3560 ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem),
3561 Checksum.size());
3562
3563 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename, ChecksumAsBytes,
3564 static_cast<uint8_t>(ChecksumKind)))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003565 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003566
3567 return false;
3568}
3569
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003570bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3571 StringRef DirectiveName) {
3572 SMLoc Loc;
3573 return parseTokenLoc(Loc) ||
3574 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3575 "' directive") ||
3576 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3577 "expected function id within range [0, UINT_MAX)");
3578}
3579
3580bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3581 SMLoc Loc;
3582 return parseTokenLoc(Loc) ||
3583 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3584 "' directive") ||
3585 check(FileNumber < 1, Loc, "file number less than one in '" +
3586 DirectiveName + "' directive") ||
3587 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3588 "unassigned file number in '" + DirectiveName + "' directive");
3589}
3590
3591/// parseDirectiveCVFuncId
3592/// ::= .cv_func_id FunctionId
3593///
3594/// Introduces a function ID that can be used with .cv_loc.
3595bool AsmParser::parseDirectiveCVFuncId() {
3596 SMLoc FunctionIdLoc = getTok().getLoc();
3597 int64_t FunctionId;
3598
3599 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3600 parseToken(AsmToken::EndOfStatement,
3601 "unexpected token in '.cv_func_id' directive"))
3602 return true;
3603
3604 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003605 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003606
3607 return false;
3608}
3609
3610/// parseDirectiveCVInlineSiteId
3611/// ::= .cv_inline_site_id FunctionId
3612/// "within" IAFunc
3613/// "inlined_at" IAFile IALine [IACol]
3614///
3615/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3616/// at" source location information for use in the line table of the caller,
3617/// whether the caller is a real function or another inlined call site.
3618bool AsmParser::parseDirectiveCVInlineSiteId() {
3619 SMLoc FunctionIdLoc = getTok().getLoc();
3620 int64_t FunctionId;
3621 int64_t IAFunc;
3622 int64_t IAFile;
3623 int64_t IALine;
3624 int64_t IACol = 0;
3625
3626 // FunctionId
3627 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3628 return true;
3629
3630 // "within"
3631 if (check((getLexer().isNot(AsmToken::Identifier) ||
3632 getTok().getIdentifier() != "within"),
3633 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3634 return true;
3635 Lex();
3636
3637 // IAFunc
3638 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3639 return true;
3640
3641 // "inlined_at"
3642 if (check((getLexer().isNot(AsmToken::Identifier) ||
3643 getTok().getIdentifier() != "inlined_at"),
3644 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3645 "directive") )
3646 return true;
3647 Lex();
3648
3649 // IAFile IALine
3650 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3651 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3652 return true;
3653
3654 // [IACol]
3655 if (getLexer().is(AsmToken::Integer)) {
3656 IACol = getTok().getIntVal();
3657 Lex();
3658 }
3659
3660 if (parseToken(AsmToken::EndOfStatement,
3661 "unexpected token in '.cv_inline_site_id' directive"))
3662 return true;
3663
3664 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3665 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003666 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003667
3668 return false;
3669}
3670
Reid Kleckner2214ed82016-01-29 00:49:42 +00003671/// parseDirectiveCVLoc
3672/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3673/// [is_stmt VALUE]
3674/// The first number is a file number, must have been previously assigned with
3675/// a .file directive, the second number is the line number and optionally the
3676/// third number is a column position (zero if not specified). The remaining
3677/// optional items are .loc sub-directives.
3678bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003679 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003680 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003681 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3682 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003683 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003684
3685 int64_t LineNumber = 0;
3686 if (getLexer().is(AsmToken::Integer)) {
3687 LineNumber = getTok().getIntVal();
3688 if (LineNumber < 0)
3689 return TokError("line number less than zero in '.cv_loc' directive");
3690 Lex();
3691 }
3692
3693 int64_t ColumnPos = 0;
3694 if (getLexer().is(AsmToken::Integer)) {
3695 ColumnPos = getTok().getIntVal();
3696 if (ColumnPos < 0)
3697 return TokError("column position less than zero in '.cv_loc' directive");
3698 Lex();
3699 }
3700
3701 bool PrologueEnd = false;
3702 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003703
3704 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003705 StringRef Name;
3706 SMLoc Loc = getTok().getLoc();
3707 if (parseIdentifier(Name))
3708 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003709 if (Name == "prologue_end")
3710 PrologueEnd = true;
3711 else if (Name == "is_stmt") {
3712 Loc = getTok().getLoc();
3713 const MCExpr *Value;
3714 if (parseExpression(Value))
3715 return true;
3716 // The expression must be the constant 0 or 1.
3717 IsStmt = ~0ULL;
3718 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3719 IsStmt = MCE->getValue();
3720
3721 if (IsStmt > 1)
3722 return Error(Loc, "is_stmt value not 0 or 1");
3723 } else {
3724 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3725 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003726 return false;
3727 };
3728
3729 if (parseMany(parseOp, false /*hasComma*/))
3730 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003731
3732 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003733 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3734 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003735 return false;
3736}
3737
3738/// parseDirectiveCVLinetable
3739/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3740bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003741 int64_t FunctionId;
3742 StringRef FnStartName, FnEndName;
3743 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003744 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003745 parseToken(AsmToken::Comma,
3746 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003747 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3748 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003749 parseToken(AsmToken::Comma,
3750 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003751 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3752 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003753 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003754
3755 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3756 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3757
3758 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3759 return false;
3760}
3761
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003762/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003763/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003764bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003765 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3766 StringRef FnStartName, FnEndName;
3767 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003768 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003769 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003770 parseIntToken(
3771 SourceFileId,
3772 "expected SourceField in '.cv_inline_linetable' directive") ||
3773 check(SourceFileId <= 0, Loc,
3774 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003775 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003776 parseIntToken(
3777 SourceLineNum,
3778 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3779 check(SourceLineNum < 0, Loc,
3780 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003781 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3782 "expected identifier in directive") ||
3783 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3784 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003785 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003786
Nirav Davea645433c2016-07-18 15:24:03 +00003787 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3788 return true;
3789
3790 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3791 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003792 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3793 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003794 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003795 return false;
3796}
3797
David Majnemer408b5e62016-02-05 01:55:49 +00003798/// parseDirectiveCVDefRange
3799/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3800bool AsmParser::parseDirectiveCVDefRange() {
3801 SMLoc Loc;
3802 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3803 while (getLexer().is(AsmToken::Identifier)) {
3804 Loc = getLexer().getLoc();
3805 StringRef GapStartName;
3806 if (parseIdentifier(GapStartName))
3807 return Error(Loc, "expected identifier in directive");
3808 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3809
3810 Loc = getLexer().getLoc();
3811 StringRef GapEndName;
3812 if (parseIdentifier(GapEndName))
3813 return Error(Loc, "expected identifier in directive");
3814 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3815
3816 Ranges.push_back({GapStartSym, GapEndSym});
3817 }
3818
David Majnemer408b5e62016-02-05 01:55:49 +00003819 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003820 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3821 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003822 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003823
3824 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3825 return false;
3826}
3827
Reid Kleckner06d02d02018-09-07 21:30:52 +00003828/// parseDirectiveCVString
3829/// ::= .cv_stringtable "string"
3830bool AsmParser::parseDirectiveCVString() {
3831 std::string Data;
3832 if (checkForValidSection() || parseEscapedString(Data))
3833 return addErrorSuffix(" in '.cv_string' directive");
3834
3835 // Put the string in the table and emit the offset.
3836 std::pair<StringRef, unsigned> Insertion =
3837 getCVContext().addToStringTable(Data);
3838 getStreamer().EmitIntValue(Insertion.second, 4);
3839 return false;
3840}
3841
Reid Kleckner2214ed82016-01-29 00:49:42 +00003842/// parseDirectiveCVStringTable
3843/// ::= .cv_stringtable
3844bool AsmParser::parseDirectiveCVStringTable() {
3845 getStreamer().EmitCVStringTableDirective();
3846 return false;
3847}
3848
3849/// parseDirectiveCVFileChecksums
3850/// ::= .cv_filechecksums
3851bool AsmParser::parseDirectiveCVFileChecksums() {
3852 getStreamer().EmitCVFileChecksumsDirective();
3853 return false;
3854}
3855
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003856/// parseDirectiveCVFileChecksumOffset
3857/// ::= .cv_filechecksumoffset fileno
3858bool AsmParser::parseDirectiveCVFileChecksumOffset() {
3859 int64_t FileNo;
3860 if (parseIntToken(FileNo, "expected identifier in directive"))
3861 return true;
3862 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3863 return true;
3864 getStreamer().EmitCVFileChecksumOffsetDirective(FileNo);
3865 return false;
3866}
3867
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00003868/// parseDirectiveCVFPOData
3869/// ::= .cv_fpo_data procsym
3870bool AsmParser::parseDirectiveCVFPOData() {
3871 SMLoc DirLoc = getLexer().getLoc();
3872 StringRef ProcName;
3873 if (parseIdentifier(ProcName))
3874 return TokError("expected symbol name");
3875 if (parseEOL("unexpected tokens"))
3876 return addErrorSuffix(" in '.cv_fpo_data' directive");
3877 MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName);
3878 getStreamer().EmitCVFPOData(ProcSym, DirLoc);
3879 return false;
3880}
3881
Jim Grosbach4b905842013-09-20 23:08:21 +00003882/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003883/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003884bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003885 StringRef Name;
3886 bool EH = false;
3887 bool Debug = false;
3888
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003889 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003890 return TokError("Expected an identifier");
3891
3892 if (Name == ".eh_frame")
3893 EH = true;
3894 else if (Name == ".debug_frame")
3895 Debug = true;
3896
3897 if (getLexer().is(AsmToken::Comma)) {
3898 Lex();
3899
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003900 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003901 return TokError("Expected an identifier");
3902
3903 if (Name == ".eh_frame")
3904 EH = true;
3905 else if (Name == ".debug_frame")
3906 Debug = true;
3907 }
3908
3909 getStreamer().EmitCFISections(EH, Debug);
3910 return false;
3911}
3912
Jim Grosbach4b905842013-09-20 23:08:21 +00003913/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003914/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003915bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003916 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003917 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3918 if (check(parseIdentifier(Simple) || Simple != "simple",
3919 "unexpected token") ||
3920 parseToken(AsmToken::EndOfStatement))
3921 return addErrorSuffix(" in '.cfi_startproc' directive");
3922 }
Wouter van Oortmerssencc75e772018-11-12 20:15:01 +00003923
Kristina Brooks1a41a112018-10-19 12:14:30 +00003924 // TODO(kristina): Deal with a corner case of incorrect diagnostic context
3925 // being produced if this directive is emitted as part of preprocessor macro
3926 // expansion which can *ONLY* happen if Clang's cc1as is the API consumer.
3927 // Tools like llvm-mc on the other hand are not affected by it, and report
3928 // correct context information.
3929 getStreamer().EmitCFIStartProc(!Simple.empty(), Lexer.getLoc());
Eli Bendersky17233942013-01-15 22:59:42 +00003930 return false;
3931}
3932
Jim Grosbach4b905842013-09-20 23:08:21 +00003933/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003934/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003935bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003936 getStreamer().EmitCFIEndProc();
3937 return false;
3938}
3939
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003940/// parse register name or number.
Jim Grosbach4b905842013-09-20 23:08:21 +00003941bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003942 SMLoc DirectiveLoc) {
3943 unsigned RegNo;
3944
3945 if (getLexer().isNot(AsmToken::Integer)) {
3946 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3947 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003948 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003949 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003950 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003951
3952 return false;
3953}
3954
Jim Grosbach4b905842013-09-20 23:08:21 +00003955/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003956/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003957bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003958 int64_t Register = 0, Offset = 0;
3959 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3960 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3961 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003962 return true;
3963
3964 getStreamer().EmitCFIDefCfa(Register, Offset);
3965 return false;
3966}
3967
Jim Grosbach4b905842013-09-20 23:08:21 +00003968/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003969/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003970bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003971 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003972 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003973 return true;
3974
3975 getStreamer().EmitCFIDefCfaOffset(Offset);
3976 return false;
3977}
3978
Jim Grosbach4b905842013-09-20 23:08:21 +00003979/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003980/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003981bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003982 int64_t Register1 = 0, Register2 = 0;
3983 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3984 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3985 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003986 return true;
3987
3988 getStreamer().EmitCFIRegister(Register1, Register2);
3989 return false;
3990}
3991
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003992/// parseDirectiveCFIWindowSave
3993/// ::= .cfi_window_save
3994bool AsmParser::parseDirectiveCFIWindowSave() {
3995 getStreamer().EmitCFIWindowSave();
3996 return false;
3997}
3998
Jim Grosbach4b905842013-09-20 23:08:21 +00003999/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00004000/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00004001bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00004002 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004003 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00004004 return true;
4005
4006 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
4007 return false;
4008}
4009
Jim Grosbach4b905842013-09-20 23:08:21 +00004010/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00004011/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00004012bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004013 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00004014 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004015 return true;
4016
4017 getStreamer().EmitCFIDefCfaRegister(Register);
4018 return false;
4019}
4020
Jim Grosbach4b905842013-09-20 23:08:21 +00004021/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00004022/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00004023bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004024 int64_t Register = 0;
4025 int64_t Offset = 0;
4026
Nirav Davea645433c2016-07-18 15:24:03 +00004027 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
4028 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4029 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00004030 return true;
4031
4032 getStreamer().EmitCFIOffset(Register, Offset);
4033 return false;
4034}
4035
Jim Grosbach4b905842013-09-20 23:08:21 +00004036/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00004037/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00004038bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004039 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00004040
Nirav Davea645433c2016-07-18 15:24:03 +00004041 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
4042 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4043 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00004044 return true;
4045
4046 getStreamer().EmitCFIRelOffset(Register, Offset);
4047 return false;
4048}
4049
4050static bool isValidEncoding(int64_t Encoding) {
4051 if (Encoding & ~0xff)
4052 return false;
4053
4054 if (Encoding == dwarf::DW_EH_PE_omit)
4055 return true;
4056
4057 const unsigned Format = Encoding & 0xf;
4058 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
4059 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
4060 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
4061 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
4062 return false;
4063
4064 const unsigned Application = Encoding & 0x70;
4065 if (Application != dwarf::DW_EH_PE_absptr &&
4066 Application != dwarf::DW_EH_PE_pcrel)
4067 return false;
4068
4069 return true;
4070}
4071
Jim Grosbach4b905842013-09-20 23:08:21 +00004072/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00004073/// IsPersonality true for cfi_personality, false for cfi_lsda
4074/// ::= .cfi_personality encoding, [symbol_name]
4075/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00004076bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00004077 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004078 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00004079 return true;
4080 if (Encoding == dwarf::DW_EH_PE_omit)
4081 return false;
4082
Eli Bendersky17233942013-01-15 22:59:42 +00004083 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004084 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
4085 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4086 check(parseIdentifier(Name), "expected identifier in directive"))
4087 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004088
Jim Grosbach6f482002015-05-18 18:43:14 +00004089 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004090
4091 if (IsPersonality)
4092 getStreamer().EmitCFIPersonality(Sym, Encoding);
4093 else
4094 getStreamer().EmitCFILsda(Sym, Encoding);
4095 return false;
4096}
4097
Jim Grosbach4b905842013-09-20 23:08:21 +00004098/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00004099/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004100bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004101 getStreamer().EmitCFIRememberState();
4102 return false;
4103}
4104
Jim Grosbach4b905842013-09-20 23:08:21 +00004105/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00004106/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004107bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004108 getStreamer().EmitCFIRestoreState();
4109 return false;
4110}
4111
Jim Grosbach4b905842013-09-20 23:08:21 +00004112/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00004113/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00004114bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004115 int64_t Register = 0;
4116
Jim Grosbach4b905842013-09-20 23:08:21 +00004117 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004118 return true;
4119
4120 getStreamer().EmitCFISameValue(Register);
4121 return false;
4122}
4123
Jim Grosbach4b905842013-09-20 23:08:21 +00004124/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00004125/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00004126bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004127 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00004128 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004129 return true;
4130
4131 getStreamer().EmitCFIRestore(Register);
4132 return false;
4133}
4134
Jim Grosbach4b905842013-09-20 23:08:21 +00004135/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00004136/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004137bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00004138 std::string Values;
4139 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004140 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004141 return true;
4142
4143 Values.push_back((uint8_t)CurrValue);
4144
4145 while (getLexer().is(AsmToken::Comma)) {
4146 Lex();
4147
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004148 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004149 return true;
4150
4151 Values.push_back((uint8_t)CurrValue);
4152 }
4153
4154 getStreamer().EmitCFIEscape(Values);
4155 return false;
4156}
4157
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00004158/// parseDirectiveCFIReturnColumn
4159/// ::= .cfi_return_column register
4160bool AsmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc) {
4161 int64_t Register = 0;
4162 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4163 return true;
4164 getStreamer().EmitCFIReturnColumn(Register);
4165 return false;
4166}
4167
Jim Grosbach4b905842013-09-20 23:08:21 +00004168/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00004169/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00004170bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00004171 if (parseToken(AsmToken::EndOfStatement,
4172 "unexpected token in '.cfi_signal_frame'"))
4173 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004174
4175 getStreamer().EmitCFISignalFrame();
4176 return false;
4177}
4178
Jim Grosbach4b905842013-09-20 23:08:21 +00004179/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00004180/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00004181bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004182 int64_t Register = 0;
4183
Jim Grosbach4b905842013-09-20 23:08:21 +00004184 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004185 return true;
4186
4187 getStreamer().EmitCFIUndefined(Register);
4188 return false;
4189}
4190
Michael Zuckerman56704612017-05-01 13:20:12 +00004191/// parseDirectiveAltmacro
4192/// ::= .altmacro
4193/// ::= .noaltmacro
4194bool AsmParser::parseDirectiveAltmacro(StringRef Directive) {
4195 if (getLexer().isNot(AsmToken::EndOfStatement))
4196 return TokError("unexpected token in '" + Directive + "' directive");
Craig Topperc81aff72018-09-25 20:55:55 +00004197 AltMacroMode = (Directive == ".altmacro");
Michael Zuckerman56704612017-05-01 13:20:12 +00004198 return false;
4199}
4200
Jim Grosbach4b905842013-09-20 23:08:21 +00004201/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00004202/// ::= .macros_on
4203/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00004204bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004205 if (parseToken(AsmToken::EndOfStatement,
4206 "unexpected token in '" + Directive + "' directive"))
4207 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004208
Jim Grosbach4b905842013-09-20 23:08:21 +00004209 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00004210 return false;
4211}
4212
Jim Grosbach4b905842013-09-20 23:08:21 +00004213/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004214/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00004215bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004216 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004217 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00004218 return TokError("expected identifier in '.macro' directive");
4219
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004220 if (getLexer().is(AsmToken::Comma))
4221 Lex();
4222
Eli Bendersky17233942013-01-15 22:59:42 +00004223 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00004224 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004225
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00004226 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004227 return Error(Lexer.getLoc(),
4228 "Vararg parameter '" + Parameters.back().Name +
4229 "' should be last one in the list of parameters.");
4230
David Majnemer91fc4c22014-01-29 18:57:46 +00004231 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004232 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00004233 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004234
Coby Tayreebedaae02017-04-08 20:29:03 +00004235 // Emit an error if two (or more) named parameters share the same name
4236 for (const MCAsmMacroParameter& CurrParam : Parameters)
4237 if (CurrParam.Name.equals(Parameter.Name))
4238 return TokError("macro '" + Name + "' has multiple parameters"
4239 " named '" + Parameter.Name + "'");
4240
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004241 if (Lexer.is(AsmToken::Colon)) {
4242 Lex(); // consume ':'
4243
4244 SMLoc QualLoc;
4245 StringRef Qualifier;
4246
4247 QualLoc = Lexer.getLoc();
4248 if (parseIdentifier(Qualifier))
4249 return Error(QualLoc, "missing parameter qualifier for "
4250 "'" + Parameter.Name + "' in macro '" + Name + "'");
4251
4252 if (Qualifier == "req")
4253 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00004254 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004255 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004256 else
4257 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
4258 "for '" + Parameter.Name + "' in macro '" + Name + "'");
4259 }
4260
David Majnemer91fc4c22014-01-29 18:57:46 +00004261 if (getLexer().is(AsmToken::Equal)) {
4262 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004263
4264 SMLoc ParamLoc;
4265
4266 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004267 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00004268 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004269
4270 if (Parameter.Required)
4271 Warning(ParamLoc, "pointless default value for required parameter "
4272 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00004273 }
David Majnemer91fc4c22014-01-29 18:57:46 +00004274
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00004275 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00004276
4277 if (getLexer().is(AsmToken::Comma))
4278 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004279 }
4280
Nirav Dave1180e6892016-06-02 17:15:05 +00004281 // Eat just the end of statement.
4282 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004283
Nirav Dave1180e6892016-06-02 17:15:05 +00004284 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00004285 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004286 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00004287 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004288 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00004289 // Ignore Lexing errors in macros.
4290 while (Lexer.is(AsmToken::Error)) {
4291 Lexer.Lex();
4292 }
4293
Eli Bendersky17233942013-01-15 22:59:42 +00004294 // Check whether we have reached the end of the file.
4295 if (getLexer().is(AsmToken::Eof))
4296 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
4297
4298 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004299 if (getLexer().is(AsmToken::Identifier)) {
4300 if (getTok().getIdentifier() == ".endm" ||
4301 getTok().getIdentifier() == ".endmacro") {
4302 if (MacroDepth == 0) { // Outermost macro.
4303 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00004304 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004305 if (getLexer().isNot(AsmToken::EndOfStatement))
4306 return TokError("unexpected token in '" + EndToken.getIdentifier() +
4307 "' directive");
4308 break;
4309 } else {
4310 // Otherwise we just found the end of an inner macro.
4311 --MacroDepth;
4312 }
4313 } else if (getTok().getIdentifier() == ".macro") {
4314 // We allow nested macros. Those aren't instantiated until the outermost
4315 // macro is expanded so just ignore them for now.
4316 ++MacroDepth;
4317 }
Eli Bendersky17233942013-01-15 22:59:42 +00004318 }
4319
4320 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004321 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00004322 }
4323
Rafael Espindola22c38a02018-02-14 16:34:27 +00004324 if (getContext().lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00004325 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
4326 }
4327
4328 const char *BodyStart = StartToken.getLoc().getPointer();
4329 const char *BodyEnd = EndToken.getLoc().getPointer();
4330 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00004331 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Oliver Stannardc3e7c6d2018-03-06 15:32:34 +00004332 MCAsmMacro Macro(Name, Body, std::move(Parameters));
4333 DEBUG_WITH_TYPE("asm-macros", dbgs() << "Defining new macro:\n";
4334 Macro.dump());
4335 getContext().defineMacro(Name, std::move(Macro));
Eli Bendersky17233942013-01-15 22:59:42 +00004336 return false;
4337}
4338
Jim Grosbach4b905842013-09-20 23:08:21 +00004339/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00004340///
4341/// With the support added for named parameters there may be code out there that
4342/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00004343/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00004344/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00004345/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00004346/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4347/// warning that the positional parameter found in body which have no effect.
4348/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00004349/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00004350/// intended or change the macro to use the named parameters. It is possible
4351/// this warning will trigger when the none of the named parameters are used
4352/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00004353void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00004354 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004355 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00004356 // If this macro is not defined with named parameters the warning we are
4357 // checking for here doesn't apply.
4358 unsigned NParameters = Parameters.size();
4359 if (NParameters == 0)
4360 return;
4361
4362 bool NamedParametersFound = false;
4363 bool PositionalParametersFound = false;
4364
4365 // Look at the body of the macro for use of both the named parameters and what
4366 // are likely to be positional parameters. This is what expandMacro() is
4367 // doing when it finds the parameters in the body.
4368 while (!Body.empty()) {
4369 // Scan for the next possible parameter.
4370 std::size_t End = Body.size(), Pos = 0;
4371 for (; Pos != End; ++Pos) {
4372 // Check for a substitution or escape.
4373 // This macro is defined with parameters, look for \foo, \bar, etc.
4374 if (Body[Pos] == '\\' && Pos + 1 != End)
4375 break;
4376
4377 // This macro should have parameters, but look for $0, $1, ..., $n too.
4378 if (Body[Pos] != '$' || Pos + 1 == End)
4379 continue;
4380 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004381 if (Next == '$' || Next == 'n' ||
4382 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004383 break;
4384 }
4385
4386 // Check if we reached the end.
4387 if (Pos == End)
4388 break;
4389
4390 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004391 switch (Body[Pos + 1]) {
4392 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004393 case '$':
4394 break;
4395
Jim Grosbach4b905842013-09-20 23:08:21 +00004396 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004397 case 'n':
4398 PositionalParametersFound = true;
4399 break;
4400
Jim Grosbach4b905842013-09-20 23:08:21 +00004401 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004402 default: {
4403 PositionalParametersFound = true;
4404 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004405 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004406 }
4407 Pos += 2;
4408 } else {
4409 unsigned I = Pos + 1;
4410 while (isIdentifierChar(Body[I]) && I + 1 != End)
4411 ++I;
4412
Jim Grosbach4b905842013-09-20 23:08:21 +00004413 const char *Begin = Body.data() + Pos + 1;
4414 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004415 unsigned Index = 0;
4416 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004417 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004418 break;
4419
4420 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004421 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4422 Pos += 3;
4423 else {
4424 Pos = I;
4425 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004426 } else {
4427 NamedParametersFound = true;
4428 Pos += 1 + Argument.size();
4429 }
4430 }
4431 // Update the scan point.
4432 Body = Body.substr(Pos);
4433 }
4434
4435 if (!NamedParametersFound && PositionalParametersFound)
4436 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4437 "used in macro body, possible positional parameter "
4438 "found in body which will have no effect");
4439}
4440
Nico Weber155dccd12014-07-24 17:08:39 +00004441/// parseDirectiveExitMacro
4442/// ::= .exitm
4443bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004444 if (parseToken(AsmToken::EndOfStatement,
4445 "unexpected token in '" + Directive + "' directive"))
4446 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004447
4448 if (!isInsideMacroInstantiation())
4449 return TokError("unexpected '" + Directive + "' in file, "
4450 "no current macro definition");
4451
4452 // Exit all conditionals that are active in the current macro.
4453 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4454 TheCondState = TheCondStack.back();
4455 TheCondStack.pop_back();
4456 }
4457
4458 handleMacroExit();
4459 return false;
4460}
4461
Jim Grosbach4b905842013-09-20 23:08:21 +00004462/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004463/// ::= .endm
4464/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004465bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004466 if (getLexer().isNot(AsmToken::EndOfStatement))
4467 return TokError("unexpected token in '" + Directive + "' directive");
4468
4469 // If we are inside a macro instantiation, terminate the current
4470 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004471 if (isInsideMacroInstantiation()) {
4472 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004473 return false;
4474 }
4475
4476 // Otherwise, this .endmacro is a stray entry in the file; well formed
4477 // .endmacro directives are handled during the macro definition parsing.
4478 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004479 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004480}
4481
Jim Grosbach4b905842013-09-20 23:08:21 +00004482/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004483/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004484bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004485 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004486 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004487 if (parseTokenLoc(Loc) ||
4488 check(parseIdentifier(Name), Loc,
4489 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004490 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004491 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004492 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004493
Rafael Espindola22c38a02018-02-14 16:34:27 +00004494 if (!getContext().lookupMacro(Name))
Nirav Dave1ab71992016-07-18 19:35:21 +00004495 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4496
Rafael Espindola22c38a02018-02-14 16:34:27 +00004497 getContext().undefineMacro(Name);
Oliver Stannardc3e7c6d2018-03-06 15:32:34 +00004498 DEBUG_WITH_TYPE("asm-macros", dbgs()
4499 << "Un-defining macro: " << Name << "\n");
Eli Bendersky17233942013-01-15 22:59:42 +00004500 return false;
4501}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004502
Jim Grosbach4b905842013-09-20 23:08:21 +00004503/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004504/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004505bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004506 // Expect a single argument: an expression that evaluates to a constant
4507 // in the inclusive range 0-30.
4508 SMLoc ExprLoc = getLexer().getLoc();
4509 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004510 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004511 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4512 "in '.bundle_align_mode' "
4513 "directive") ||
4514 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4515 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004516 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004517
4518 // Because of AlignSizePow2's verified range we can safely truncate it to
4519 // unsigned.
4520 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4521 return false;
4522}
4523
Jim Grosbach4b905842013-09-20 23:08:21 +00004524/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004525/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004526bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004527 if (checkForValidSection())
4528 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004529 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004530
Nirav Dave1a9044b2016-10-24 14:35:29 +00004531 StringRef Option;
4532 SMLoc Loc = getTok().getLoc();
4533 const char *kInvalidOptionError =
4534 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004535
Nirav Dave1a9044b2016-10-24 14:35:29 +00004536 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004537 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4538 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004539 parseToken(AsmToken::EndOfStatement,
4540 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004541 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004542 AlignToEnd = true;
4543 }
4544
Eli Bendersky802b6282013-01-07 21:51:08 +00004545 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004546 return false;
4547}
4548
Jim Grosbach4b905842013-09-20 23:08:21 +00004549/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004550/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004551bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004552 if (checkForValidSection() ||
4553 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004554 "unexpected token in '.bundle_unlock' directive"))
4555 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004556
4557 getStreamer().EmitBundleUnlock();
4558 return false;
4559}
4560
Jim Grosbach4b905842013-09-20 23:08:21 +00004561/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004562/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004563bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Petr Hosek67a94a72016-05-28 05:57:48 +00004564 SMLoc NumBytesLoc = Lexer.getLoc();
4565 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004566 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004567 return true;
4568
4569 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004570 if (parseOptionalToken(AsmToken::Comma))
4571 if (parseAbsoluteExpression(FillExpr))
4572 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4573 if (parseToken(AsmToken::EndOfStatement))
4574 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004575
Eli Bendersky17233942013-01-15 22:59:42 +00004576 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004577 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004578
4579 return false;
4580}
4581
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004582/// parseDirectiveDCB
4583/// ::= .dcb.{b, l, w} expression, expression
4584bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004585 SMLoc NumValuesLoc = Lexer.getLoc();
4586 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004587 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004588 return true;
4589
4590 if (NumValues < 0) {
4591 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4592 return false;
4593 }
4594
4595 if (parseToken(AsmToken::Comma,
4596 "unexpected token in '" + Twine(IDVal) + "' directive"))
4597 return true;
4598
4599 const MCExpr *Value;
4600 SMLoc ExprLoc = getLexer().getLoc();
4601 if (parseExpression(Value))
4602 return true;
4603
4604 // Special case constant expressions to match code generator.
4605 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4606 assert(Size <= 8 && "Invalid size");
4607 uint64_t IntValue = MCE->getValue();
4608 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4609 return Error(ExprLoc, "literal value out of range for directive");
4610 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4611 getStreamer().EmitIntValue(IntValue, Size);
4612 } else {
4613 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4614 getStreamer().EmitValue(Value, Size, ExprLoc);
4615 }
4616
4617 if (parseToken(AsmToken::EndOfStatement,
4618 "unexpected token in '" + Twine(IDVal) + "' directive"))
4619 return true;
4620
4621 return false;
4622}
4623
4624/// parseDirectiveRealDCB
4625/// ::= .dcb.{d, s} expression, expression
4626bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004627 SMLoc NumValuesLoc = Lexer.getLoc();
4628 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004629 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004630 return true;
4631
4632 if (NumValues < 0) {
4633 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4634 return false;
4635 }
4636
4637 if (parseToken(AsmToken::Comma,
4638 "unexpected token in '" + Twine(IDVal) + "' directive"))
4639 return true;
4640
4641 APInt AsInt;
4642 if (parseRealValue(Semantics, AsInt))
4643 return true;
4644
4645 if (parseToken(AsmToken::EndOfStatement,
4646 "unexpected token in '" + Twine(IDVal) + "' directive"))
4647 return true;
4648
4649 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4650 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4651 AsInt.getBitWidth() / 8);
4652
4653 return false;
4654}
4655
Petr Hosek85b2f672016-09-23 21:53:36 +00004656/// parseDirectiveDS
4657/// ::= .ds.{b, d, l, p, s, w, x} expression
4658bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004659 SMLoc NumValuesLoc = Lexer.getLoc();
4660 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004661 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004662 return true;
4663
4664 if (NumValues < 0) {
4665 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4666 return false;
4667 }
4668
4669 if (parseToken(AsmToken::EndOfStatement,
4670 "unexpected token in '" + Twine(IDVal) + "' directive"))
4671 return true;
4672
4673 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4674 getStreamer().emitFill(Size, 0);
4675
4676 return false;
4677}
4678
Jim Grosbach4b905842013-09-20 23:08:21 +00004679/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004680/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004681bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004682 if (checkForValidSection())
4683 return true;
4684
Nirav Dave1a9044b2016-10-24 14:35:29 +00004685 auto parseOp = [&]() -> bool {
4686 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004687 if (parseExpression(Value))
4688 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004689 if (Signed)
4690 getStreamer().EmitSLEB128Value(Value);
4691 else
4692 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004693 return false;
4694 };
Eli Bendersky17233942013-01-15 22:59:42 +00004695
Nirav Dave1a9044b2016-10-24 14:35:29 +00004696 if (parseMany(parseOp))
4697 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004698
4699 return false;
4700}
4701
Jim Grosbach4b905842013-09-20 23:08:21 +00004702/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004703/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004704bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004705 auto parseOp = [&]() -> bool {
4706 StringRef Name;
4707 SMLoc Loc = getTok().getLoc();
4708 if (parseIdentifier(Name))
4709 return Error(Loc, "expected identifier");
4710 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004711
Nirav Dave1a9044b2016-10-24 14:35:29 +00004712 // Assembler local symbols don't make any sense here. Complain loudly.
4713 if (Sym->isTemporary())
4714 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004715
Nirav Dave1a9044b2016-10-24 14:35:29 +00004716 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4717 return Error(Loc, "unable to emit symbol attribute");
4718 return false;
4719 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004720
Nirav Dave1a9044b2016-10-24 14:35:29 +00004721 if (parseMany(parseOp))
4722 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004723 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004724}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004725
Jim Grosbach4b905842013-09-20 23:08:21 +00004726/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004727/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004728bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004729 if (checkForValidSection())
4730 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004731
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004732 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004733 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004734 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004735 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004736
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004737 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004738 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004739
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004740 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004741 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004742 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004743
4744 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004745 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004746 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004747 return true;
4748
4749 int64_t Pow2Alignment = 0;
4750 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004751 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004752 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004753 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004754 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004755 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004756
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004757 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4758 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004759 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4760
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004761 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004762 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4763 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004764 if (!isPowerOf2_64(Pow2Alignment))
4765 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4766 Pow2Alignment = Log2_64(Pow2Alignment);
4767 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004768 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004769
Nirav Dave1a9044b2016-10-24 14:35:29 +00004770 if (parseToken(AsmToken::EndOfStatement,
4771 "unexpected token in '.comm' or '.lcomm' directive"))
4772 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004773
Chris Lattner28ad7542009-07-09 17:25:12 +00004774 // NOTE: a size of zero for a .comm should create a undefined symbol
4775 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004776 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004777 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004778 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004779
Eric Christopherbc818852010-05-14 01:38:54 +00004780 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004781 // may internally end up wanting an alignment in bytes.
4782 // FIXME: Diagnose overflow.
4783 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004784 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004785 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004786
Rafael Espindola13a79bb2017-02-02 21:26:06 +00004787 Sym->redefineIfPossible();
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004788 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004789 return Error(IDLoc, "invalid symbol redefinition");
4790
Chris Lattner28ad7542009-07-09 17:25:12 +00004791 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004792 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004793 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004794 return false;
4795 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004796
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004797 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004798 return false;
4799}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004800
Jim Grosbach4b905842013-09-20 23:08:21 +00004801/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004802/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004803bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004804 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004805 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004806
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004807 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004808 if (parseToken(AsmToken::EndOfStatement,
4809 "unexpected token in '.abort' directive"))
4810 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004811
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004812 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004813 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004814 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004815 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004816 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004817
4818 return false;
4819}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004820
Jim Grosbach4b905842013-09-20 23:08:21 +00004821/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004822/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004823bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004824 // Allow the strings to have escaped octal character sequence.
4825 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004826 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004827
Nirav Davea645433c2016-07-18 15:24:03 +00004828 if (check(getTok().isNot(AsmToken::String),
4829 "expected string in '.include' directive") ||
4830 parseEscapedString(Filename) ||
4831 check(getTok().isNot(AsmToken::EndOfStatement),
4832 "unexpected token in '.include' directive") ||
4833 // Attempt to switch the lexer to the included file before consuming the
4834 // end of statement to avoid losing it when we switch.
4835 check(enterIncludeFile(Filename), IncludeLoc,
4836 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004837 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004838
4839 return false;
4840}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004841
Jim Grosbach4b905842013-09-20 23:08:21 +00004842/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004843/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004844bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004845 // Allow the strings to have escaped octal character sequence.
4846 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004847 SMLoc IncbinLoc = getTok().getLoc();
4848 if (check(getTok().isNot(AsmToken::String),
4849 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00004850 parseEscapedString(Filename))
4851 return true;
4852
4853 int64_t Skip = 0;
4854 const MCExpr *Count = nullptr;
4855 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004856 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00004857 // The skip expression can be omitted while specifying the count, e.g:
4858 // .incbin "filename",,4
4859 if (getTok().isNot(AsmToken::Comma)) {
4860 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4861 return true;
4862 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00004863 if (parseOptionalToken(AsmToken::Comma)) {
4864 CountLoc = getTok().getLoc();
4865 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00004866 return true;
4867 }
4868 }
4869
4870 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004871 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004872 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004873
Petr Hosek2f4ac442016-09-23 00:41:06 +00004874 if (check(Skip < 0, SkipLoc, "skip is negative"))
4875 return true;
4876
Nirav Dave1ab71992016-07-18 19:35:21 +00004877 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00004878 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00004879 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004880 return false;
4881}
4882
Jim Grosbach4b905842013-09-20 23:08:21 +00004883/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004884/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4885bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004886 TheCondStack.push_back(TheCondState);
4887 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004888 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004889 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004890 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004891 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004892 if (parseAbsoluteExpression(ExprValue) ||
4893 parseToken(AsmToken::EndOfStatement,
4894 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004895 return true;
4896
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004897 switch (DirKind) {
4898 default:
4899 llvm_unreachable("unsupported directive");
4900 case DK_IF:
4901 case DK_IFNE:
4902 break;
4903 case DK_IFEQ:
4904 ExprValue = ExprValue == 0;
4905 break;
4906 case DK_IFGE:
4907 ExprValue = ExprValue >= 0;
4908 break;
4909 case DK_IFGT:
4910 ExprValue = ExprValue > 0;
4911 break;
4912 case DK_IFLE:
4913 ExprValue = ExprValue <= 0;
4914 break;
4915 case DK_IFLT:
4916 ExprValue = ExprValue < 0;
4917 break;
4918 }
4919
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004920 TheCondState.CondMet = ExprValue;
4921 TheCondState.Ignore = !TheCondState.CondMet;
4922 }
4923
4924 return false;
4925}
4926
Jim Grosbach4b905842013-09-20 23:08:21 +00004927/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004928/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004929bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004930 TheCondStack.push_back(TheCondState);
4931 TheCondState.TheCond = AsmCond::IfCond;
4932
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004933 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004934 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004935 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004936 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004937
Nirav Davea645433c2016-07-18 15:24:03 +00004938 if (parseToken(AsmToken::EndOfStatement,
4939 "unexpected token in '.ifb' directive"))
4940 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004941
4942 TheCondState.CondMet = ExpectBlank == Str.empty();
4943 TheCondState.Ignore = !TheCondState.CondMet;
4944 }
4945
4946 return false;
4947}
4948
Jim Grosbach4b905842013-09-20 23:08:21 +00004949/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004950/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004951/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004952bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004953 TheCondStack.push_back(TheCondState);
4954 TheCondState.TheCond = AsmCond::IfCond;
4955
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004956 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004957 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004958 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004959 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004960
Nirav Davea645433c2016-07-18 15:24:03 +00004961 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4962 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004963
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004964 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004965
Nirav Davea645433c2016-07-18 15:24:03 +00004966 if (parseToken(AsmToken::EndOfStatement,
4967 "unexpected token in '.ifc' directive"))
4968 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004969
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004970 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004971 TheCondState.Ignore = !TheCondState.CondMet;
4972 }
4973
4974 return false;
4975}
4976
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004977/// parseDirectiveIfeqs
4978/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004979bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004980 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004981 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004982 return TokError("expected string parameter for '.ifeqs' directive");
4983 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004984 }
4985
4986 StringRef String1 = getTok().getStringContents();
4987 Lex();
4988
4989 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004990 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004991 return TokError(
4992 "expected comma after first string for '.ifeqs' directive");
4993 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004994 }
4995
4996 Lex();
4997
4998 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004999 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00005000 return TokError("expected string parameter for '.ifeqs' directive");
5001 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005002 }
5003
5004 StringRef String2 = getTok().getStringContents();
5005 Lex();
5006
5007 TheCondStack.push_back(TheCondState);
5008 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00005009 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005010 TheCondState.Ignore = !TheCondState.CondMet;
5011
5012 return false;
5013}
5014
Jim Grosbach4b905842013-09-20 23:08:21 +00005015/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00005016/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00005017bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005018 StringRef Name;
5019 TheCondStack.push_back(TheCondState);
5020 TheCondState.TheCond = AsmCond::IfCond;
5021
5022 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005023 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005024 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00005025 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
5026 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
5027 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005028
Jim Grosbach6f482002015-05-18 18:43:14 +00005029 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005030
5031 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00005032 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005033 else
Craig Topper353eda42014-04-24 06:44:33 +00005034 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005035 TheCondState.Ignore = !TheCondState.CondMet;
5036 }
5037
5038 return false;
5039}
5040
Jim Grosbach4b905842013-09-20 23:08:21 +00005041/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005042/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00005043bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005044 if (TheCondState.TheCond != AsmCond::IfCond &&
5045 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00005046 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
5047 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005048 TheCondState.TheCond = AsmCond::ElseIfCond;
5049
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005050 bool LastIgnoreState = false;
5051 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00005052 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005053 if (LastIgnoreState || TheCondState.CondMet) {
5054 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005055 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00005056 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005057 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005058 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005059 return true;
5060
Nirav Dave1a9044b2016-10-24 14:35:29 +00005061 if (parseToken(AsmToken::EndOfStatement,
5062 "unexpected token in '.elseif' directive"))
5063 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00005064
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005065 TheCondState.CondMet = ExprValue;
5066 TheCondState.Ignore = !TheCondState.CondMet;
5067 }
5068
5069 return false;
5070}
5071
Jim Grosbach4b905842013-09-20 23:08:21 +00005072/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005073/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00005074bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005075 if (parseToken(AsmToken::EndOfStatement,
5076 "unexpected token in '.else' directive"))
5077 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005078
5079 if (TheCondState.TheCond != AsmCond::IfCond &&
5080 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00005081 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
5082 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005083 TheCondState.TheCond = AsmCond::ElseCond;
5084 bool LastIgnoreState = false;
5085 if (!TheCondStack.empty())
5086 LastIgnoreState = TheCondStack.back().Ignore;
5087 if (LastIgnoreState || TheCondState.CondMet)
5088 TheCondState.Ignore = true;
5089 else
5090 TheCondState.Ignore = false;
5091
5092 return false;
5093}
5094
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005095/// parseDirectiveEnd
5096/// ::= .end
5097bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005098 if (parseToken(AsmToken::EndOfStatement,
5099 "unexpected token in '.end' directive"))
5100 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005101
5102 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00005103 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005104
5105 return false;
5106}
5107
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005108/// parseDirectiveError
5109/// ::= .err
5110/// ::= .error [string]
5111bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
5112 if (!TheCondStack.empty()) {
5113 if (TheCondStack.back().Ignore) {
5114 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005115 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005116 }
5117 }
5118
5119 if (!WithMessage)
5120 return Error(L, ".err encountered");
5121
5122 StringRef Message = ".error directive invoked in source file";
5123 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005124 if (Lexer.isNot(AsmToken::String))
5125 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005126
5127 Message = getTok().getStringContents();
5128 Lex();
5129 }
5130
Nirav Dave2364748a2016-09-16 18:30:20 +00005131 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005132}
5133
Nico Weber404012b2014-07-24 16:26:06 +00005134/// parseDirectiveWarning
5135/// ::= .warning [string]
5136bool AsmParser::parseDirectiveWarning(SMLoc L) {
5137 if (!TheCondStack.empty()) {
5138 if (TheCondStack.back().Ignore) {
5139 eatToEndOfStatement();
5140 return false;
5141 }
5142 }
5143
5144 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00005145
5146 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005147 if (Lexer.isNot(AsmToken::String))
5148 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00005149
5150 Message = getTok().getStringContents();
5151 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00005152 if (parseToken(AsmToken::EndOfStatement,
5153 "expected end of statement in '.warning' directive"))
5154 return true;
Nico Weber404012b2014-07-24 16:26:06 +00005155 }
5156
Nirav Dave2364748a2016-09-16 18:30:20 +00005157 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00005158}
5159
Jim Grosbach4b905842013-09-20 23:08:21 +00005160/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005161/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00005162bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005163 if (parseToken(AsmToken::EndOfStatement,
5164 "unexpected token in '.endif' directive"))
5165 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005166
Jim Grosbach4b905842013-09-20 23:08:21 +00005167 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00005168 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
5169 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005170 if (!TheCondStack.empty()) {
5171 TheCondState = TheCondStack.back();
5172 TheCondStack.pop_back();
5173 }
5174
5175 return false;
5176}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00005177
Eli Bendersky17233942013-01-15 22:59:42 +00005178void AsmParser::initializeDirectiveKindMap() {
5179 DirectiveKindMap[".set"] = DK_SET;
5180 DirectiveKindMap[".equ"] = DK_EQU;
5181 DirectiveKindMap[".equiv"] = DK_EQUIV;
5182 DirectiveKindMap[".ascii"] = DK_ASCII;
5183 DirectiveKindMap[".asciz"] = DK_ASCIZ;
5184 DirectiveKindMap[".string"] = DK_STRING;
5185 DirectiveKindMap[".byte"] = DK_BYTE;
5186 DirectiveKindMap[".short"] = DK_SHORT;
5187 DirectiveKindMap[".value"] = DK_VALUE;
5188 DirectiveKindMap[".2byte"] = DK_2BYTE;
5189 DirectiveKindMap[".long"] = DK_LONG;
5190 DirectiveKindMap[".int"] = DK_INT;
5191 DirectiveKindMap[".4byte"] = DK_4BYTE;
5192 DirectiveKindMap[".quad"] = DK_QUAD;
5193 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00005194 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00005195 DirectiveKindMap[".single"] = DK_SINGLE;
5196 DirectiveKindMap[".float"] = DK_FLOAT;
5197 DirectiveKindMap[".double"] = DK_DOUBLE;
5198 DirectiveKindMap[".align"] = DK_ALIGN;
5199 DirectiveKindMap[".align32"] = DK_ALIGN32;
5200 DirectiveKindMap[".balign"] = DK_BALIGN;
5201 DirectiveKindMap[".balignw"] = DK_BALIGNW;
5202 DirectiveKindMap[".balignl"] = DK_BALIGNL;
5203 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
5204 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
5205 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
5206 DirectiveKindMap[".org"] = DK_ORG;
5207 DirectiveKindMap[".fill"] = DK_FILL;
5208 DirectiveKindMap[".zero"] = DK_ZERO;
5209 DirectiveKindMap[".extern"] = DK_EXTERN;
5210 DirectiveKindMap[".globl"] = DK_GLOBL;
5211 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00005212 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
5213 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
5214 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
5215 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
5216 DirectiveKindMap[".reference"] = DK_REFERENCE;
5217 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
5218 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
5219 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
5220 DirectiveKindMap[".comm"] = DK_COMM;
5221 DirectiveKindMap[".common"] = DK_COMMON;
5222 DirectiveKindMap[".lcomm"] = DK_LCOMM;
5223 DirectiveKindMap[".abort"] = DK_ABORT;
5224 DirectiveKindMap[".include"] = DK_INCLUDE;
5225 DirectiveKindMap[".incbin"] = DK_INCBIN;
5226 DirectiveKindMap[".code16"] = DK_CODE16;
5227 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
5228 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005229 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00005230 DirectiveKindMap[".irp"] = DK_IRP;
5231 DirectiveKindMap[".irpc"] = DK_IRPC;
5232 DirectiveKindMap[".endr"] = DK_ENDR;
5233 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
5234 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
5235 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
5236 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00005237 DirectiveKindMap[".ifeq"] = DK_IFEQ;
5238 DirectiveKindMap[".ifge"] = DK_IFGE;
5239 DirectiveKindMap[".ifgt"] = DK_IFGT;
5240 DirectiveKindMap[".ifle"] = DK_IFLE;
5241 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00005242 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00005243 DirectiveKindMap[".ifb"] = DK_IFB;
5244 DirectiveKindMap[".ifnb"] = DK_IFNB;
5245 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005246 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00005247 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00005248 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00005249 DirectiveKindMap[".ifdef"] = DK_IFDEF;
5250 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
5251 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
5252 DirectiveKindMap[".elseif"] = DK_ELSEIF;
5253 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005254 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00005255 DirectiveKindMap[".endif"] = DK_ENDIF;
5256 DirectiveKindMap[".skip"] = DK_SKIP;
5257 DirectiveKindMap[".space"] = DK_SPACE;
5258 DirectiveKindMap[".file"] = DK_FILE;
5259 DirectiveKindMap[".line"] = DK_LINE;
5260 DirectiveKindMap[".loc"] = DK_LOC;
5261 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005262 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005263 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005264 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
5265 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00005266 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005267 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00005268 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner06d02d02018-09-07 21:30:52 +00005269 DirectiveKindMap[".cv_string"] = DK_CV_STRING;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005270 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
5271 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00005272 DirectiveKindMap[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET;
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00005273 DirectiveKindMap[".cv_fpo_data"] = DK_CV_FPO_DATA;
Eli Bendersky17233942013-01-15 22:59:42 +00005274 DirectiveKindMap[".sleb128"] = DK_SLEB128;
5275 DirectiveKindMap[".uleb128"] = DK_ULEB128;
5276 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
5277 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
5278 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
5279 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
5280 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
5281 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
5282 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
5283 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
5284 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
5285 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
5286 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
5287 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
5288 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
5289 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
5290 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
5291 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00005292 DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN;
Eli Bendersky17233942013-01-15 22:59:42 +00005293 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
5294 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
5295 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00005296 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Luke Cheeseman41a9e532018-12-21 10:45:08 +00005297 DirectiveKindMap[".cfi_b_key_frame"] = DK_CFI_B_KEY_FRAME;
Eli Bendersky17233942013-01-15 22:59:42 +00005298 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
5299 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
5300 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00005301 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00005302 DirectiveKindMap[".endm"] = DK_ENDM;
5303 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
5304 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005305 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005306 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00005307 DirectiveKindMap[".warning"] = DK_WARNING;
Michael Zuckerman56704612017-05-01 13:20:12 +00005308 DirectiveKindMap[".altmacro"] = DK_ALTMACRO;
5309 DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00005310 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00005311 DirectiveKindMap[".dc"] = DK_DC;
5312 DirectiveKindMap[".dc.a"] = DK_DC_A;
5313 DirectiveKindMap[".dc.b"] = DK_DC_B;
5314 DirectiveKindMap[".dc.d"] = DK_DC_D;
5315 DirectiveKindMap[".dc.l"] = DK_DC_L;
5316 DirectiveKindMap[".dc.s"] = DK_DC_S;
5317 DirectiveKindMap[".dc.w"] = DK_DC_W;
5318 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00005319 DirectiveKindMap[".dcb"] = DK_DCB;
5320 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
5321 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
5322 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
5323 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
5324 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
5325 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00005326 DirectiveKindMap[".ds"] = DK_DS;
5327 DirectiveKindMap[".ds.b"] = DK_DS_B;
5328 DirectiveKindMap[".ds.d"] = DK_DS_D;
5329 DirectiveKindMap[".ds.l"] = DK_DS_L;
5330 DirectiveKindMap[".ds.p"] = DK_DS_P;
5331 DirectiveKindMap[".ds.s"] = DK_DS_S;
5332 DirectiveKindMap[".ds.w"] = DK_DS_W;
5333 DirectiveKindMap[".ds.x"] = DK_DS_X;
Coby Tayree01e53202017-10-02 14:36:31 +00005334 DirectiveKindMap[".print"] = DK_PRINT;
Peter Collingbourne3e227332018-07-17 22:17:18 +00005335 DirectiveKindMap[".addrsig"] = DK_ADDRSIG;
5336 DirectiveKindMap[".addrsig_sym"] = DK_ADDRSIG_SYM;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00005337}
5338
Jim Grosbach4b905842013-09-20 23:08:21 +00005339MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005340 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005341
Rafael Espindola34b9c512012-06-03 23:57:14 +00005342 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005343 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005344 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00005345 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005346 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00005347 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005348 }
5349
Rafael Espindola34b9c512012-06-03 23:57:14 +00005350 if (Lexer.is(AsmToken::Identifier) &&
Nirav Davee24fcd52018-07-18 16:17:03 +00005351 (getTok().getIdentifier() == ".rep" ||
5352 getTok().getIdentifier() == ".rept" ||
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00005353 getTok().getIdentifier() == ".irp" ||
5354 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005355 ++NestLevel;
5356 }
5357
5358 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00005359 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005360 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005361 EndToken = getTok();
5362 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005363 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005364 printError(getTok().getLoc(),
5365 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00005366 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005367 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005368 break;
5369 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005370 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005371 }
5372
Rafael Espindola34b9c512012-06-03 23:57:14 +00005373 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005374 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005375 }
5376
5377 const char *BodyStart = StartToken.getLoc().getPointer();
5378 const char *BodyEnd = EndToken.getLoc().getPointer();
5379 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5380
Rafael Espindola34b9c512012-06-03 23:57:14 +00005381 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005382 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00005383 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005384}
5385
Jim Grosbach4b905842013-09-20 23:08:21 +00005386void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005387 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005388 OS << ".endr\n";
5389
Rafael Espindola3560ff22014-08-27 20:03:13 +00005390 std::unique_ptr<MemoryBuffer> Instantiation =
5391 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005392
Rafael Espindola34b9c512012-06-03 23:57:14 +00005393 // Create the macro instantiation object and add to the current macro
5394 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005395 MacroInstantiation *MI = new MacroInstantiation(
5396 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005397 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005398
Rafael Espindola34b9c512012-06-03 23:57:14 +00005399 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005400 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005401 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005402 Lex();
5403}
5404
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005405/// parseDirectiveRept
5406/// ::= .rep | .rept count
5407bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005408 const MCExpr *CountExpr;
5409 SMLoc CountLoc = getTok().getLoc();
5410 if (parseExpression(CountExpr))
5411 return true;
5412
Rafael Espindola34b9c512012-06-03 23:57:14 +00005413 int64_t Count;
Nirav Dave6c0665e2018-04-30 19:22:40 +00005414 if (!CountExpr->evaluateAsAbsolute(Count, getStreamer().getAssemblerPtr())) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005415 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5416 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005417
Nirav Davea645433c2016-07-18 15:24:03 +00005418 if (check(Count < 0, CountLoc, "Count is negative") ||
5419 parseToken(AsmToken::EndOfStatement,
5420 "unexpected token in '" + Dir + "' directive"))
5421 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005422
5423 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005424 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005425 if (!M)
5426 return true;
5427
5428 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5429 // to hold the macro body with substitutions.
5430 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005431 raw_svector_ostream OS(Buf);
5432 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005433 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5434 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005435 return true;
5436 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005437 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005438
5439 return false;
5440}
5441
Jim Grosbach4b905842013-09-20 23:08:21 +00005442/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005443/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005444bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005445 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005446 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005447 if (check(parseIdentifier(Parameter.Name),
5448 "expected identifier in '.irp' directive") ||
5449 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5450 parseMacroArguments(nullptr, A) ||
5451 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005452 return true;
5453
Rafael Espindola768b41c2012-06-15 14:02:34 +00005454 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005455 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005456 if (!M)
5457 return true;
5458
5459 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5460 // to hold the macro body with substitutions.
5461 SmallString<256> Buf;
5462 raw_svector_ostream OS(Buf);
5463
Craig Topper84008482015-10-10 05:38:14 +00005464 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005465 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5466 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005467 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005468 return true;
5469 }
5470
Jim Grosbach4b905842013-09-20 23:08:21 +00005471 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005472
5473 return false;
5474}
5475
Jim Grosbach4b905842013-09-20 23:08:21 +00005476/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005477/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005478bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005479 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005480 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005481
5482 if (check(parseIdentifier(Parameter.Name),
5483 "expected identifier in '.irpc' directive") ||
5484 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5485 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005486 return true;
5487
5488 if (A.size() != 1 || A.front().size() != 1)
5489 return TokError("unexpected token in '.irpc' directive");
5490
5491 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005492 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5493 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005494
5495 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005496 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005497 if (!M)
5498 return true;
5499
5500 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5501 // to hold the macro body with substitutions.
5502 SmallString<256> Buf;
5503 raw_svector_ostream OS(Buf);
5504
5505 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005506 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005507 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005508 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005509
Toma Tabacu217116e2015-04-27 10:50:29 +00005510 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5511 // This is undocumented, but GAS seems to support it.
5512 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005513 return true;
5514 }
5515
Jim Grosbach4b905842013-09-20 23:08:21 +00005516 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005517
5518 return false;
5519}
5520
Jim Grosbach4b905842013-09-20 23:08:21 +00005521bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005522 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005523 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005524
5525 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005526 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005527 assert(getLexer().is(AsmToken::EndOfStatement));
5528
Jim Grosbach4b905842013-09-20 23:08:21 +00005529 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005530 return false;
5531}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005532
Jim Grosbach4b905842013-09-20 23:08:21 +00005533bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005534 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005535 const MCExpr *Value;
5536 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005537 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005538 return true;
5539 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5540 if (!MCE)
5541 return Error(ExprLoc, "unexpected expression in _emit");
5542 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005543 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005544 return Error(ExprLoc, "literal value out of range for directive");
5545
Craig Topper7d5b2312015-10-10 05:25:02 +00005546 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005547 return false;
5548}
5549
Jim Grosbach4b905842013-09-20 23:08:21 +00005550bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005551 const MCExpr *Value;
5552 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005553 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005554 return true;
5555 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5556 if (!MCE)
5557 return Error(ExprLoc, "unexpected expression in align");
5558 uint64_t IntValue = MCE->getValue();
5559 if (!isPowerOf2_64(IntValue))
5560 return Error(ExprLoc, "literal value not a power of two greater then zero");
5561
Craig Topper7d5b2312015-10-10 05:25:02 +00005562 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005563 return false;
5564}
5565
Coby Tayree01e53202017-10-02 14:36:31 +00005566bool AsmParser::parseDirectivePrint(SMLoc DirectiveLoc) {
5567 const AsmToken StrTok = getTok();
5568 Lex();
5569 if (StrTok.isNot(AsmToken::String) || StrTok.getString().front() != '"')
5570 return Error(DirectiveLoc, "expected double quoted string after .print");
5571 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5572 return true;
5573 llvm::outs() << StrTok.getStringContents() << '\n';
5574 return false;
5575}
5576
Peter Collingbourne3e227332018-07-17 22:17:18 +00005577bool AsmParser::parseDirectiveAddrsig() {
5578 getStreamer().EmitAddrsig();
5579 return false;
5580}
5581
5582bool AsmParser::parseDirectiveAddrsigSym() {
5583 StringRef Name;
5584 if (check(parseIdentifier(Name),
5585 "expected identifier in '.addrsig_sym' directive"))
5586 return true;
5587 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
5588 getStreamer().EmitAddrsigSym(Sym);
5589 return false;
5590}
5591
Chad Rosierf43fcf52013-02-13 21:27:17 +00005592// We are comparing pointers, but the pointers are relative to a single string.
5593// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005594static int rewritesSort(const AsmRewrite *AsmRewriteA,
5595 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005596 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5597 return -1;
5598 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5599 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005600
Chad Rosierfce4fab2013-04-08 17:43:47 +00005601 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5602 // rewrite to the same location. Make sure the SizeDirective rewrite is
5603 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5604 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005605 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5606 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005607 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005608
Jim Grosbach4b905842013-09-20 23:08:21 +00005609 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5610 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005611 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005612 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005613}
5614
Jim Grosbach4b905842013-09-20 23:08:21 +00005615bool AsmParser::parseMSInlineAsm(
5616 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00005617 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
Jim Grosbach4b905842013-09-20 23:08:21 +00005618 SmallVectorImpl<std::string> &Constraints,
5619 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5620 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005621 SmallVector<void *, 4> InputDecls;
5622 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005623 SmallVector<bool, 4> InputDeclsAddressOf;
5624 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005625 SmallVector<std::string, 4> InputConstraints;
5626 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005627 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005628
Benjamin Kramer1a136112013-02-15 20:37:21 +00005629 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005630
5631 // Prime the lexer.
5632 Lex();
5633
5634 // While we have input, parse each statement.
5635 unsigned InputIdx = 0;
5636 unsigned OutputIdx = 0;
5637 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005638 // Parse curly braces marking block start/end
5639 if (parseCurlyBlockScope(AsmStrRewrites))
5640 continue;
5641
Eli Friedman0f4871d2012-10-22 23:58:19 +00005642 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005643 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005644
Nirav Dave2364748a2016-09-16 18:30:20 +00005645 if (StatementErr || Info.ParseError) {
5646 // Emit pending errors if any exist.
5647 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005648 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005649 }
5650
5651 // No pending error should exist here.
5652 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005653
Benjamin Kramer1a136112013-02-15 20:37:21 +00005654 if (Info.Opcode == ~0U)
5655 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005656
Benjamin Kramer1a136112013-02-15 20:37:21 +00005657 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005658
Benjamin Kramer1a136112013-02-15 20:37:21 +00005659 // Build the list of clobbers, outputs and inputs.
5660 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005661 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005662
Benjamin Kramer1a136112013-02-15 20:37:21 +00005663 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005664 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005665 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005666
Benjamin Kramer1a136112013-02-15 20:37:21 +00005667 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005668 if (Operand.isReg() && !Operand.needAddressOf() &&
5669 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005670 unsigned NumDefs = Desc.getNumDefs();
5671 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005672 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5673 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005674 continue;
5675 }
5676
5677 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005678 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005679 if (SymName.empty())
5680 continue;
5681
David Blaikie960ea3f2014-06-08 16:18:35 +00005682 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005683 if (!OpDecl)
5684 continue;
5685
5686 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005687 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005688 if (isOutput) {
5689 ++InputIdx;
5690 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005691 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005692 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005693 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005694 } else {
5695 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005696 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5697 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005698 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005699 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005700 }
Reid Kleckneree088972013-12-10 18:27:32 +00005701
5702 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005703 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5704 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005705 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005706 }
5707
5708 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005709 NumOutputs = OutputDecls.size();
5710 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005711
5712 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005713 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5714 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5715 ClobberRegs.end());
5716 Clobbers.assign(ClobberRegs.size(), std::string());
5717 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5718 raw_string_ostream OS(Clobbers[I]);
5719 IP->printRegName(OS, ClobberRegs[I]);
5720 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005721
5722 // Merge the various outputs and inputs. Output are expected first.
5723 if (NumOutputs || NumInputs) {
5724 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005725 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005726 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005727 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005728 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005729 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005730 }
5731 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005732 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005733 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005734 }
5735 }
5736
5737 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005738 std::string AsmStringIR;
5739 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005740 StringRef ASMString =
5741 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5742 const char *AsmStart = ASMString.begin();
5743 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005744 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005745 for (const AsmRewrite &AR : AsmStrRewrites) {
5746 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005747
David Majnemer8114c1a2014-06-23 02:17:16 +00005748 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005749 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005750
Chad Rosier120eefd2013-03-19 17:32:17 +00005751 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005752 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005753 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005754
Chad Rosier37e755c2012-10-23 17:43:43 +00005755 // Skip the original expression.
5756 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005757 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005758 continue;
5759 }
5760
Chad Rosierff10ed12013-04-12 16:26:42 +00005761 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005762 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005763 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005764 default:
5765 break;
Coby Tayreed8912892017-08-24 08:46:25 +00005766 case AOK_IntelExpr:
5767 assert(AR.IntelExp.isValid() && "cannot write invalid intel expression");
5768 if (AR.IntelExp.NeedBracs)
5769 OS << "[";
5770 if (AR.IntelExp.hasBaseReg())
5771 OS << AR.IntelExp.BaseReg;
5772 if (AR.IntelExp.hasIndexReg())
5773 OS << (AR.IntelExp.hasBaseReg() ? " + " : "")
5774 << AR.IntelExp.IndexReg;
5775 if (AR.IntelExp.Scale > 1)
5776 OS << " * $$" << AR.IntelExp.Scale;
5777 if (AR.IntelExp.Imm || !AR.IntelExp.hasRegs())
5778 OS << (AR.IntelExp.hasRegs() ? " + $$" : "$$") << AR.IntelExp.Imm;
5779 if (AR.IntelExp.NeedBracs)
5780 OS << "]";
Chad Rosier8bce6642012-10-18 15:49:34 +00005781 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005782 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005783 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005784 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005785 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005786 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005787 break;
5788 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005789 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005790 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005791 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005792 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005793 default: break;
5794 case 8: OS << "byte ptr "; break;
5795 case 16: OS << "word ptr "; break;
5796 case 32: OS << "dword ptr "; break;
5797 case 64: OS << "qword ptr "; break;
5798 case 80: OS << "xword ptr "; break;
5799 case 128: OS << "xmmword ptr "; break;
5800 case 256: OS << "ymmword ptr "; break;
5801 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005802 break;
5803 case AOK_Emit:
5804 OS << ".byte";
5805 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005806 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005807 // MS alignment directives are measured in bytes. If the native assembler
5808 // measures alignment in bytes, we can pass it straight through.
5809 OS << ".align";
5810 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5811 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005812
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005813 // Alignment is in log2 form, so print that instead and skip the original
5814 // immediate.
5815 unsigned Val = AR.Val;
5816 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005817 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005818 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5819 break;
5820 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005821 case AOK_EVEN:
5822 OS << ".even";
5823 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005824 case AOK_EndOfStatement:
5825 OS << "\n\t";
5826 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005827 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005828
Chad Rosier8bce6642012-10-18 15:49:34 +00005829 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005830 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005831 }
5832
5833 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005834 if (AsmStart != AsmEnd)
5835 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005836
5837 AsmString = OS.str();
5838 return false;
5839}
5840
Pete Cooper80d21cb2015-06-22 19:35:57 +00005841namespace llvm {
5842namespace MCParserUtils {
5843
5844/// Returns whether the given symbol is used anywhere in the given expression,
5845/// or subexpressions.
5846static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5847 switch (Value->getKind()) {
5848 case MCExpr::Binary: {
5849 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5850 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5851 isSymbolUsedInExpression(Sym, BE->getRHS());
5852 }
5853 case MCExpr::Target:
5854 case MCExpr::Constant:
5855 return false;
5856 case MCExpr::SymbolRef: {
5857 const MCSymbol &S =
5858 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5859 if (S.isVariable())
5860 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5861 return &S == Sym;
5862 }
5863 case MCExpr::Unary:
5864 return isSymbolUsedInExpression(
5865 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5866 }
5867
5868 llvm_unreachable("Unknown expr kind!");
5869}
5870
5871bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5872 MCAsmParser &Parser, MCSymbol *&Sym,
Nirav Dave7fd992a2018-08-16 16:31:14 +00005873 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005874
5875 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005876 SMLoc EqualLoc = Parser.getTok().getLoc();
Nirav Dave7fd992a2018-08-16 16:31:14 +00005877 if (Parser.parseExpression(Value))
5878 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005879
5880 // Note: we don't count b as used in "a = b". This is to allow
5881 // a = b
5882 // b = c
5883
Nirav Dave1a9044b2016-10-24 14:35:29 +00005884 if (Parser.parseToken(AsmToken::EndOfStatement))
5885 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00005886
5887 // Validate that the LHS is allowed to be a variable (either it has not been
5888 // used as a symbol, or it is an absolute symbol).
5889 Sym = Parser.getContext().lookupSymbol(Name);
5890 if (Sym) {
5891 // Diagnose assignment to a label.
5892 //
5893 // FIXME: Diagnostics. Note the location of the definition as a label.
5894 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5895 if (isSymbolUsedInExpression(Sym, Value))
5896 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005897 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5898 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005899 ; // Allow redefinitions of undefined symbols only used in directives.
5900 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5901 ; // Allow redefinitions of variables that haven't yet been used.
5902 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5903 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5904 else if (!Sym->isVariable())
5905 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5906 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5907 return Parser.Error(EqualLoc,
5908 "invalid reassignment of non-absolute variable '" +
5909 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005910 } else if (Name == ".") {
Oliver Stannard268f42f2016-12-14 10:43:58 +00005911 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005912 return false;
5913 } else
5914 Sym = Parser.getContext().getOrCreateSymbol(Name);
5915
5916 Sym->setRedefinable(allow_redef);
5917
5918 return false;
5919}
5920
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005921} // end namespace MCParserUtils
5922} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005923
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005924/// Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005925MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
Sanne Wouda29338752017-02-08 14:48:05 +00005926 MCStreamer &Out, const MCAsmInfo &MAI,
5927 unsigned CB) {
5928 return new AsmParser(SM, C, Out, MAI, CB);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005929}