blob: b59ac08ad6cc4513c5c1c839cfe513455b89ba6f [file] [log] [blame]
Chris Lattnerb0133452009-06-21 20:16:42 +00001//===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerb0133452009-06-21 20:16:42 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This class implements the parser for assembly files.
10//
11//===----------------------------------------------------------------------===//
12
Daniel Dunbar2af16532010-09-24 01:59:56 +000013#include "llvm/ADT/APFloat.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000014#include "llvm/ADT/APInt.h"
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/None.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000017#include "llvm/ADT/STLExtras.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000018#include "llvm/ADT/SmallString.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000019#include "llvm/ADT/SmallVector.h"
Reid Kleckner26fa1bf2017-09-19 18:14:45 +000020#include "llvm/ADT/StringExtras.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000021#include "llvm/ADT/StringMap.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000022#include "llvm/ADT/StringRef.h"
Daniel Dunbareb6bb322009-07-27 23:20:52 +000023#include "llvm/ADT/Twine.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000024#include "llvm/BinaryFormat/Dwarf.h"
Reid Kleckner7bbe7112019-10-19 01:44:09 +000025#include "llvm/DebugInfo/CodeView/SymbolRecord.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;
Serge Guelton836aa272019-01-20 23:06:45 +0000162 int64_t LineNumber;
Tim Northoverc0bef992016-04-13 19:46:54 +0000163 SMLoc Loc;
Serge Guelton836aa272019-01-20 23:06:45 +0000164 unsigned Buf;
165 CppHashInfoTy() : Filename(), LineNumber(0), Loc(), Buf(0) {}
Tim Northoverc0bef992016-04-13 19:46:54 +0000166 };
167 CppHashInfoTy CppHashInfo;
168
Paul Robinson9c563262019-05-21 11:59:03 +0000169 /// The filename from the first cpp hash file line comment, if any.
170 StringRef FirstCppHashFilename;
171
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000172 /// List of forward directional labels for diagnosis at the end.
Tim Northoverc0bef992016-04-13 19:46:54 +0000173 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
174
Devang Patela173ee52012-01-31 18:14:05 +0000175 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000176 unsigned AssemblerDialect = ~0U;
Devang Patela173ee52012-01-31 18:14:05 +0000177
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000178 /// is Darwin compatibility enabled?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000179 bool IsDarwin = false;
Preston Gurd05500642012-09-19 20:36:12 +0000180
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000181 /// Are we parsing ms-style inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000182 bool ParsingInlineAsm = false;
Chad Rosier49963552012-10-13 00:26:04 +0000183
Paul Robinsoncc7344a2018-06-14 13:38:20 +0000184 /// Did we already inform the user about inconsistent MD5 usage?
185 bool ReportedInconsistentMD5 = false;
186
Craig Topperc81aff72018-09-25 20:55:55 +0000187 // Is alt macro mode enabled.
188 bool AltMacroMode = false;
189
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000190public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000191 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000192 const MCAsmInfo &MAI, unsigned CB);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000193 AsmParser(const AsmParser &) = delete;
194 AsmParser &operator=(const AsmParser &) = delete;
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000195 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000196
Craig Topper59be68f2014-03-08 07:14:16 +0000197 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000198
Craig Topper59be68f2014-03-08 07:14:16 +0000199 void addDirectiveHandler(StringRef Directive,
200 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000201 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000202 }
203
Toma Tabacu11e14a92015-04-21 11:50:52 +0000204 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
205 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
206 }
207
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000208 /// @name MCAsmParser Interface
209 /// {
210
Craig Topper59be68f2014-03-08 07:14:16 +0000211 SourceMgr &getSourceManager() override { return SrcMgr; }
212 MCAsmLexer &getLexer() override { return Lexer; }
213 MCContext &getContext() override { return Ctx; }
214 MCStreamer &getStreamer() override { return Out; }
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000215
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000216 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
217
Craig Topper59be68f2014-03-08 07:14:16 +0000218 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000219 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000220 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000221 else
222 return AssemblerDialect;
223 }
Craig Topper59be68f2014-03-08 07:14:16 +0000224 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000225 AssemblerDialect = i;
226 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000227
Nirav Dave2364748a2016-09-16 18:30:20 +0000228 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
229 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
230 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000231
Craig Topper59be68f2014-03-08 07:14:16 +0000232 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000233
Yunzhong Gao27ea29b2016-09-02 23:15:29 +0000234 void setParsingInlineAsm(bool V) override {
235 ParsingInlineAsm = V;
Reid Kleckner953bdce2018-10-24 20:23:57 +0000236 // When parsing MS inline asm, we must lex 0b1101 and 0ABCH as binary and
237 // hex integer literals.
238 Lexer.setLexMasmIntegers(V);
Yunzhong Gao27ea29b2016-09-02 23:15:29 +0000239 }
Craig Topper59be68f2014-03-08 07:14:16 +0000240 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000241
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000242 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000243 unsigned &NumOutputs, unsigned &NumInputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000244 SmallVectorImpl<std::pair<void *,bool>> &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000245 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000246 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000247 const MCInstrInfo *MII, const MCInstPrinter *IP,
248 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000249
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000250 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000251 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
252 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
253 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000254 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
255 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000256 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000257
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000258 /// Parse a floating point expression using the float \p Semantics
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000259 /// and set \p Res to the value.
260 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
261
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000262 /// Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000263 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000264 bool parseIdentifier(StringRef &Res) override;
265 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000266
Nirav Davef43cc9f2016-10-10 15:24:54 +0000267 bool checkForValidSection() override;
Nirav Davea645433c2016-07-18 15:24:03 +0000268
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000269 /// }
270
271private:
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000272 bool parseStatement(ParseStatementInfo &Info,
273 MCAsmParserSemaCallback *SI);
Marina Yatsina5f5de9f2016-03-07 18:11:16 +0000274 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
Craig Topper3c76c522015-09-20 23:35:59 +0000275 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000276
Jim Grosbach4b905842013-09-20 23:08:21 +0000277 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000278 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000279 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000280 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000281 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000282 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000283
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000284 /// Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000285 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000286
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000287 /// Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000288 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000289
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000290 /// Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000291 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000292
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000293 /// Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000294 ///
295 /// \param M The macro.
296 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000297 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000298
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000299 /// Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000300 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000301
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000302 /// Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000303 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000304
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000305 /// Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000306 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000307
Jim Grosbach4b905842013-09-20 23:08:21 +0000308 void printMacroInstantiations();
309 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Nirav Dave2364748a2016-09-16 18:30:20 +0000310 SMRange Range = None) const {
311 ArrayRef<SMRange> Ranges(Range);
Chris Lattner72845262011-10-16 05:47:55 +0000312 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000313 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000314 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000315
Paul Robinson938d9a02018-03-22 15:48:01 +0000316 /// Should we emit DWARF describing this assembler source? (Returns false if
317 /// the source has .file directives, which means we don't want to generate
318 /// info describing the assembler source itself.)
319 bool enabledGenDwarfForAssembly();
320
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000321 /// Enter the specified file. This returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000322 bool enterIncludeFile(const std::string &Filename);
323
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000324 /// Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000325 /// This returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000326 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
327 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
Daniel Dunbar43235712010-07-18 18:54:11 +0000328
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000329 /// Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000330 /// current token is not set; clients should ensure Lex() is called
331 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000332 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000333 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000334 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000335 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000336
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000337 /// Parse up to the end of statement and a return the contents from the
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000338 /// current token until the end of the statement; the current token on exit
339 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000340 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000341
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000342 /// Parse until the end of a statement or a comma is encountered,
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000343 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000344 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000345
Jim Grosbach4b905842013-09-20 23:08:21 +0000346 bool parseAssignment(StringRef Name, bool allow_redef,
Nirav Dave7fd992a2018-08-16 16:31:14 +0000347 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000348
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000349 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
350 MCBinaryExpr::Opcode &Kind);
351
Jim Grosbach4b905842013-09-20 23:08:21 +0000352 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
353 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
354 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000355
Jim Grosbach4b905842013-09-20 23:08:21 +0000356 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000357
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000358 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
359 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
360
Eli Bendersky17233942013-01-15 22:59:42 +0000361 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000362 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000363 DK_NO_DIRECTIVE, // Placeholder
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000364 DK_SET,
365 DK_EQU,
366 DK_EQUIV,
367 DK_ASCII,
368 DK_ASCIZ,
369 DK_STRING,
370 DK_BYTE,
371 DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000372 DK_RELOC,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000373 DK_VALUE,
374 DK_2BYTE,
375 DK_LONG,
376 DK_INT,
377 DK_4BYTE,
378 DK_QUAD,
379 DK_8BYTE,
380 DK_OCTA,
381 DK_DC,
382 DK_DC_A,
383 DK_DC_B,
384 DK_DC_D,
385 DK_DC_L,
386 DK_DC_S,
387 DK_DC_W,
388 DK_DC_X,
389 DK_DCB,
390 DK_DCB_B,
391 DK_DCB_D,
392 DK_DCB_L,
393 DK_DCB_S,
394 DK_DCB_W,
395 DK_DCB_X,
396 DK_DS,
397 DK_DS_B,
398 DK_DS_D,
399 DK_DS_L,
400 DK_DS_P,
401 DK_DS_S,
402 DK_DS_W,
403 DK_DS_X,
404 DK_SINGLE,
405 DK_FLOAT,
406 DK_DOUBLE,
407 DK_ALIGN,
408 DK_ALIGN32,
409 DK_BALIGN,
410 DK_BALIGNW,
411 DK_BALIGNL,
412 DK_P2ALIGN,
413 DK_P2ALIGNW,
414 DK_P2ALIGNL,
415 DK_ORG,
416 DK_FILL,
417 DK_ENDR,
418 DK_BUNDLE_ALIGN_MODE,
419 DK_BUNDLE_LOCK,
420 DK_BUNDLE_UNLOCK,
421 DK_ZERO,
422 DK_EXTERN,
423 DK_GLOBL,
424 DK_GLOBAL,
425 DK_LAZY_REFERENCE,
426 DK_NO_DEAD_STRIP,
427 DK_SYMBOL_RESOLVER,
428 DK_PRIVATE_EXTERN,
429 DK_REFERENCE,
430 DK_WEAK_DEFINITION,
431 DK_WEAK_REFERENCE,
432 DK_WEAK_DEF_CAN_BE_HIDDEN,
Vedant Kumar13ef84f2019-01-25 18:30:22 +0000433 DK_COLD,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000434 DK_COMM,
435 DK_COMMON,
436 DK_LCOMM,
437 DK_ABORT,
438 DK_INCLUDE,
439 DK_INCBIN,
440 DK_CODE16,
441 DK_CODE16GCC,
442 DK_REPT,
443 DK_IRP,
444 DK_IRPC,
445 DK_IF,
446 DK_IFEQ,
447 DK_IFGE,
448 DK_IFGT,
449 DK_IFLE,
450 DK_IFLT,
451 DK_IFNE,
452 DK_IFB,
453 DK_IFNB,
454 DK_IFC,
455 DK_IFEQS,
456 DK_IFNC,
457 DK_IFNES,
458 DK_IFDEF,
459 DK_IFNDEF,
460 DK_IFNOTDEF,
461 DK_ELSEIF,
462 DK_ELSE,
463 DK_ENDIF,
464 DK_SPACE,
465 DK_SKIP,
466 DK_FILE,
467 DK_LINE,
468 DK_LOC,
469 DK_STABS,
470 DK_CV_FILE,
471 DK_CV_FUNC_ID,
472 DK_CV_INLINE_SITE_ID,
473 DK_CV_LOC,
474 DK_CV_LINETABLE,
475 DK_CV_INLINE_LINETABLE,
476 DK_CV_DEF_RANGE,
477 DK_CV_STRINGTABLE,
Reid Kleckner06d02d02018-09-07 21:30:52 +0000478 DK_CV_STRING,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000479 DK_CV_FILECHECKSUMS,
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000480 DK_CV_FILECHECKSUM_OFFSET,
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000481 DK_CV_FPO_DATA,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000482 DK_CFI_SECTIONS,
483 DK_CFI_STARTPROC,
484 DK_CFI_ENDPROC,
485 DK_CFI_DEF_CFA,
486 DK_CFI_DEF_CFA_OFFSET,
487 DK_CFI_ADJUST_CFA_OFFSET,
488 DK_CFI_DEF_CFA_REGISTER,
489 DK_CFI_OFFSET,
490 DK_CFI_REL_OFFSET,
491 DK_CFI_PERSONALITY,
492 DK_CFI_LSDA,
493 DK_CFI_REMEMBER_STATE,
494 DK_CFI_RESTORE_STATE,
495 DK_CFI_SAME_VALUE,
496 DK_CFI_RESTORE,
497 DK_CFI_ESCAPE,
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000498 DK_CFI_RETURN_COLUMN,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000499 DK_CFI_SIGNAL_FRAME,
500 DK_CFI_UNDEFINED,
501 DK_CFI_REGISTER,
502 DK_CFI_WINDOW_SAVE,
Luke Cheeseman41a9e532018-12-21 10:45:08 +0000503 DK_CFI_B_KEY_FRAME,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000504 DK_MACROS_ON,
505 DK_MACROS_OFF,
506 DK_ALTMACRO,
507 DK_NOALTMACRO,
508 DK_MACRO,
509 DK_EXITM,
510 DK_ENDM,
511 DK_ENDMACRO,
512 DK_PURGEM,
513 DK_SLEB128,
514 DK_ULEB128,
515 DK_ERR,
516 DK_ERROR,
517 DK_WARNING,
Coby Tayree01e53202017-10-02 14:36:31 +0000518 DK_PRINT,
Peter Collingbourne3e227332018-07-17 22:17:18 +0000519 DK_ADDRSIG,
520 DK_ADDRSIG_SYM,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000521 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000522 };
523
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000524 /// Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000525 /// directives parsed by this class.
526 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000527
Nilanjana Basuda60fc82019-08-05 14:16:58 +0000528 // Codeview def_range type parsing.
529 enum CVDefRangeType {
530 CVDR_DEFRANGE = 0, // Placeholder
531 CVDR_DEFRANGE_REGISTER,
532 CVDR_DEFRANGE_FRAMEPOINTER_REL,
533 CVDR_DEFRANGE_SUBFIELD_REGISTER,
534 CVDR_DEFRANGE_REGISTER_REL
535 };
536
537 /// Maps Codeview def_range types --> CVDefRangeType enum, for
538 /// Codeview def_range types parsed by this class.
539 StringMap<CVDefRangeType> CVDefRangeTypeMap;
540
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000541 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000542 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000543 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Nirav Dave1a9044b2016-10-24 14:35:29 +0000544 bool parseDirectiveValue(StringRef IDVal,
545 unsigned Size); // ".byte", ".long", ...
546 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
547 bool parseDirectiveRealValue(StringRef IDVal,
548 const fltSemantics &); // ".single", ...
Jim Grosbach4b905842013-09-20 23:08:21 +0000549 bool parseDirectiveFill(); // ".fill"
550 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000551 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000552 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
553 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000554 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000555 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000556
Eli Bendersky17233942013-01-15 22:59:42 +0000557 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000558 bool parseDirectiveFile(SMLoc DirectiveLoc);
559 bool parseDirectiveLine();
560 bool parseDirectiveLoc();
561 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000562
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000563 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
Reid Kleckner06d02d02018-09-07 21:30:52 +0000564 // ".cv_inline_linetable", ".cv_def_range", ".cv_string"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000565 bool parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000566 bool parseDirectiveCVFuncId();
567 bool parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000568 bool parseDirectiveCVLoc();
569 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000570 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000571 bool parseDirectiveCVDefRange();
Reid Kleckner06d02d02018-09-07 21:30:52 +0000572 bool parseDirectiveCVString();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000573 bool parseDirectiveCVStringTable();
574 bool parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000575 bool parseDirectiveCVFileChecksumOffset();
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000576 bool parseDirectiveCVFPOData();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000577
Eli Bendersky17233942013-01-15 22:59:42 +0000578 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000579 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000580 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000581 bool parseDirectiveCFISections();
582 bool parseDirectiveCFIStartProc();
583 bool parseDirectiveCFIEndProc();
584 bool parseDirectiveCFIDefCfaOffset();
585 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
586 bool parseDirectiveCFIAdjustCfaOffset();
587 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
588 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
589 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
590 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
591 bool parseDirectiveCFIRememberState();
592 bool parseDirectiveCFIRestoreState();
593 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
594 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
595 bool parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000596 bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +0000597 bool parseDirectiveCFISignalFrame();
598 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000599
600 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000601 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000602 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000603 bool parseDirectiveEndMacro(StringRef Directive);
604 bool parseDirectiveMacro(SMLoc DirectiveLoc);
605 bool parseDirectiveMacrosOnOff(StringRef Directive);
Michael Zuckerman56704612017-05-01 13:20:12 +0000606 // alternate macro mode directives
607 bool parseDirectiveAltmacro(StringRef Directive);
Eli Benderskyf483ff92012-12-20 19:05:53 +0000608 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000609 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000610 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000611 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000612 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000613 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000614
Eli Bendersky17233942013-01-15 22:59:42 +0000615 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000616 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000617
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000618 // ".dcb"
619 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
620 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
Petr Hosek85b2f672016-09-23 21:53:36 +0000621 // ".ds"
622 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000623
Eli Bendersky17233942013-01-15 22:59:42 +0000624 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000625 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000626
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000627 /// Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000628 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000629 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000630
Jim Grosbach4b905842013-09-20 23:08:21 +0000631 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000632
Jim Grosbach4b905842013-09-20 23:08:21 +0000633 bool parseDirectiveAbort(); // ".abort"
634 bool parseDirectiveInclude(); // ".include"
635 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000636
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000637 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
638 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000639 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000640 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000641 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000642 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000643 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
644 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000645 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000646 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
647 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
648 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
649 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000650 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000651
Jim Grosbach4b905842013-09-20 23:08:21 +0000652 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000653 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000654
Rafael Espindola34b9c512012-06-03 23:57:14 +0000655 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000656 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
657 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000658 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000659 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000660 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
661 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
662 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000663
Chad Rosierc7f552c2013-02-12 21:33:51 +0000664 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000665 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000666 size_t Len);
667
668 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000669 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000670
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000671 // "end"
672 bool parseDirectiveEnd(SMLoc DirectiveLoc);
673
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000674 // ".err" or ".error"
675 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000676
Nico Weber404012b2014-07-24 16:26:06 +0000677 // ".warning"
678 bool parseDirectiveWarning(SMLoc DirectiveLoc);
679
Coby Tayree01e53202017-10-02 14:36:31 +0000680 // .print <double-quotes-string>
681 bool parseDirectivePrint(SMLoc DirectiveLoc);
682
Peter Collingbourne3e227332018-07-17 22:17:18 +0000683 // Directives to support address-significance tables.
684 bool parseDirectiveAddrsig();
685 bool parseDirectiveAddrsigSym();
686
Eli Bendersky17233942013-01-15 22:59:42 +0000687 void initializeDirectiveKindMap();
Nilanjana Basuda60fc82019-08-05 14:16:58 +0000688 void initializeCVDefRangeTypeMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000689};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000690
691} // end anonymous namespace
Daniel Dunbar86033402010-07-12 17:54:38 +0000692
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000693namespace llvm {
694
695extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000696extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000697extern MCAsmParserExtension *createCOFFAsmParser();
Wouter van Oortmerssencc75e772018-11-12 20:15:01 +0000698extern MCAsmParserExtension *createWasmAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000699
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000700} // end namespace llvm
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000701
Chris Lattnerc35681b2010-01-19 19:46:13 +0000702enum { DEFAULT_ADDRSPACE = 0 };
703
David Blaikie9f380a32015-03-16 18:06:57 +0000704AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000705 const MCAsmInfo &MAI, unsigned CB = 0)
David Blaikie9f380a32015-03-16 18:06:57 +0000706 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000707 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
Nirav Dave2364748a2016-09-16 18:30:20 +0000708 HadError = false;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000709 // Save the old handler.
710 SavedDiagHandler = SrcMgr.getDiagHandler();
711 SavedDiagContext = SrcMgr.getDiagContext();
712 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000713 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000714 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000715
Daniel Dunbarc5011082010-07-12 18:12:02 +0000716 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000717 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
718 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000719 PlatformParser.reset(createCOFFAsmParser());
720 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000721 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000722 PlatformParser.reset(createDarwinAsmParser());
723 IsDarwin = true;
724 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000725 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000726 PlatformParser.reset(createELFAsmParser());
727 break;
Dan Gohman18eafb62017-02-22 01:23:18 +0000728 case MCObjectFileInfo::IsWasm:
Wouter van Oortmerssencc75e772018-11-12 20:15:01 +0000729 PlatformParser.reset(createWasmAsmParser());
Dan Gohman18eafb62017-02-22 01:23:18 +0000730 break;
Jason Liua03ae732019-03-12 22:01:10 +0000731 case MCObjectFileInfo::IsXCOFF:
Hubert Tongfc34a532019-08-06 15:05:20 +0000732 report_fatal_error(
733 "Need to implement createXCOFFAsmParser for XCOFF format.");
Jason Liua03ae732019-03-12 22:01:10 +0000734 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000735 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000736
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000737 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000738 initializeDirectiveKindMap();
Nilanjana Basuda60fc82019-08-05 14:16:58 +0000739 initializeCVDefRangeTypeMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000740
741 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000742}
743
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000744AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000745 assert((HadError || ActiveMacros.empty()) &&
746 "Unexpected active macro instantiation!");
Sanne Wouda29338752017-02-08 14:48:05 +0000747
748 // Restore the saved diagnostics handler and context for use during
749 // finalization.
750 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000751}
752
Jim Grosbach4b905842013-09-20 23:08:21 +0000753void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000754 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000755 for (std::vector<MacroInstantiation *>::const_reverse_iterator
756 it = ActiveMacros.rbegin(),
757 ie = ActiveMacros.rend();
758 it != ie; ++it)
759 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000760 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000761}
762
Nirav Dave2364748a2016-09-16 18:30:20 +0000763void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
764 printPendingErrors();
765 printMessage(L, SourceMgr::DK_Note, Msg, Range);
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000766 printMacroInstantiations();
767}
768
Nirav Dave2364748a2016-09-16 18:30:20 +0000769bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000770 if(getTargetParser().getTargetOptions().MCNoWarn)
771 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000772 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Nirav Dave2364748a2016-09-16 18:30:20 +0000773 return Error(L, Msg, Range);
774 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000775 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000776 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000777}
778
Nirav Dave2364748a2016-09-16 18:30:20 +0000779bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000780 HadError = true;
Nirav Dave2364748a2016-09-16 18:30:20 +0000781 printMessage(L, SourceMgr::DK_Error, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000782 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000783 return true;
784}
785
Jim Grosbach4b905842013-09-20 23:08:21 +0000786bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000787 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000788 unsigned NewBuf =
789 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
790 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000791 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000792
Sean Callanan7a77eae2010-01-21 00:19:58 +0000793 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000794 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000795 return false;
796}
Daniel Dunbar43235712010-07-18 18:54:11 +0000797
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000798/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000799/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000800/// returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000801bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
802 const MCExpr *Count, SMLoc Loc) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000803 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000804 unsigned NewBuf =
805 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
806 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000807 return true;
808
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000809 // Pick up the bytes from the file and emit them.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000810 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
811 Bytes = Bytes.drop_front(Skip);
812 if (Count) {
813 int64_t Res;
Nirav Dave6c0665e2018-04-30 19:22:40 +0000814 if (!Count->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
Petr Hosek2f4ac442016-09-23 00:41:06 +0000815 return Error(Loc, "expected absolute expression");
816 if (Res < 0)
817 return Warning(Loc, "negative count has no effect");
818 Bytes = Bytes.take_front(Res);
819 }
820 getStreamer().EmitBytes(Bytes);
Kevin Enderby109f25c2011-12-14 21:47:48 +0000821 return false;
822}
823
Alp Tokera55b95b2014-07-06 10:33:31 +0000824void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
825 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000826 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
827 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000828}
829
Sean Callanan7a77eae2010-01-21 00:19:58 +0000830const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000831 if (Lexer.getTok().is(AsmToken::Error))
832 Error(Lexer.getErrLoc(), Lexer.getErr());
833
Nirav Dave53a72f42016-07-11 12:42:14 +0000834 // if it's a end of statement with a comment in it
835 if (getTok().is(AsmToken::EndOfStatement)) {
836 // if this is a line comment output it.
Nirav Dave670109d2017-06-09 14:04:03 +0000837 if (!getTok().getString().empty() && getTok().getString().front() != '\n' &&
Nirav Dave53a72f42016-07-11 12:42:14 +0000838 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
839 Out.addExplicitComment(Twine(getTok().getString()));
840 }
841
Sean Callanan7a77eae2010-01-21 00:19:58 +0000842 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000843
844 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000845 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000846 if (MAI.preserveAsmComments())
847 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000848 tok = &Lexer.Lex();
849 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000850
Sean Callanan7a77eae2010-01-21 00:19:58 +0000851 if (tok->is(AsmToken::Eof)) {
852 // If this is the end of an included file, pop the parent file off the
853 // include stack.
854 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
855 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000856 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000857 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000858 }
859 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000860
Sean Callanan7a77eae2010-01-21 00:19:58 +0000861 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000862}
863
Paul Robinson938d9a02018-03-22 15:48:01 +0000864bool AsmParser::enabledGenDwarfForAssembly() {
865 // Check whether the user specified -g.
866 if (!getContext().getGenDwarfForAssembly())
867 return false;
868 // If we haven't encountered any .file directives (which would imply that
869 // the assembler source was produced with debug info already) then emit one
870 // describing the assembler source file itself.
Paul Robinson1ca25762019-03-01 20:58:04 +0000871 if (getContext().getGenDwarfFileNumber() == 0) {
Paul Robinson9c563262019-05-21 11:59:03 +0000872 // Use the first #line directive for this, if any. It's preprocessed, so
873 // there is no checksum, and of course no source directive.
874 if (!FirstCppHashFilename.empty())
875 getContext().setMCLineTableRootFile(/*CUID=*/0,
876 getContext().getCompilationDir(),
877 FirstCppHashFilename,
878 /*Cksum=*/None, /*Source=*/None);
Paul Robinson1ca25762019-03-01 20:58:04 +0000879 const MCDwarfFile &RootFile =
880 getContext().getMCDwarfLineTable(/*CUID=*/0).getRootFile();
Paul Robinson938d9a02018-03-22 15:48:01 +0000881 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
Paul Robinson1ca25762019-03-01 20:58:04 +0000882 /*CUID=*/0, getContext().getCompilationDir(), RootFile.Name,
883 RootFile.Checksum, RootFile.Source));
884 }
Paul Robinson938d9a02018-03-22 15:48:01 +0000885 return true;
886}
887
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000888bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000889 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000890 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000891 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000892
Chris Lattner36e02122009-06-21 20:54:55 +0000893 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000894 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000895
896 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000897 AsmCond StartingCondState = TheCondState;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000898 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000899
Kevin Enderby6469fc22011-11-01 22:27:22 +0000900 // If we are generating dwarf for assembly source files save the initial text
Paul Robinson938d9a02018-03-22 15:48:01 +0000901 // section. (Don't use enabledGenDwarfForAssembly() here, as we aren't
902 // emitting any actual debug info yet and haven't had a chance to parse any
903 // embedded .file directives.)
Kevin Enderby6469fc22011-11-01 22:27:22 +0000904 if (getContext().getGenDwarfForAssembly()) {
Eric Christopher445c9522016-10-14 05:47:37 +0000905 MCSection *Sec = getStreamer().getCurrentSectionOnly();
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000906 if (!Sec->getBeginSymbol()) {
907 MCSymbol *SectionStartSym = getContext().createTempSymbol();
908 getStreamer().EmitLabel(SectionStartSym);
909 Sec->setBeginSymbol(SectionStartSym);
910 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000911 bool InsertResult = getContext().addGenDwarfSection(Sec);
912 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000913 (void)InsertResult;
Kevin Enderby6469fc22011-11-01 22:27:22 +0000914 }
915
Chris Lattner73f36112009-07-02 21:53:43 +0000916 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000917 while (Lexer.isNot(AsmToken::Eof)) {
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000918 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000919 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000920 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000921
Nirav Dave2364748a2016-09-16 18:30:20 +0000922 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
923 // for printing ErrMsg via Lex() only if no (presumably better) parser error
924 // exists.
925 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
Nirav Dave1180e6892016-06-02 17:15:05 +0000926 Lex();
927 }
928
Nirav Dave2364748a2016-09-16 18:30:20 +0000929 // parseStatement returned true so may need to emit an error.
930 printPendingErrors();
931
932 // Skipping to the next line if needed.
933 if (!getLexer().isAtStartOfStatement())
934 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000935 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000936
Wouter van Oortmerssen29c6ce52018-12-26 22:46:18 +0000937 getTargetParser().onEndOfFile();
938 printPendingErrors();
939
Nirav Dave2364748a2016-09-16 18:30:20 +0000940 // All errors should have been emitted.
941 assert(!hasPendingError() && "unexpected error from parseStatement");
942
Oliver Stannard21718282016-07-26 14:19:47 +0000943 getTargetParser().flushPendingInstructions(getStreamer());
944
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000945 if (TheCondState.TheCond != StartingCondState.TheCond ||
946 TheCondState.Ignore != StartingCondState.Ignore)
Nirav Dave2364748a2016-09-16 18:30:20 +0000947 printError(getTok().getLoc(), "unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000948 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000949 const auto &LineTables = getContext().getMCDwarfLineTables();
950 if (!LineTables.empty()) {
951 unsigned Index = 0;
952 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
953 if (File.Name.empty() && Index != 0)
Nirav Dave2364748a2016-09-16 18:30:20 +0000954 printError(getTok().getLoc(), "unassigned file number: " +
955 Twine(Index) +
956 " for .file directives");
David Blaikie8bf66c42014-04-01 07:35:52 +0000957 ++Index;
958 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000959 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000960
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000961 // Check to see that all assembler local symbols were actually defined.
962 // Targets that don't do subsections via symbols may not want this, though,
963 // so conservatively exclude them. Only do this if we're finalizing, though,
964 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000965 if (!NoFinalize) {
966 if (MAI.hasSubsectionsViaSymbols()) {
967 for (const auto &TableEntry : getContext().getSymbols()) {
968 MCSymbol *Sym = TableEntry.getValue();
969 // Variable symbols may not be marked as defined, so check those
970 // explicitly. If we know it's a variable, we have a definition for
971 // the purposes of this check.
972 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
973 // FIXME: We would really like to refer back to where the symbol was
974 // first referenced for a source location. We need to add something
975 // to track that. Currently, we just point to the end of the file.
Nirav Dave2364748a2016-09-16 18:30:20 +0000976 printError(getTok().getLoc(), "assembler local symbol '" +
977 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000978 }
979 }
980
981 // Temporary symbols like the ones for directional jumps don't go in the
982 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000983 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
984 if (std::get<2>(LocSym)->isUndefined()) {
985 // Reset the state of any "# line file" directives we've seen to the
986 // context as it was at the diagnostic site.
987 CppHashInfo = std::get<1>(LocSym);
Nirav Dave2364748a2016-09-16 18:30:20 +0000988 printError(std::get<0>(LocSym), "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000989 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000990 }
991 }
992
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000993 // Finalize the output stream if there are no errors and if the client wants
994 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000995 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000996 Out.Finish();
997
Oliver Stannard07b43d32015-11-17 09:58:07 +0000998 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000999}
1000
Nirav Davef43cc9f2016-10-10 15:24:54 +00001001bool AsmParser::checkForValidSection() {
Eric Christopher445c9522016-10-14 05:47:37 +00001002 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
Rafael Espindola7b61ddf2014-10-15 16:12:52 +00001003 Out.InitSections(false);
Nirav Davef43cc9f2016-10-10 15:24:54 +00001004 return Error(getTok().getLoc(),
1005 "expected section directive before assembly directive");
Daniel Dunbare5444a82010-09-09 22:42:59 +00001006 }
Nirav Davef43cc9f2016-10-10 15:24:54 +00001007 return false;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001008}
1009
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001010/// Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001011void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +00001012 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +00001013 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001014
Chris Lattnere5074c42009-06-22 01:29:09 +00001015 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001016 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +00001017 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +00001018}
1019
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001020StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +00001021 const char *Start = getTok().getLoc().getPointer();
1022
Jim Grosbach4b905842013-09-20 23:08:21 +00001023 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +00001024 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +00001025
1026 const char *End = getTok().getLoc().getPointer();
1027 return StringRef(Start, End - Start);
1028}
Chris Lattner78db3622009-06-22 05:51:26 +00001029
Jim Grosbach4b905842013-09-20 23:08:21 +00001030StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00001031 const char *Start = getTok().getLoc().getPointer();
1032
1033 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +00001034 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +00001035 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00001036
1037 const char *End = getTok().getLoc().getPointer();
1038 return StringRef(Start, End - Start);
1039}
1040
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001041/// Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001042/// NOTE: This assumes the leading '(' has already been consumed.
1043///
1044/// parenexpr ::= expr)
1045///
Jim Grosbach4b905842013-09-20 23:08:21 +00001046bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1047 if (parseExpression(Res))
1048 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001049 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +00001050 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001051 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001052 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +00001053 return false;
1054}
Chris Lattner78db3622009-06-22 05:51:26 +00001055
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001056/// Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001057/// NOTE: This assumes the leading '[' has already been consumed.
1058///
1059/// bracketexpr ::= expr]
1060///
Jim Grosbach4b905842013-09-20 23:08:21 +00001061bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1062 if (parseExpression(Res))
1063 return true;
Nirav Davea645433c2016-07-18 15:24:03 +00001064 EndLoc = getTok().getEndLoc();
1065 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
1066 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001067 return false;
1068}
1069
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001070/// Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001071/// primaryexpr ::= (parenexpr
1072/// primaryexpr ::= symbol
1073/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +00001074/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +00001075/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +00001076bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001077 SMLoc FirstTokenLoc = getLexer().getLoc();
1078 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
1079 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +00001080 default:
1081 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +00001082 // If we have an error assume that we've already handled it.
1083 case AsmToken::Error:
1084 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001085 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001086 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001087 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001088 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001089 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001090 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +00001091 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +00001092 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00001093 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +00001094 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +00001095 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001096 if (parseIdentifier(Identifier)) {
Nirav Daved0463322016-10-12 13:58:07 +00001097 // We may have failed but $ may be a valid token.
1098 if (getTok().is(AsmToken::Dollar)) {
David Majnemer0c58bc62013-09-25 10:47:21 +00001099 if (Lexer.getMAI().getDollarIsPC()) {
Nirav Daved0463322016-10-12 13:58:07 +00001100 Lex();
David Majnemer0c58bc62013-09-25 10:47:21 +00001101 // This is a '$' reference, which references the current PC. Emit a
1102 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001103 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +00001104 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001105 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +00001106 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +00001107 EndLoc = FirstTokenLoc;
1108 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +00001109 }
1110 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +00001111 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001112 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001113 // Parse symbol variant
1114 std::pair<StringRef, StringRef> Split;
1115 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +00001116 if (FirstTokenKind == AsmToken::String) {
1117 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +00001118 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +00001119 SMLoc AtLoc = getLexer().getLoc();
1120 StringRef VName;
1121 if (parseIdentifier(VName))
1122 return Error(AtLoc, "expected symbol variant after '@'");
1123
1124 Split = std::make_pair(Identifier, VName);
1125 }
1126 } else {
1127 Split = Identifier.split('@');
1128 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001129 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +00001130 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +00001131 StringRef VName;
1132 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +00001133 // eat ')'.
1134 if (parseToken(AsmToken::RParen,
1135 "unexpected token in variant, expected ')'"))
1136 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +00001137 Split = std::make_pair(Identifier, VName);
1138 }
Daniel Dunbar24764322010-08-24 19:13:42 +00001139
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001140 EndLoc = SMLoc::getFromPointer(Identifier.end());
1141
Daniel Dunbard20cda02009-10-16 01:34:54 +00001142 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +00001143 StringRef SymbolName = Identifier;
Weiming Zhaocf26d562016-12-01 18:00:36 +00001144 if (SymbolName.empty())
Francis Visoiu Mistrih627d1462018-10-08 10:28:11 +00001145 return Error(getLexer().getLoc(), "expected a symbol reference");
Weiming Zhaocf26d562016-12-01 18:00:36 +00001146
Hans Wennborgce69d772013-10-18 20:46:28 +00001147 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +00001148
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001149 // Lookup the symbol variant if used.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001150 if (!Split.second.empty()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001151 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +00001152 if (Variant != MCSymbolRefExpr::VK_Invalid) {
1153 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +00001154 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +00001155 Variant = MCSymbolRefExpr::VK_None;
1156 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +00001157 return Error(SMLoc::getFromPointer(Split.second.begin()),
1158 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001159 }
1160 }
Daniel Dunbar55992562010-03-15 23:51:06 +00001161
Bill Wendling1b104382019-08-09 20:16:31 +00001162 MCSymbol *Sym = getContext().getInlineAsmLabel(SymbolName);
1163 if (!Sym)
1164 Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +00001165
Daniel Dunbard20cda02009-10-16 01:34:54 +00001166 // If this is an absolute variable reference, substitute it now to preserve
1167 // semantics in the face of reassignment.
Nirav Dave05b58912018-06-05 15:13:39 +00001168 if (Sym->isVariable()) {
1169 auto V = Sym->getVariableValue(/*SetUsed*/ false);
Nirav Daveb1f9e4d2018-09-17 20:34:26 +00001170 bool DoInline = isa<MCConstantExpr>(V) && !Variant;
Nirav Dave05b58912018-06-05 15:13:39 +00001171 if (auto TV = dyn_cast<MCTargetExpr>(V))
1172 DoInline = TV->inlineAssignedExpr();
1173 if (DoInline) {
1174 if (Variant)
1175 return Error(EndLoc, "unexpected modifier on variable reference");
1176 Res = Sym->getVariableValue(/*SetUsed*/ false);
1177 return false;
1178 }
Daniel Dunbard20cda02009-10-16 01:34:54 +00001179 }
1180
1181 // Otherwise create a symbol ref.
Chad Rosier9245e122017-01-19 20:06:32 +00001182 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
Chris Lattner78db3622009-06-22 05:51:26 +00001183 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001184 }
David Woodhousef42a6662014-02-01 16:20:54 +00001185 case AsmToken::BigNum:
1186 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001187 case AsmToken::Integer: {
1188 SMLoc Loc = getTok().getLoc();
1189 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001190 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001191 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001192 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001193 // Look for 'b' or 'f' following an Integer as a directional label
1194 if (Lexer.getKind() == AsmToken::Identifier) {
1195 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001196 // Lookup the symbol variant if used.
1197 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1198 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1199 if (Split.first.size() != IDVal.size()) {
1200 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001201 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001202 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001203 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001204 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001205 if (IDVal == "f" || IDVal == "b") {
1206 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001207 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001208 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001209 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001210 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001211 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001212 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001213 Lex(); // Eat identifier.
1214 }
1215 }
Chris Lattner78db3622009-06-22 05:51:26 +00001216 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001217 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001218 case AsmToken::Real: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001219 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001220 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001221 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001222 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001223 Lex(); // Eat token.
1224 return false;
1225 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001226 case AsmToken::Dot: {
1227 // This is a '.' reference, which references the current PC. Emit a
1228 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001229 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001230 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001231 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001232 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001233 Lex(); // Eat identifier.
1234 return false;
1235 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001236 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001237 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001238 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001239 case AsmToken::LBrac:
1240 if (!PlatformParser->HasBracketExpressions())
1241 return TokError("brackets expression not supported on this target");
1242 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001243 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001244 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001245 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001246 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001247 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001248 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001249 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001250 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001251 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001252 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001253 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001254 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001255 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001256 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001257 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001258 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001259 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001260 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001261 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001262 // MIPS unary expression operators. The lexer won't generate these tokens if
1263 // MCAsmInfo::HasMipsExpressions is false for the target.
1264 case AsmToken::PercentCall16:
1265 case AsmToken::PercentCall_Hi:
1266 case AsmToken::PercentCall_Lo:
1267 case AsmToken::PercentDtprel_Hi:
1268 case AsmToken::PercentDtprel_Lo:
1269 case AsmToken::PercentGot:
1270 case AsmToken::PercentGot_Disp:
1271 case AsmToken::PercentGot_Hi:
1272 case AsmToken::PercentGot_Lo:
1273 case AsmToken::PercentGot_Ofst:
1274 case AsmToken::PercentGot_Page:
1275 case AsmToken::PercentGottprel:
1276 case AsmToken::PercentGp_Rel:
1277 case AsmToken::PercentHi:
1278 case AsmToken::PercentHigher:
1279 case AsmToken::PercentHighest:
1280 case AsmToken::PercentLo:
1281 case AsmToken::PercentNeg:
1282 case AsmToken::PercentPcrel_Hi:
1283 case AsmToken::PercentPcrel_Lo:
1284 case AsmToken::PercentTlsgd:
1285 case AsmToken::PercentTlsldm:
1286 case AsmToken::PercentTprel_Hi:
1287 case AsmToken::PercentTprel_Lo:
1288 Lex(); // Eat the operator.
1289 if (Lexer.isNot(AsmToken::LParen))
1290 return TokError("expected '(' after operator");
1291 Lex(); // Eat the operator.
1292 if (parseExpression(Res, EndLoc))
1293 return true;
1294 if (Lexer.isNot(AsmToken::RParen))
1295 return TokError("expected ')'");
1296 Lex(); // Eat the operator.
1297 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1298 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001299 }
1300}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001301
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001302bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001303 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001304 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001305}
1306
Daniel Dunbar55f16672010-09-17 02:47:07 +00001307const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001308AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001309 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001310 // Ask the target implementation about this expression first.
1311 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1312 if (NewE)
1313 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001314 // Recurse over the given expression, rebuilding it to apply the given variant
1315 // if there is exactly one symbol.
1316 switch (E->getKind()) {
1317 case MCExpr::Target:
1318 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001319 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001320
1321 case MCExpr::SymbolRef: {
1322 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1323
1324 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001325 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1326 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001327 return E;
1328 }
1329
Jim Grosbach13760bd2015-05-30 01:25:56 +00001330 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001331 }
1332
1333 case MCExpr::Unary: {
1334 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001335 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001336 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001337 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001338 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001339 }
1340
1341 case MCExpr::Binary: {
1342 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001343 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1344 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001345
1346 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001347 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001348
Jim Grosbach4b905842013-09-20 23:08:21 +00001349 if (!LHS)
1350 LHS = BE->getLHS();
1351 if (!RHS)
1352 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001353
Jim Grosbach13760bd2015-05-30 01:25:56 +00001354 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001355 }
1356 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001357
Craig Toppera2886c22012-02-07 05:05:23 +00001358 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001359}
1360
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001361/// This function checks if the next token is <string> type or arithmetic.
1362/// string that begin with character '<' must end with character '>'.
1363/// otherwise it is arithmetics.
1364/// If the function returns a 'true' value,
1365/// the End argument will be filled with the last location pointed to the '>'
1366/// character.
1367
Craig Topper3da977b2018-09-25 19:37:35 +00001368/// There is a gap between the AltMacro's documentation and the single quote
1369/// implementation. GCC does not fully support this feature and so we will not
1370/// support it.
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001371/// TODO: Adding single quote as a string.
Craig Topperd2aab832018-09-25 20:13:55 +00001372static bool isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc) {
Craig Topperc06ee832018-09-25 18:33:00 +00001373 assert((StrLoc.getPointer() != nullptr) &&
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001374 "Argument to the function cannot be a NULL value");
1375 const char *CharPtr = StrLoc.getPointer();
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001376 while ((*CharPtr != '>') && (*CharPtr != '\n') && (*CharPtr != '\r') &&
1377 (*CharPtr != '\0')) {
1378 if (*CharPtr == '!')
1379 CharPtr++;
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001380 CharPtr++;
1381 }
1382 if (*CharPtr == '>') {
1383 EndLoc = StrLoc.getFromPointer(CharPtr + 1);
1384 return true;
1385 }
1386 return false;
1387}
1388
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001389/// creating a string without the escape characters '!'.
Craig Topperd2aab832018-09-25 20:13:55 +00001390static std::string altMacroString(StringRef AltMacroStr) {
1391 std::string Res;
Michael Zuckermanff298792017-05-10 14:00:57 +00001392 for (size_t Pos = 0; Pos < AltMacroStr.size(); Pos++) {
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001393 if (AltMacroStr[Pos] == '!')
1394 Pos++;
1395 Res += AltMacroStr[Pos];
1396 }
Craig Topperd2aab832018-09-25 20:13:55 +00001397 return Res;
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001398}
1399
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001400/// Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001401///
Jim Grosbachbd164242011-08-20 16:24:13 +00001402/// expr ::= expr &&,|| expr -> lowest.
1403/// expr ::= expr |,^,&,! expr
1404/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1405/// expr ::= expr <<,>> expr
1406/// expr ::= expr +,- expr
1407/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001408/// expr ::= primaryexpr
1409///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001410bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001411 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001412 Res = nullptr;
Nirav Dave7fd992a2018-08-16 16:31:14 +00001413 if (getTargetParser().parsePrimaryExpr(Res, EndLoc) ||
1414 parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001415 return true;
1416
Daniel Dunbar55f16672010-09-17 02:47:07 +00001417 // As a special case, we support 'a op b @ modifier' by rewriting the
1418 // expression to include the modifier. This is inefficient, but in general we
1419 // expect users to use 'a@modifier op b'.
1420 if (Lexer.getKind() == AsmToken::At) {
1421 Lex();
1422
1423 if (Lexer.isNot(AsmToken::Identifier))
1424 return TokError("unexpected symbol modifier following '@'");
1425
1426 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001427 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001428 if (Variant == MCSymbolRefExpr::VK_Invalid)
1429 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1430
Jim Grosbach4b905842013-09-20 23:08:21 +00001431 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001432 if (!ModifiedRes) {
1433 return TokError("invalid modifier '" + getTok().getIdentifier() +
1434 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001435 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001436
Daniel Dunbar55f16672010-09-17 02:47:07 +00001437 Res = ModifiedRes;
1438 Lex();
1439 }
1440
Nirav Dave6c0665e2018-04-30 19:22:40 +00001441 // Try to constant fold it up front, if possible. Do not exploit
1442 // assembler here.
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001443 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001444 if (Res->evaluateAsAbsolute(Value))
1445 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001446
1447 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001448}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001449
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001450bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001451 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001452 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001453}
1454
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001455bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1456 SMLoc &EndLoc) {
1457 if (parseParenExpr(Res, EndLoc))
1458 return true;
1459
1460 for (; ParenDepth > 0; --ParenDepth) {
1461 if (parseBinOpRHS(1, Res, EndLoc))
1462 return true;
1463
1464 // We don't Lex() the last RParen.
1465 // This is the same behavior as parseParenExpression().
1466 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001467 EndLoc = getTok().getEndLoc();
1468 if (parseToken(AsmToken::RParen,
1469 "expected ')' in parentheses expression"))
1470 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001471 }
1472 }
1473 return false;
1474}
1475
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001476bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001477 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001478
Daniel Dunbar75630b32009-06-30 02:10:03 +00001479 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001480 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001481 return true;
1482
Nirav Dave6c0665e2018-04-30 19:22:40 +00001483 if (!Expr->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001484 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001485
1486 return false;
1487}
1488
David Majnemer0993e0b2015-10-26 03:15:34 +00001489static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1490 MCBinaryExpr::Opcode &Kind,
1491 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001492 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001493 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001494 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001495
Jim Grosbach4b905842013-09-20 23:08:21 +00001496 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001497 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001498 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001499 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001500 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001501 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001502 return 1;
1503
Jim Grosbach4b905842013-09-20 23:08:21 +00001504 // Low Precedence: |, &, ^
1505 //
1506 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001507 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001508 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001509 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001510 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001511 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001512 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001513 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001514 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001515 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001516
Jim Grosbach4b905842013-09-20 23:08:21 +00001517 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001518 case AsmToken::EqualEqual:
1519 Kind = MCBinaryExpr::EQ;
1520 return 3;
1521 case AsmToken::ExclaimEqual:
1522 case AsmToken::LessGreater:
1523 Kind = MCBinaryExpr::NE;
1524 return 3;
1525 case AsmToken::Less:
1526 Kind = MCBinaryExpr::LT;
1527 return 3;
1528 case AsmToken::LessEqual:
1529 Kind = MCBinaryExpr::LTE;
1530 return 3;
1531 case AsmToken::Greater:
1532 Kind = MCBinaryExpr::GT;
1533 return 3;
1534 case AsmToken::GreaterEqual:
1535 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001536 return 3;
1537
Jim Grosbach4b905842013-09-20 23:08:21 +00001538 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001539 case AsmToken::LessLess:
1540 Kind = MCBinaryExpr::Shl;
1541 return 4;
1542 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001543 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001544 return 4;
1545
Jim Grosbach4b905842013-09-20 23:08:21 +00001546 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001547 case AsmToken::Plus:
1548 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001549 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001550 case AsmToken::Minus:
1551 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001552 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001553
Jim Grosbach4b905842013-09-20 23:08:21 +00001554 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001555 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001556 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001557 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001558 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001559 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001560 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001561 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001562 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001563 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001564 }
1565}
1566
David Majnemer0993e0b2015-10-26 03:15:34 +00001567static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1568 MCBinaryExpr::Opcode &Kind,
1569 bool ShouldUseLogicalShr) {
1570 switch (K) {
1571 default:
1572 return 0; // not a binop.
1573
1574 // Lowest Precedence: &&, ||
1575 case AsmToken::AmpAmp:
1576 Kind = MCBinaryExpr::LAnd;
1577 return 2;
1578 case AsmToken::PipePipe:
1579 Kind = MCBinaryExpr::LOr;
1580 return 1;
1581
1582 // Low Precedence: ==, !=, <>, <, <=, >, >=
1583 case AsmToken::EqualEqual:
1584 Kind = MCBinaryExpr::EQ;
1585 return 3;
1586 case AsmToken::ExclaimEqual:
1587 case AsmToken::LessGreater:
1588 Kind = MCBinaryExpr::NE;
1589 return 3;
1590 case AsmToken::Less:
1591 Kind = MCBinaryExpr::LT;
1592 return 3;
1593 case AsmToken::LessEqual:
1594 Kind = MCBinaryExpr::LTE;
1595 return 3;
1596 case AsmToken::Greater:
1597 Kind = MCBinaryExpr::GT;
1598 return 3;
1599 case AsmToken::GreaterEqual:
1600 Kind = MCBinaryExpr::GTE;
1601 return 3;
1602
1603 // Low Intermediate Precedence: +, -
1604 case AsmToken::Plus:
1605 Kind = MCBinaryExpr::Add;
1606 return 4;
1607 case AsmToken::Minus:
1608 Kind = MCBinaryExpr::Sub;
1609 return 4;
1610
1611 // High Intermediate Precedence: |, &, ^
1612 //
1613 // FIXME: gas seems to support '!' as an infix operator?
1614 case AsmToken::Pipe:
1615 Kind = MCBinaryExpr::Or;
1616 return 5;
1617 case AsmToken::Caret:
1618 Kind = MCBinaryExpr::Xor;
1619 return 5;
1620 case AsmToken::Amp:
1621 Kind = MCBinaryExpr::And;
1622 return 5;
1623
1624 // Highest Precedence: *, /, %, <<, >>
1625 case AsmToken::Star:
1626 Kind = MCBinaryExpr::Mul;
1627 return 6;
1628 case AsmToken::Slash:
1629 Kind = MCBinaryExpr::Div;
1630 return 6;
1631 case AsmToken::Percent:
1632 Kind = MCBinaryExpr::Mod;
1633 return 6;
1634 case AsmToken::LessLess:
1635 Kind = MCBinaryExpr::Shl;
1636 return 6;
1637 case AsmToken::GreaterGreater:
1638 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1639 return 6;
1640 }
1641}
1642
1643unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1644 MCBinaryExpr::Opcode &Kind) {
1645 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1646 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1647 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1648}
1649
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001650/// Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001651/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001652bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001653 SMLoc &EndLoc) {
Chad Rosier9245e122017-01-19 20:06:32 +00001654 SMLoc StartLoc = Lexer.getLoc();
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001655 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001656 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001657 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001658
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001659 // If the next token is lower precedence than we are allowed to eat, return
1660 // successfully with what we ate already.
1661 if (TokPrec < Precedence)
1662 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001663
Sean Callanan686ed8d2010-01-19 20:22:31 +00001664 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001665
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001666 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001667 const MCExpr *RHS;
Nirav Dave7fd992a2018-08-16 16:31:14 +00001668 if (getTargetParser().parsePrimaryExpr(RHS, EndLoc))
Jim Grosbach4b905842013-09-20 23:08:21 +00001669 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001670
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001671 // If BinOp binds less tightly with RHS than the operator after RHS, let
1672 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001673 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001674 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001675 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1676 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001677
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001678 // Merge LHS and RHS according to operator.
Chad Rosier9245e122017-01-19 20:06:32 +00001679 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001680 }
1681}
1682
Chris Lattner36e02122009-06-21 20:54:55 +00001683/// ParseStatement:
1684/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001685/// ::= Label* Directive ...Operands... EndOfStatement
1686/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001687bool AsmParser::parseStatement(ParseStatementInfo &Info,
1688 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001689 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001690 // Eat initial spaces and comments
1691 while (Lexer.is(AsmToken::Space))
1692 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001693 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001694 // if this is a line comment we can drop it safely
Nirav Dave670109d2017-06-09 14:04:03 +00001695 if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
Nirav Davefd910412016-06-17 16:06:17 +00001696 getTok().getString().front() == '\n')
1697 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001698 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001699 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001700 }
Nirav Davefd910412016-06-17 16:06:17 +00001701 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001702 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001703 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001704 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001705 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001706 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001707 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001708 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001709 if (Lexer.is(AsmToken::Integer)) {
1710 LocalLabelVal = getTok().getIntVal();
1711 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001712 if (!TheCondState.Ignore) {
1713 Lex(); // always eat a token
1714 return Error(IDLoc, "unexpected token at start of statement");
1715 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001716 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001717 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001718 IDVal = getTok().getString();
1719 Lex(); // Consume the integer token to be used as an identifier token.
1720 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001721 if (!TheCondState.Ignore) {
1722 Lex(); // always eat a token
1723 return Error(IDLoc, "unexpected token at start of statement");
1724 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001725 }
1726 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001727 } else if (Lexer.is(AsmToken::Dot)) {
1728 // Treat '.' as a valid identifier in this context.
1729 Lex();
1730 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001731 } else if (Lexer.is(AsmToken::LCurly)) {
1732 // Treat '{' as a valid identifier in this context.
1733 Lex();
1734 IDVal = "{";
1735
1736 } else if (Lexer.is(AsmToken::RCurly)) {
1737 // Treat '}' as a valid identifier in this context.
1738 Lex();
1739 IDVal = "}";
Yonghong Song06ff6552017-09-12 17:55:23 +00001740 } else if (Lexer.is(AsmToken::Star) &&
1741 getTargetParser().starIsStartOfStatement()) {
1742 // Accept '*' as a valid start of statement.
1743 Lex();
1744 IDVal = "*";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001745 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001746 if (!TheCondState.Ignore) {
1747 Lex(); // always eat a token
1748 return Error(IDLoc, "unexpected token at start of statement");
1749 }
Chris Lattner926885c2010-04-17 18:14:27 +00001750 IDVal = "";
1751 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001752
Chris Lattner926885c2010-04-17 18:14:27 +00001753 // Handle conditional assembly here before checking for skipping. We
1754 // have to do this so that .endif isn't skipped in a ".if 0" block for
1755 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001756 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001757 DirectiveKindMap.find(IDVal);
1758 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
Nilanjana Basuda60fc82019-08-05 14:16:58 +00001759
Jim Grosbach4b905842013-09-20 23:08:21 +00001760 ? DK_NO_DIRECTIVE
1761 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001762 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001763 default:
1764 break;
1765 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001766 case DK_IFEQ:
1767 case DK_IFGE:
1768 case DK_IFGT:
1769 case DK_IFLE:
1770 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001771 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001772 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001773 case DK_IFB:
1774 return parseDirectiveIfb(IDLoc, true);
1775 case DK_IFNB:
1776 return parseDirectiveIfb(IDLoc, false);
1777 case DK_IFC:
1778 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001779 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001780 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001781 case DK_IFNC:
1782 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001783 case DK_IFNES:
1784 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001785 case DK_IFDEF:
1786 return parseDirectiveIfdef(IDLoc, true);
1787 case DK_IFNDEF:
1788 case DK_IFNOTDEF:
1789 return parseDirectiveIfdef(IDLoc, false);
1790 case DK_ELSEIF:
1791 return parseDirectiveElseIf(IDLoc);
1792 case DK_ELSE:
1793 return parseDirectiveElse(IDLoc);
1794 case DK_ENDIF:
1795 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001796 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001797
Eli Bendersky88024712013-01-16 19:32:36 +00001798 // Ignore the statement if in the middle of inactive conditional
1799 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001800 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001801 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001802 return false;
1803 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001804
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001805 // FIXME: Recurse on local labels?
1806
1807 // See what kind of statement we have.
1808 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001809 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001810 if (!getTargetParser().isLabel(ID))
1811 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001812 if (checkForValidSection())
1813 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001814
Chris Lattner36e02122009-06-21 20:54:55 +00001815 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001816 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001817
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001818 // Diagnose attempt to use '.' as a label.
1819 if (IDVal == ".")
1820 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1821
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001822 // Diagnose attempt to use a variable as a label.
1823 //
1824 // FIXME: Diagnostics. Note the location of the definition as a label.
1825 // FIXME: This doesn't diagnose assignment to a symbol which has been
1826 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001827 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001828 if (LocalLabelVal == -1) {
1829 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001830 StringRef RewrittenLabel =
1831 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001832 assert(!RewrittenLabel.empty() &&
Nico Weber67e715f2015-06-19 23:43:47 +00001833 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001834 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1835 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001836 IDVal = RewrittenLabel;
1837 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001838 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001839 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001840 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
Nirav Dave9263ae32016-08-02 19:17:54 +00001841 // End of Labels should be treated as end of line for lexing
1842 // purposes but that information is not available to the Lexer who
1843 // does not understand Labels. This may cause us to see a Hash
1844 // here instead of a preprocessor line comment.
1845 if (getTok().is(AsmToken::Hash)) {
1846 StringRef CommentStr = parseStringToEndOfStatement();
1847 Lexer.Lex();
1848 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1849 }
1850
Nirav Dave8ea792d2016-07-13 14:03:12 +00001851 // Consume any end of statement token, if present, to avoid spurious
1852 // AddBlankLine calls().
1853 if (getTok().is(AsmToken::EndOfStatement)) {
1854 Lex();
1855 }
1856
Maya Madhavanec1efe42018-09-20 05:11:42 +00001857 getTargetParser().doBeforeLabelEmit(Sym);
1858
Daniel Dunbare73b2672009-08-26 22:13:22 +00001859 // Emit the label.
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00001860 if (!getTargetParser().isParsingInlineAsm())
Rafael Espindolabe991572017-02-10 15:13:12 +00001861 Out.EmitLabel(Sym, IDLoc);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001862
Kevin Enderbye7739d42011-12-09 18:09:40 +00001863 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001864 // info to make a dwarf label entry for this label if needed.
Paul Robinson938d9a02018-03-22 15:48:01 +00001865 if (enabledGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001866 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1867 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001868
Tim Northover1744d0a2013-10-25 12:49:50 +00001869 getTargetParser().onLabelParsed(Sym);
1870
Eli Friedman0f4871d2012-10-22 23:58:19 +00001871 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001872 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001873
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001874 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001875 if (!getTargetParser().equalIsAsmAssignment())
1876 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001877 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001878 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001879
Nirav Dave7fd992a2018-08-16 16:31:14 +00001880 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001881
1882 default: // Normal instruction or directive.
1883 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001884 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001885
1886 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001887 if (areMacrosEnabled())
Rafael Espindola22c38a02018-02-14 16:34:27 +00001888 if (const MCAsmMacro *M = getContext().lookupMacro(IDVal)) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001889 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001890 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001891
Michael J. Spencer530ce852010-10-09 11:00:50 +00001892 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001893
Eli Bendersky17233942013-01-15 22:59:42 +00001894 // Directives start with "."
Ana Pazos353f67a2018-08-25 01:34:32 +00001895 if (IDVal.startswith(".") && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001896 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001897 //
Eli Bendersky17233942013-01-15 22:59:42 +00001898 // 1. The target-specific assembly parser. Some directives are target
1899 // specific or may potentially behave differently on certain targets.
1900 // 2. Asm parser extensions. For example, platform-specific parsers
1901 // (like the ELF parser) register themselves as extensions.
1902 // 3. The generic directive parser implemented by this class. These are
1903 // all the directives that behave in a target and platform independent
1904 // manner, or at least have a default behavior that's shared between
1905 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001906
Oliver Stannard21718282016-07-26 14:19:47 +00001907 getTargetParser().flushPendingInstructions(getStreamer());
1908
Nirav Dave2364748a2016-09-16 18:30:20 +00001909 SMLoc StartTokLoc = getTok().getLoc();
1910 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1911
1912 if (hasPendingError())
1913 return true;
1914 // Currently the return value should be true if we are
1915 // uninterested but as this is at odds with the standard parsing
1916 // convention (return true = error) we have instances of a parsed
1917 // directive that fails returning true as an error. Catch these
1918 // cases as best as possible errors here.
1919 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1920 return true;
1921 // Return if we did some parsing or believe we succeeded.
1922 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001923 return false;
1924
Alp Tokercb402912014-01-24 17:20:08 +00001925 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001926 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001927 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1928 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001929 if (Handler.first)
1930 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1931
1932 // Finally, if no one else is interested in this directive, it must be
1933 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001934 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001935 default:
1936 break;
1937 case DK_SET:
1938 case DK_EQU:
1939 return parseDirectiveSet(IDVal, true);
1940 case DK_EQUIV:
1941 return parseDirectiveSet(IDVal, false);
1942 case DK_ASCII:
1943 return parseDirectiveAscii(IDVal, false);
1944 case DK_ASCIZ:
1945 case DK_STRING:
1946 return parseDirectiveAscii(IDVal, true);
1947 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001948 case DK_DC_B:
1949 return parseDirectiveValue(IDVal, 1);
1950 case DK_DC:
1951 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001952 case DK_SHORT:
1953 case DK_VALUE:
1954 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001955 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001956 case DK_LONG:
1957 case DK_INT:
1958 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001959 case DK_DC_L:
1960 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001961 case DK_QUAD:
1962 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001963 return parseDirectiveValue(IDVal, 8);
1964 case DK_DC_A:
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001965 return parseDirectiveValue(
1966 IDVal, getContext().getAsmInfo()->getCodePointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001967 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001968 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001969 case DK_SINGLE:
1970 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001971 case DK_DC_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001972 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
Jim Grosbach4b905842013-09-20 23:08:21 +00001973 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001974 case DK_DC_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001975 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
Jim Grosbach4b905842013-09-20 23:08:21 +00001976 case DK_ALIGN: {
1977 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1978 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1979 }
1980 case DK_ALIGN32: {
1981 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1982 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1983 }
1984 case DK_BALIGN:
1985 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1986 case DK_BALIGNW:
1987 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1988 case DK_BALIGNL:
1989 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1990 case DK_P2ALIGN:
1991 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1992 case DK_P2ALIGNW:
1993 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1994 case DK_P2ALIGNL:
1995 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1996 case DK_ORG:
1997 return parseDirectiveOrg();
1998 case DK_FILL:
1999 return parseDirectiveFill();
2000 case DK_ZERO:
2001 return parseDirectiveZero();
2002 case DK_EXTERN:
2003 eatToEndOfStatement(); // .extern is the default, ignore it.
2004 return false;
2005 case DK_GLOBL:
2006 case DK_GLOBAL:
2007 return parseDirectiveSymbolAttribute(MCSA_Global);
2008 case DK_LAZY_REFERENCE:
2009 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
2010 case DK_NO_DEAD_STRIP:
2011 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
2012 case DK_SYMBOL_RESOLVER:
2013 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
2014 case DK_PRIVATE_EXTERN:
2015 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
2016 case DK_REFERENCE:
2017 return parseDirectiveSymbolAttribute(MCSA_Reference);
2018 case DK_WEAK_DEFINITION:
2019 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
2020 case DK_WEAK_REFERENCE:
2021 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
2022 case DK_WEAK_DEF_CAN_BE_HIDDEN:
2023 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Vedant Kumar13ef84f2019-01-25 18:30:22 +00002024 case DK_COLD:
2025 return parseDirectiveSymbolAttribute(MCSA_Cold);
Jim Grosbach4b905842013-09-20 23:08:21 +00002026 case DK_COMM:
2027 case DK_COMMON:
2028 return parseDirectiveComm(/*IsLocal=*/false);
2029 case DK_LCOMM:
2030 return parseDirectiveComm(/*IsLocal=*/true);
2031 case DK_ABORT:
2032 return parseDirectiveAbort();
2033 case DK_INCLUDE:
2034 return parseDirectiveInclude();
2035 case DK_INCBIN:
2036 return parseDirectiveIncbin();
2037 case DK_CODE16:
2038 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00002039 return TokError(Twine(IDVal) +
2040 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00002041 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00002042 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00002043 case DK_IRP:
2044 return parseDirectiveIrp(IDLoc);
2045 case DK_IRPC:
2046 return parseDirectiveIrpc(IDLoc);
2047 case DK_ENDR:
2048 return parseDirectiveEndr(IDLoc);
2049 case DK_BUNDLE_ALIGN_MODE:
2050 return parseDirectiveBundleAlignMode();
2051 case DK_BUNDLE_LOCK:
2052 return parseDirectiveBundleLock();
2053 case DK_BUNDLE_UNLOCK:
2054 return parseDirectiveBundleUnlock();
2055 case DK_SLEB128:
2056 return parseDirectiveLEB128(true);
2057 case DK_ULEB128:
2058 return parseDirectiveLEB128(false);
2059 case DK_SPACE:
2060 case DK_SKIP:
2061 return parseDirectiveSpace(IDVal);
2062 case DK_FILE:
2063 return parseDirectiveFile(IDLoc);
2064 case DK_LINE:
2065 return parseDirectiveLine();
2066 case DK_LOC:
2067 return parseDirectiveLoc();
2068 case DK_STABS:
2069 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002070 case DK_CV_FILE:
2071 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00002072 case DK_CV_FUNC_ID:
2073 return parseDirectiveCVFuncId();
2074 case DK_CV_INLINE_SITE_ID:
2075 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002076 case DK_CV_LOC:
2077 return parseDirectiveCVLoc();
2078 case DK_CV_LINETABLE:
2079 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00002080 case DK_CV_INLINE_LINETABLE:
2081 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00002082 case DK_CV_DEF_RANGE:
2083 return parseDirectiveCVDefRange();
Reid Kleckner06d02d02018-09-07 21:30:52 +00002084 case DK_CV_STRING:
2085 return parseDirectiveCVString();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002086 case DK_CV_STRINGTABLE:
2087 return parseDirectiveCVStringTable();
2088 case DK_CV_FILECHECKSUMS:
2089 return parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00002090 case DK_CV_FILECHECKSUM_OFFSET:
2091 return parseDirectiveCVFileChecksumOffset();
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00002092 case DK_CV_FPO_DATA:
2093 return parseDirectiveCVFPOData();
Jim Grosbach4b905842013-09-20 23:08:21 +00002094 case DK_CFI_SECTIONS:
2095 return parseDirectiveCFISections();
2096 case DK_CFI_STARTPROC:
2097 return parseDirectiveCFIStartProc();
2098 case DK_CFI_ENDPROC:
2099 return parseDirectiveCFIEndProc();
2100 case DK_CFI_DEF_CFA:
2101 return parseDirectiveCFIDefCfa(IDLoc);
2102 case DK_CFI_DEF_CFA_OFFSET:
2103 return parseDirectiveCFIDefCfaOffset();
2104 case DK_CFI_ADJUST_CFA_OFFSET:
2105 return parseDirectiveCFIAdjustCfaOffset();
2106 case DK_CFI_DEF_CFA_REGISTER:
2107 return parseDirectiveCFIDefCfaRegister(IDLoc);
2108 case DK_CFI_OFFSET:
2109 return parseDirectiveCFIOffset(IDLoc);
2110 case DK_CFI_REL_OFFSET:
2111 return parseDirectiveCFIRelOffset(IDLoc);
2112 case DK_CFI_PERSONALITY:
2113 return parseDirectiveCFIPersonalityOrLsda(true);
2114 case DK_CFI_LSDA:
2115 return parseDirectiveCFIPersonalityOrLsda(false);
2116 case DK_CFI_REMEMBER_STATE:
2117 return parseDirectiveCFIRememberState();
2118 case DK_CFI_RESTORE_STATE:
2119 return parseDirectiveCFIRestoreState();
2120 case DK_CFI_SAME_VALUE:
2121 return parseDirectiveCFISameValue(IDLoc);
2122 case DK_CFI_RESTORE:
2123 return parseDirectiveCFIRestore(IDLoc);
2124 case DK_CFI_ESCAPE:
2125 return parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00002126 case DK_CFI_RETURN_COLUMN:
2127 return parseDirectiveCFIReturnColumn(IDLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +00002128 case DK_CFI_SIGNAL_FRAME:
2129 return parseDirectiveCFISignalFrame();
2130 case DK_CFI_UNDEFINED:
2131 return parseDirectiveCFIUndefined(IDLoc);
2132 case DK_CFI_REGISTER:
2133 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00002134 case DK_CFI_WINDOW_SAVE:
2135 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00002136 case DK_MACROS_ON:
2137 case DK_MACROS_OFF:
2138 return parseDirectiveMacrosOnOff(IDVal);
2139 case DK_MACRO:
2140 return parseDirectiveMacro(IDLoc);
Michael Zuckerman56704612017-05-01 13:20:12 +00002141 case DK_ALTMACRO:
2142 case DK_NOALTMACRO:
2143 return parseDirectiveAltmacro(IDVal);
Nico Weber155dccd12014-07-24 17:08:39 +00002144 case DK_EXITM:
2145 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00002146 case DK_ENDM:
2147 case DK_ENDMACRO:
2148 return parseDirectiveEndMacro(IDVal);
2149 case DK_PURGEM:
2150 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00002151 case DK_END:
2152 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00002153 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00002154 return parseDirectiveError(IDLoc, false);
2155 case DK_ERROR:
2156 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00002157 case DK_WARNING:
2158 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002159 case DK_RELOC:
2160 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002161 case DK_DCB:
2162 case DK_DCB_W:
2163 return parseDirectiveDCB(IDVal, 2);
2164 case DK_DCB_B:
2165 return parseDirectiveDCB(IDVal, 1);
2166 case DK_DCB_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002167 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002168 case DK_DCB_L:
2169 return parseDirectiveDCB(IDVal, 4);
2170 case DK_DCB_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002171 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
Petr Hosek731bb9c2016-08-23 21:34:53 +00002172 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002173 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00002174 return TokError(Twine(IDVal) +
2175 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00002176 case DK_DS:
2177 case DK_DS_W:
2178 return parseDirectiveDS(IDVal, 2);
2179 case DK_DS_B:
2180 return parseDirectiveDS(IDVal, 1);
2181 case DK_DS_D:
2182 return parseDirectiveDS(IDVal, 8);
2183 case DK_DS_L:
2184 case DK_DS_S:
2185 return parseDirectiveDS(IDVal, 4);
2186 case DK_DS_P:
2187 case DK_DS_X:
2188 return parseDirectiveDS(IDVal, 12);
Coby Tayree01e53202017-10-02 14:36:31 +00002189 case DK_PRINT:
2190 return parseDirectivePrint(IDLoc);
Peter Collingbourne3e227332018-07-17 22:17:18 +00002191 case DK_ADDRSIG:
2192 return parseDirectiveAddrsig();
2193 case DK_ADDRSIG_SYM:
2194 return parseDirectiveAddrsigSym();
Eli Friedman20b02642010-07-19 04:17:25 +00002195 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002196
Jim Grosbach758e0cc2012-05-01 18:38:27 +00002197 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00002198 }
Chris Lattner36e02122009-06-21 20:54:55 +00002199
Chad Rosierc7f552c2013-02-12 21:33:51 +00002200 // __asm _emit or __asm __emit
2201 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
2202 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002203 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00002204
2205 // __asm align
2206 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002207 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00002208
Coby Tayree3847be92017-04-04 17:57:23 +00002209 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
Michael Zuckerman02ecd432015-12-13 17:07:23 +00002210 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00002211 if (checkForValidSection())
2212 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00002213
Chris Lattner7cbfa442010-05-19 23:34:33 +00002214 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00002215 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00002216 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00002217 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
2218 Info.ParsedOperands);
2219 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00002220
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002221 // Dump the parsed representation, if requested.
2222 if (getShowParsedOperands()) {
2223 SmallString<256> Str;
2224 raw_svector_ostream OS(Str);
2225 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002226 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002227 if (i != 0)
2228 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002229 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002230 }
2231 OS << "]";
2232
Jim Grosbach4b905842013-09-20 23:08:21 +00002233 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002234 }
2235
Nirav Dave2364748a2016-09-16 18:30:20 +00002236 // Fail even if ParseInstruction erroneously returns false.
2237 if (hasPendingError() || ParseHadError)
2238 return true;
2239
Oliver Stannard8b273082014-06-19 15:52:37 +00002240 // If we are generating dwarf for the current section then generate a .loc
2241 // directive for the instruction.
Paul Robinson938d9a02018-03-22 15:48:01 +00002242 if (!ParseHadError && enabledGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002243 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002244 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002245 unsigned Line;
2246 if (ActiveMacros.empty())
2247 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2248 else
Frederic Riss16238d92015-06-25 21:57:33 +00002249 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2250 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002251
Eli Bendersky88024712013-01-16 19:32:36 +00002252 // If we previously parsed a cpp hash file line comment then make sure the
2253 // current Dwarf File is for the CppHashFilename if not then emit the
2254 // Dwarf File table for it and adjust the line number for the .loc.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00002255 if (!CppHashInfo.Filename.empty()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002256 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002257 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002258 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002259
Graydon Hoare54fe2082018-04-07 00:44:02 +00002260 unsigned CppHashLocLineNo =
2261 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Tim Northoverc0bef992016-04-13 19:46:54 +00002262 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002263 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002264
Jim Grosbach4b905842013-09-20 23:08:21 +00002265 getStreamer().EmitDwarfLocDirective(
2266 getContext().getGenDwarfFileNumber(), Line, 0,
2267 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2268 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002269 }
2270
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002271 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002272 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002273 uint64_t ErrorInfo;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00002274 if (getTargetParser().MatchAndEmitInstruction(
2275 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2276 getTargetParser().isParsingInlineAsm()))
Nirav Dave2364748a2016-09-16 18:30:20 +00002277 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002278 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002279 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002280}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002281
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002282// Parse and erase curly braces marking block start/end
Sam Cleggf009da22018-04-19 22:00:53 +00002283bool
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002284AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2285 // Identify curly brace marking block start/end
2286 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2287 return false;
2288
2289 SMLoc StartLoc = Lexer.getLoc();
2290 Lex(); // Eat the brace
2291 if (Lexer.is(AsmToken::EndOfStatement))
2292 Lex(); // Eat EndOfStatement following the brace
2293
2294 // Erase the block start/end brace from the output asm string
2295 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2296 StartLoc.getPointer());
2297 return true;
2298}
2299
Jim Grosbach4b905842013-09-20 23:08:21 +00002300/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002301/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002302bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002303 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002304 // Lexer only ever emits HashDirective if it fully formed if it's
2305 // done the checking already so this is an internal error.
2306 assert(getTok().is(AsmToken::Integer) &&
2307 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002308 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002309 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002310 assert(getTok().is(AsmToken::String) &&
2311 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002312 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002313 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002314
Kevin Enderby72553612011-09-13 23:45:18 +00002315 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002316 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002317
Paul Robinson9c563262019-05-21 11:59:03 +00002318 // Save the SMLoc, Filename and LineNumber for later use by diagnostics
2319 // and possibly DWARF file info.
Tim Northoverc0bef992016-04-13 19:46:54 +00002320 CppHashInfo.Loc = L;
2321 CppHashInfo.Filename = Filename;
2322 CppHashInfo.LineNumber = LineNumber;
2323 CppHashInfo.Buf = CurBuffer;
Paul Robinson9c563262019-05-21 11:59:03 +00002324 if (FirstCppHashFilename.empty())
2325 FirstCppHashFilename = Filename;
Kevin Enderby72553612011-09-13 23:45:18 +00002326 return false;
2327}
2328
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002329/// will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002330/// for the Filename and LineNo if any in the diagnostic.
2331void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002332 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002333 raw_ostream &OS = errs();
2334
2335 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002336 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002337 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2338 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002339 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002340
Jim Grosbach4b905842013-09-20 23:08:21 +00002341 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002342 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002343 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2344 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2345 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002346 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2347 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002348 }
2349
Eric Christophera7c32732012-12-18 00:30:54 +00002350 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002351 // manager changed or buffer changed (like in a nested include) then just
2352 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002353 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002354 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002355 if (Parser->SavedDiagHandler)
2356 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2357 else
Craig Topper353eda42014-04-24 06:44:33 +00002358 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002359 return;
2360 }
2361
Eric Christophera7c32732012-12-18 00:30:54 +00002362 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002363 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2364 // for the diagnostic.
2365 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002366
2367 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2368 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002369 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002370 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002371 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002372
Jim Grosbach4b905842013-09-20 23:08:21 +00002373 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2374 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002375 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002376
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002377 if (Parser->SavedDiagHandler)
2378 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2379 else
Craig Topper353eda42014-04-24 06:44:33 +00002380 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002381}
2382
Rafael Espindola2c064482012-08-21 18:29:30 +00002383// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2384// difference being that that function accepts '@' as part of identifiers and
2385// we can't do that. AsmLexer.cpp should probably be changed to handle
2386// '@' as a special case when needed.
2387static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002388 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2389 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002390}
2391
Rafael Espindola34b9c512012-06-03 23:57:14 +00002392bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002393 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002394 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002395 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002396 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002397 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002398 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002399 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002400
Preston Gurd05500642012-09-19 20:36:12 +00002401 // A macro without parameters is handled differently on Darwin:
2402 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002403 while (!Body.empty()) {
2404 // Scan for the next substitution.
2405 std::size_t End = Body.size(), Pos = 0;
2406 for (; Pos != End; ++Pos) {
2407 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002408 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002409 // This macro has no parameters, look for $0, $1, etc.
2410 if (Body[Pos] != '$' || Pos + 1 == End)
2411 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002412
Rafael Espindola1134ab232011-06-05 02:43:45 +00002413 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002414 if (Next == '$' || Next == 'n' ||
2415 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002416 break;
2417 } else {
2418 // This macro has parameters, look for \foo, \bar, etc.
2419 if (Body[Pos] == '\\' && Pos + 1 != End)
2420 break;
2421 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002422 }
2423
2424 // Add the prefix.
2425 OS << Body.slice(0, Pos);
2426
2427 // Check if we reached the end.
2428 if (Pos == End)
2429 break;
2430
Benjamin Kramer513e7442014-02-20 13:36:32 +00002431 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002432 switch (Body[Pos + 1]) {
2433 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002434 case '$':
2435 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002436 break;
2437
Jim Grosbach4b905842013-09-20 23:08:21 +00002438 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002439 case 'n':
2440 OS << A.size();
2441 break;
2442
Jim Grosbach4b905842013-09-20 23:08:21 +00002443 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002444 default: {
2445 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002446 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002447 if (Index >= A.size())
2448 break;
2449
2450 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002451 for (const AsmToken &Token : A[Index])
2452 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002453 break;
2454 }
2455 }
2456 Pos += 2;
2457 } else {
2458 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002459
2460 // Check for the \@ pseudo-variable.
2461 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002462 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002463 else
2464 while (isIdentifierChar(Body[I]) && I + 1 != End)
2465 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002466
Jim Grosbach4b905842013-09-20 23:08:21 +00002467 const char *Begin = Body.data() + Pos + 1;
2468 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002469 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002470
Toma Tabacu217116e2015-04-27 10:50:29 +00002471 if (Argument == "@") {
2472 OS << NumOfMacroInstantiations;
2473 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002474 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002475 for (; Index < NParameters; ++Index)
2476 if (Parameters[Index].Name == Argument)
2477 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002478
Toma Tabacu217116e2015-04-27 10:50:29 +00002479 if (Index == NParameters) {
2480 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2481 Pos += 3;
2482 else {
2483 OS << '\\' << Argument;
2484 Pos = I;
2485 }
2486 } else {
2487 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002488 for (const AsmToken &Token : A[Index])
Michael Zuckerman56704612017-05-01 13:20:12 +00002489 // For altmacro mode, you can write '%expr'.
2490 // The prefix '%' evaluates the expression 'expr'
Craig Topper3da977b2018-09-25 19:37:35 +00002491 // and uses the result as a string (e.g. replace %(1+2) with the
2492 // string "3").
Michael Zuckerman56704612017-05-01 13:20:12 +00002493 // Here, we identify the integer token which is the result of the
Craig Topper3da977b2018-09-25 19:37:35 +00002494 // absolute expression evaluation and replace it with its string
2495 // representation.
Craig Topperc81aff72018-09-25 20:55:55 +00002496 if (AltMacroMode && Token.getString().front() == '%' &&
Craig Topper3da977b2018-09-25 19:37:35 +00002497 Token.is(AsmToken::Integer))
Michael Zuckerman56704612017-05-01 13:20:12 +00002498 // Emit an integer value to the buffer.
2499 OS << Token.getIntVal();
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002500 // Only Token that was validated as a string and begins with '<'
2501 // is considered altMacroString!!!
Craig Topperc81aff72018-09-25 20:55:55 +00002502 else if (AltMacroMode && Token.getString().front() == '<' &&
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002503 Token.is(AsmToken::String)) {
Craig Topperd2aab832018-09-25 20:13:55 +00002504 OS << altMacroString(Token.getStringContents());
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002505 }
Toma Tabacu217116e2015-04-27 10:50:29 +00002506 // We expect no quotes around the string's contents when
2507 // parsing for varargs.
Michael Zuckerman56704612017-05-01 13:20:12 +00002508 else if (Token.isNot(AsmToken::String) || VarargParameter)
Craig Topper84008482015-10-10 05:38:14 +00002509 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002510 else
Craig Topper84008482015-10-10 05:38:14 +00002511 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002512
2513 Pos += 1 + Argument.size();
2514 }
Preston Gurd05500642012-09-19 20:36:12 +00002515 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002516 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002517 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002518 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002519 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002520
Rafael Espindola1134ab232011-06-05 02:43:45 +00002521 return false;
2522}
Daniel Dunbar43235712010-07-18 18:54:11 +00002523
Nico Weber2a8f9222014-07-24 16:29:04 +00002524MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002525 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002526 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002527 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002528
Jim Grosbach4b905842013-09-20 23:08:21 +00002529static bool isOperator(AsmToken::TokenKind kind) {
2530 switch (kind) {
2531 default:
2532 return false;
2533 case AsmToken::Plus:
2534 case AsmToken::Minus:
2535 case AsmToken::Tilde:
2536 case AsmToken::Slash:
2537 case AsmToken::Star:
2538 case AsmToken::Dot:
2539 case AsmToken::Equal:
2540 case AsmToken::EqualEqual:
2541 case AsmToken::Pipe:
2542 case AsmToken::PipePipe:
2543 case AsmToken::Caret:
2544 case AsmToken::Amp:
2545 case AsmToken::AmpAmp:
2546 case AsmToken::Exclaim:
2547 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002548 case AsmToken::Less:
2549 case AsmToken::LessEqual:
2550 case AsmToken::LessLess:
2551 case AsmToken::LessGreater:
2552 case AsmToken::Greater:
2553 case AsmToken::GreaterEqual:
2554 case AsmToken::GreaterGreater:
2555 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002556 }
2557}
2558
David Majnemer16252452014-01-29 00:07:39 +00002559namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002560
David Majnemer16252452014-01-29 00:07:39 +00002561class AsmLexerSkipSpaceRAII {
2562public:
2563 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2564 Lexer.setSkipSpace(SkipSpace);
2565 }
2566
2567 ~AsmLexerSkipSpaceRAII() {
2568 Lexer.setSkipSpace(true);
2569 }
2570
2571private:
2572 AsmLexer &Lexer;
2573};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002574
2575} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002576
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002577bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2578
2579 if (Vararg) {
2580 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2581 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002582 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002583 }
2584 return false;
2585 }
2586
Rafael Espindola768b41c2012-06-15 14:02:34 +00002587 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002588
David Majnemer16252452014-01-29 00:07:39 +00002589 // Darwin doesn't use spaces to delmit arguments.
2590 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002591
Scott Egertona1fa68a2016-02-11 13:48:49 +00002592 bool SpaceEaten;
2593
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002594 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002595 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002596 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002597 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002598
Scott Egertona1fa68a2016-02-11 13:48:49 +00002599 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002600
Scott Egertona1fa68a2016-02-11 13:48:49 +00002601 if (Lexer.is(AsmToken::Comma))
2602 break;
2603
2604 if (Lexer.is(AsmToken::Space)) {
2605 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002606 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002607 }
Preston Gurd05500642012-09-19 20:36:12 +00002608
2609 // Spaces can delimit parameters, but could also be part an expression.
2610 // If the token after a space is an operator, add the token and the next
2611 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002612 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002613 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002614 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002615 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002616
Scott Egertona1fa68a2016-02-11 13:48:49 +00002617 // Whitespace after an operator can be ignored.
2618 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002619 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002620
2621 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002622 }
2623 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002624 if (SpaceEaten)
2625 break;
Preston Gurd05500642012-09-19 20:36:12 +00002626 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002627
Jim Grosbach4b905842013-09-20 23:08:21 +00002628 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002629 // to be able to fill in the remaining default parameter values
2630 if (Lexer.is(AsmToken::EndOfStatement))
2631 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002632
2633 // Adjust the current parentheses level.
2634 if (Lexer.is(AsmToken::LParen))
2635 ++ParenLevel;
2636 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2637 --ParenLevel;
2638
2639 // Append the token to the current argument list.
2640 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002641 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002642 }
Preston Gurd05500642012-09-19 20:36:12 +00002643
Rafael Espindola768b41c2012-06-15 14:02:34 +00002644 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002645 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002646 return false;
2647}
2648
2649// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002650bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002651 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002652 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002653 bool NamedParametersFound = false;
2654 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002655
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002656 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002657 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002658
Rafael Espindola768b41c2012-06-15 14:02:34 +00002659 // Parse two kinds of macro invocations:
2660 // - macros defined without any parameters accept an arbitrary number of them
2661 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002662 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002663 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2664 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002665 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002666 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002667
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002668 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002669 if (parseIdentifier(FA.Name))
2670 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002671
Nirav Dave2364748a2016-09-16 18:30:20 +00002672 if (Lexer.isNot(AsmToken::Equal))
2673 return TokError("expected '=' after formal parameter identifier");
2674
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002675 Lex();
2676
2677 NamedParametersFound = true;
2678 }
Michael Zuckerman56704612017-05-01 13:20:12 +00002679 bool Vararg = HasVararg && Parameter == (NParameters - 1);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002680
Nirav Dave2364748a2016-09-16 18:30:20 +00002681 if (NamedParametersFound && FA.Name.empty())
2682 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002683
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002684 SMLoc StrLoc = Lexer.getLoc();
2685 SMLoc EndLoc;
Craig Topperc81aff72018-09-25 20:55:55 +00002686 if (AltMacroMode && Lexer.is(AsmToken::Percent)) {
Craig Topper3da977b2018-09-25 19:37:35 +00002687 const MCExpr *AbsoluteExp;
2688 int64_t Value;
2689 /// Eat '%'
2690 Lex();
2691 if (parseExpression(AbsoluteExp, EndLoc))
2692 return false;
2693 if (!AbsoluteExp->evaluateAsAbsolute(Value,
2694 getStreamer().getAssemblerPtr()))
2695 return Error(StrLoc, "expected absolute expression");
2696 const char *StrChar = StrLoc.getPointer();
2697 const char *EndChar = EndLoc.getPointer();
2698 AsmToken newToken(AsmToken::Integer,
2699 StringRef(StrChar, EndChar - StrChar), Value);
2700 FA.Value.push_back(newToken);
Craig Topperc81aff72018-09-25 20:55:55 +00002701 } else if (AltMacroMode && Lexer.is(AsmToken::Less) &&
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002702 isAltmacroString(StrLoc, EndLoc)) {
Craig Topper3da977b2018-09-25 19:37:35 +00002703 const char *StrChar = StrLoc.getPointer();
2704 const char *EndChar = EndLoc.getPointer();
2705 jumpToLoc(EndLoc, CurBuffer);
2706 /// Eat from '<' to '>'
2707 Lex();
2708 AsmToken newToken(AsmToken::String,
2709 StringRef(StrChar, EndChar - StrChar));
2710 FA.Value.push_back(newToken);
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002711 } else if(parseMacroArgument(FA.Value, Vararg))
Craig Topper3da977b2018-09-25 19:37:35 +00002712 return true;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002713
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002714 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002715 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002716 unsigned FAI = 0;
2717 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002718 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002719 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002720
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002721 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002722 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002723 return Error(IDLoc, "parameter named '" + FA.Name +
2724 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002725 }
2726 PI = FAI;
2727 }
2728
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002729 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002730 if (A.size() <= PI)
2731 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002732 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002733
2734 if (FALocs.size() <= PI)
2735 FALocs.resize(PI + 1);
2736
2737 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002738 }
Jim Grosbach206661622012-07-30 22:44:17 +00002739
Preston Gurd242ed3152012-09-19 20:29:04 +00002740 // At the end of the statement, fill in remaining arguments that have
2741 // default values. If there aren't any, then the next argument is
2742 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002743 if (Lexer.is(AsmToken::EndOfStatement)) {
2744 bool Failure = false;
2745 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2746 if (A[FAI].empty()) {
2747 if (M->Parameters[FAI].Required) {
2748 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2749 "missing value for required parameter "
2750 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2751 Failure = true;
2752 }
2753
2754 if (!M->Parameters[FAI].Value.empty())
2755 A[FAI] = M->Parameters[FAI].Value;
2756 }
2757 }
2758 return Failure;
2759 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002760
2761 if (Lexer.is(AsmToken::Comma))
2762 Lex();
2763 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002764
2765 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002766}
2767
Jim Grosbach4b905842013-09-20 23:08:21 +00002768bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002769 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2770 // eliminate this, although we should protect against infinite loops.
2771 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2772 if (ActiveMacros.size() == MaxNestingDepth) {
2773 std::ostringstream MaxNestingDepthError;
2774 MaxNestingDepthError << "macros cannot be nested more than "
2775 << MaxNestingDepth << " levels deep."
2776 << " Use -asm-macro-max-nesting-depth to increase "
2777 "this limit.";
2778 return TokError(MaxNestingDepthError.str());
2779 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002780
Eli Bendersky38274122013-01-14 23:22:36 +00002781 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002782 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002783 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002784
Rafael Espindola1134ab232011-06-05 02:43:45 +00002785 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2786 // to hold the macro body with substitutions.
2787 SmallString<256> Buf;
2788 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002789 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002790
Toma Tabacu217116e2015-04-27 10:50:29 +00002791 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002792 return true;
2793
Eli Bendersky38274122013-01-14 23:22:36 +00002794 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002795 // instantiation.
2796 OS << ".endmacro\n";
2797
Rafael Espindola3560ff22014-08-27 20:03:13 +00002798 std::unique_ptr<MemoryBuffer> Instantiation =
2799 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002800
Daniel Dunbar43235712010-07-18 18:54:11 +00002801 // Create the macro instantiation object and add to the current macro
2802 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002803 MacroInstantiation *MI = new MacroInstantiation(
2804 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002805 ActiveMacros.push_back(MI);
2806
Toma Tabacu217116e2015-04-27 10:50:29 +00002807 ++NumOfMacroInstantiations;
2808
Daniel Dunbar43235712010-07-18 18:54:11 +00002809 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002810 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002811 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002812 Lex();
2813
2814 return false;
2815}
2816
Jim Grosbach4b905842013-09-20 23:08:21 +00002817void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002818 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002819 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002820 Lex();
2821
2822 // Pop the instantiation entry.
2823 delete ActiveMacros.back();
2824 ActiveMacros.pop_back();
2825}
2826
Jim Grosbach4b905842013-09-20 23:08:21 +00002827bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Nirav Dave7fd992a2018-08-16 16:31:14 +00002828 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002829 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002830 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002831 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
Nirav Dave7fd992a2018-08-16 16:31:14 +00002832 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002833 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002834
Pete Cooper80d21cb2015-06-22 19:35:57 +00002835 if (!Sym) {
2836 // In the case where we parse an expression starting with a '.', we will
2837 // not generate an error, nor will we create a symbol. In this case we
2838 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002839 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002840 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002841
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002842 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002843 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002844 if (NoDeadStrip)
2845 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2846
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002847 return false;
2848}
2849
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002850/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002851/// ::= identifier
2852/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002853bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002854 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002855 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2856 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002857 // handle this as a context dependent token, instead we detect adjacent tokens
2858 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002859 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2860 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002861
Hans Wennborgce69d772013-10-18 20:46:28 +00002862 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002863
2864 AsmToken Buf[1];
2865 Lexer.peekTokens(Buf, false);
2866
2867 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002868 return true;
2869
Hans Wennborgce69d772013-10-18 20:46:28 +00002870 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002871 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002872 return true;
2873
Nirav Daved0463322016-10-12 13:58:07 +00002874 // eat $ or @
2875 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002876 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002877 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002878 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002879 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002880 return false;
2881 }
2882
Jim Grosbach4b905842013-09-20 23:08:21 +00002883 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002884 return true;
2885
Sean Callanan936b0d32010-01-19 21:44:56 +00002886 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002887
Sean Callanan686ed8d2010-01-19 20:22:31 +00002888 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002889
2890 return false;
2891}
2892
Jim Grosbach4b905842013-09-20 23:08:21 +00002893/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002894/// ::= .equ identifier ',' expression
2895/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002896/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002897bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002898 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002899 if (check(parseIdentifier(Name), "expected identifier") ||
2900 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2901 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2902 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002903}
2904
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002905bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002906 if (check(getTok().isNot(AsmToken::String), "expected string"))
2907 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002908
2909 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002910 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002911 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2912 if (Str[i] != '\\') {
2913 Data += Str[i];
2914 continue;
2915 }
2916
2917 // Recognize escaped characters. Note that this escape semantics currently
Bill Wendling411f1882019-10-08 04:39:52 +00002918 // loosely follows Darwin 'as'.
Daniel Dunbaref668c12009-08-14 18:19:52 +00002919 ++i;
2920 if (i == e)
2921 return TokError("unexpected backslash at end of string");
2922
Bill Wendling411f1882019-10-08 04:39:52 +00002923 // Recognize hex sequences similarly to GNU 'as'.
2924 if (Str[i] == 'x' || Str[i] == 'X') {
2925 size_t length = Str.size();
2926 if (i + 1 >= length || !isHexDigit(Str[i + 1]))
2927 return TokError("invalid hexadecimal escape sequence");
2928
2929 // Consume hex characters. GNU 'as' reads all hexadecimal characters and
2930 // then truncates to the lower 16 bits. Seems reasonable.
2931 unsigned Value = 0;
2932 while (i + 1 < length && isHexDigit(Str[i + 1]))
2933 Value = Value * 16 + hexDigitValue(Str[++i]);
2934
2935 Data += (unsigned char)(Value & 0xFF);
2936 continue;
2937 }
2938
Daniel Dunbaref668c12009-08-14 18:19:52 +00002939 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002940 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002941 // Consume up to three octal characters.
2942 unsigned Value = Str[i] - '0';
2943
Jim Grosbach4b905842013-09-20 23:08:21 +00002944 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002945 ++i;
2946 Value = Value * 8 + (Str[i] - '0');
2947
Jim Grosbach4b905842013-09-20 23:08:21 +00002948 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002949 ++i;
2950 Value = Value * 8 + (Str[i] - '0');
2951 }
2952 }
2953
2954 if (Value > 255)
2955 return TokError("invalid octal escape sequence (out of range)");
2956
Jim Grosbach4b905842013-09-20 23:08:21 +00002957 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002958 continue;
2959 }
2960
2961 // Otherwise recognize individual escapes.
2962 switch (Str[i]) {
2963 default:
2964 // Just reject invalid escape sequences for now.
2965 return TokError("invalid escape sequence (unrecognized character)");
2966
2967 case 'b': Data += '\b'; break;
2968 case 'f': Data += '\f'; break;
2969 case 'n': Data += '\n'; break;
2970 case 'r': Data += '\r'; break;
2971 case 't': Data += '\t'; break;
2972 case '"': Data += '"'; break;
2973 case '\\': Data += '\\'; break;
2974 }
2975 }
2976
Nirav Davea645433c2016-07-18 15:24:03 +00002977 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002978 return false;
2979}
2980
Jim Grosbach4b905842013-09-20 23:08:21 +00002981/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002982/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002983bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002984 auto parseOp = [&]() -> bool {
2985 std::string Data;
2986 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002987 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002988 getStreamer().EmitBytes(Data);
2989 if (ZeroTerminated)
2990 getStreamer().EmitBytes(StringRef("\0", 1));
2991 return false;
2992 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002993
Nirav Dave1a9044b2016-10-24 14:35:29 +00002994 if (parseMany(parseOp))
2995 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002996 return false;
2997}
2998
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002999/// parseDirectiveReloc
3000/// ::= .reloc expression , identifier [ , expression ]
3001bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
3002 const MCExpr *Offset;
3003 const MCExpr *Expr = nullptr;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003004 int64_t OffsetValue;
Vladimir Stefanovic1d2714b2018-11-21 16:28:39 +00003005 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00003006
Daniel Sanders9f6ad492015-11-12 13:33:00 +00003007 if (parseExpression(Offset))
3008 return true;
3009
Vladimir Stefanovic1d2714b2018-11-21 16:28:39 +00003010 if ((Offset->evaluateAsAbsolute(OffsetValue,
3011 getStreamer().getAssemblerPtr()) &&
3012 check(OffsetValue < 0, OffsetLoc, "expression is negative")) ||
3013 (check(Offset->getKind() != llvm::MCExpr::Constant &&
3014 Offset->getKind() != llvm::MCExpr::SymbolRef,
3015 OffsetLoc, "expected non-negative number or a label")) ||
3016 (parseToken(AsmToken::Comma, "expected comma") ||
3017 check(getTok().isNot(AsmToken::Identifier), "expected relocation name")))
Nirav Davea645433c2016-07-18 15:24:03 +00003018 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00003019
Daniel Sanders9f6ad492015-11-12 13:33:00 +00003020 SMLoc NameLoc = Lexer.getTok().getLoc();
3021 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00003022 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00003023
3024 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00003025 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00003026 SMLoc ExprLoc = Lexer.getLoc();
3027 if (parseExpression(Expr))
3028 return true;
3029
3030 MCValue Value;
3031 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
3032 return Error(ExprLoc, "expression must be relocatable");
3033 }
3034
Nirav Davea645433c2016-07-18 15:24:03 +00003035 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00003036 "unexpected token in .reloc directive"))
3037 return true;
3038
Peter Smith57f661b2018-06-06 09:40:06 +00003039 const MCTargetAsmParser &MCT = getTargetParser();
3040 const MCSubtargetInfo &STI = MCT.getSTI();
3041 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc, STI))
Nirav Dave1ab71992016-07-18 19:35:21 +00003042 return Error(NameLoc, "unknown relocation name");
3043
Daniel Sanders9f6ad492015-11-12 13:33:00 +00003044 return false;
3045}
3046
Jim Grosbach4b905842013-09-20 23:08:21 +00003047/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00003048/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003049bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
3050 auto parseOp = [&]() -> bool {
3051 const MCExpr *Value;
3052 SMLoc ExprLoc = getLexer().getLoc();
3053 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00003054 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003055 // Special case constant expressions to match code generator.
3056 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3057 assert(Size <= 8 && "Invalid size");
3058 uint64_t IntValue = MCE->getValue();
3059 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
3060 return Error(ExprLoc, "out of range literal value");
3061 getStreamer().EmitIntValue(IntValue, Size);
3062 } else
3063 getStreamer().EmitValue(Value, Size, ExprLoc);
3064 return false;
3065 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00003066
Nirav Dave1a9044b2016-10-24 14:35:29 +00003067 if (parseMany(parseOp))
3068 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00003069 return false;
3070}
3071
Paul Robinson01954692018-04-11 15:14:05 +00003072static bool parseHexOcta(AsmParser &Asm, uint64_t &hi, uint64_t &lo) {
3073 if (Asm.getTok().isNot(AsmToken::Integer) &&
3074 Asm.getTok().isNot(AsmToken::BigNum))
3075 return Asm.TokError("unknown token in expression");
3076 SMLoc ExprLoc = Asm.getTok().getLoc();
3077 APInt IntValue = Asm.getTok().getAPIntVal();
3078 Asm.Lex();
3079 if (!IntValue.isIntN(128))
3080 return Asm.Error(ExprLoc, "out of range literal value");
3081 if (!IntValue.isIntN(64)) {
3082 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
3083 lo = IntValue.getLoBits(64).getZExtValue();
3084 } else {
3085 hi = 0;
3086 lo = IntValue.getZExtValue();
3087 }
3088 return false;
3089}
3090
David Woodhoused6de0d92014-02-01 16:20:59 +00003091/// ParseDirectiveOctaValue
3092/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003093
3094bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
3095 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00003096 if (checkForValidSection())
3097 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003098 uint64_t hi, lo;
Paul Robinson01954692018-04-11 15:14:05 +00003099 if (parseHexOcta(*this, hi, lo))
3100 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003101 if (MAI.isLittleEndian()) {
3102 getStreamer().EmitIntValue(lo, 8);
3103 getStreamer().EmitIntValue(hi, 8);
3104 } else {
3105 getStreamer().EmitIntValue(hi, 8);
3106 getStreamer().EmitIntValue(lo, 8);
3107 }
3108 return false;
3109 };
David Woodhoused6de0d92014-02-01 16:20:59 +00003110
Nirav Dave1a9044b2016-10-24 14:35:29 +00003111 if (parseMany(parseOp))
3112 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00003113 return false;
3114}
3115
Petr Hosek4cb08ce2016-09-23 19:25:15 +00003116bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
3117 // We don't truly support arithmetic on floating point expressions, so we
3118 // have to manually parse unary prefixes.
3119 bool IsNeg = false;
3120 if (getLexer().is(AsmToken::Minus)) {
3121 Lexer.Lex();
3122 IsNeg = true;
3123 } else if (getLexer().is(AsmToken::Plus))
3124 Lexer.Lex();
3125
3126 if (Lexer.is(AsmToken::Error))
3127 return TokError(Lexer.getErr());
3128 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
3129 Lexer.isNot(AsmToken::Identifier))
3130 return TokError("unexpected token in directive");
3131
3132 // Convert to an APFloat.
3133 APFloat Value(Semantics);
3134 StringRef IDVal = getTok().getString();
3135 if (getLexer().is(AsmToken::Identifier)) {
3136 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
3137 Value = APFloat::getInf(Semantics);
3138 else if (!IDVal.compare_lower("nan"))
3139 Value = APFloat::getNaN(Semantics, false, ~0);
3140 else
3141 return TokError("invalid floating point literal");
3142 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
3143 APFloat::opInvalidOp)
3144 return TokError("invalid floating point literal");
3145 if (IsNeg)
3146 Value.changeSign();
3147
3148 // Consume the numeric token.
3149 Lex();
3150
3151 Res = Value.bitcastToAPInt();
3152
3153 return false;
3154}
3155
Jim Grosbach4b905842013-09-20 23:08:21 +00003156/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00003157/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003158bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
3159 const fltSemantics &Semantics) {
3160 auto parseOp = [&]() -> bool {
3161 APInt AsInt;
3162 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00003163 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003164 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
3165 AsInt.getBitWidth() / 8);
3166 return false;
3167 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00003168
Nirav Dave1a9044b2016-10-24 14:35:29 +00003169 if (parseMany(parseOp))
3170 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00003171 return false;
3172}
3173
Jim Grosbach4b905842013-09-20 23:08:21 +00003174/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00003175/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003176bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003177 SMLoc NumBytesLoc = Lexer.getLoc();
3178 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003179 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00003180 return true;
3181
Rafael Espindolab91bac62010-10-05 19:42:57 +00003182 int64_t Val = 0;
3183 if (getLexer().is(AsmToken::Comma)) {
3184 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003185 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00003186 return true;
3187 }
3188
Nirav Davea645433c2016-07-18 15:24:03 +00003189 if (parseToken(AsmToken::EndOfStatement,
3190 "unexpected token in '.zero' directive"))
3191 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00003192 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00003193
3194 return false;
3195}
3196
Jim Grosbach4b905842013-09-20 23:08:21 +00003197/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00003198/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003199bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003200 SMLoc NumValuesLoc = Lexer.getLoc();
3201 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003202 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00003203 return true;
3204
Roman Divackye33098f2013-09-24 17:44:41 +00003205 int64_t FillSize = 1;
3206 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00003207
David Majnemer522d3db2014-02-01 07:19:38 +00003208 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003209
Nirav Dave1a9044b2016-10-24 14:35:29 +00003210 if (parseOptionalToken(AsmToken::Comma)) {
3211 SizeLoc = getTok().getLoc();
3212 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00003213 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003214 if (parseOptionalToken(AsmToken::Comma)) {
3215 ExprLoc = getTok().getLoc();
3216 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00003217 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00003218 }
3219 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003220 if (parseToken(AsmToken::EndOfStatement,
3221 "unexpected token in '.fill' directive"))
3222 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003223
David Majnemer522d3db2014-02-01 07:19:38 +00003224 if (FillSize < 0) {
3225 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00003226 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00003227 }
3228 if (FillSize > 8) {
3229 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
3230 FillSize = 8;
3231 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00003232
David Majnemer522d3db2014-02-01 07:19:38 +00003233 if (!isUInt<32>(FillExpr) && FillSize > 4)
3234 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
3235
Petr Hosek67a94a72016-05-28 05:57:48 +00003236 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00003237
3238 return false;
3239}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003240
Jim Grosbach4b905842013-09-20 23:08:21 +00003241/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003242/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003243bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00003244 const MCExpr *Offset;
Oliver Stannard268f42f2016-12-14 10:43:58 +00003245 SMLoc OffsetLoc = Lexer.getLoc();
Nirav Davef43cc9f2016-10-10 15:24:54 +00003246 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003247 return true;
3248
3249 // Parse optional fill expression.
3250 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003251 if (parseOptionalToken(AsmToken::Comma))
3252 if (parseAbsoluteExpression(FillExpr))
3253 return addErrorSuffix(" in '.org' directive");
3254 if (parseToken(AsmToken::EndOfStatement))
3255 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00003256
Oliver Stannard268f42f2016-12-14 10:43:58 +00003257 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003258 return false;
3259}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003260
Jim Grosbach4b905842013-09-20 23:08:21 +00003261/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003262/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00003263bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003264 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003265 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003266 SMLoc MaxBytesLoc;
3267 bool HasFillExpr = false;
3268 int64_t FillExpr = 0;
3269 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003270
3271 auto parseAlign = [&]() -> bool {
Coby Tayreed483a102017-08-02 17:36:10 +00003272 if (parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00003273 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003274 if (parseOptionalToken(AsmToken::Comma)) {
3275 // The fill expression can be omitted while specifying a maximum number of
3276 // alignment bytes, e.g:
3277 // .align 3,,4
3278 if (getTok().isNot(AsmToken::Comma)) {
3279 HasFillExpr = true;
3280 if (parseAbsoluteExpression(FillExpr))
3281 return true;
3282 }
3283 if (parseOptionalToken(AsmToken::Comma))
3284 if (parseTokenLoc(MaxBytesLoc) ||
3285 parseAbsoluteExpression(MaxBytesToFill))
3286 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003287 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003288 return parseToken(AsmToken::EndOfStatement);
3289 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003290
Coby Tayreed483a102017-08-02 17:36:10 +00003291 if (checkForValidSection())
3292 return addErrorSuffix(" in directive");
3293 // Ignore empty '.p2align' directives for GNU-as compatibility
3294 if (IsPow2 && (ValueSize == 1) && getTok().is(AsmToken::EndOfStatement)) {
3295 Warning(AlignmentLoc, "p2align directive with no operand(s) is ignored");
3296 return parseToken(AsmToken::EndOfStatement);
3297 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003298 if (parseAlign())
3299 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003300
Nirav Dave2364748a2016-09-16 18:30:20 +00003301 // Always emit an alignment here even if we thrown an error.
3302 bool ReturnVal = false;
3303
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003304 // Compute alignment in bytes.
3305 if (IsPow2) {
3306 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003307 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003308 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003309 Alignment = 31;
3310 }
3311
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003312 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003313 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003314 // Reject alignments that aren't either a power of two or zero,
3315 // for gas compatibility. Alignment of zero is silently rounded
3316 // up to one.
3317 if (Alignment == 0)
3318 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003319 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003320 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003321 }
3322
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003323 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003324 if (MaxBytesLoc.isValid()) {
3325 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003326 ReturnVal |= Error(MaxBytesLoc,
3327 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003328 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003329 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003330 }
3331
3332 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003333 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003334 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003335 MaxBytesToFill = 0;
3336 }
3337 }
3338
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003339 // Check whether we should use optimal code alignment for this .align
3340 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003341 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003342 assert(Section && "must have section to emit alignment");
3343 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003344 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3345 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003346 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003347 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003348 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003349 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3350 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003351 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003352
Nirav Dave2364748a2016-09-16 18:30:20 +00003353 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003354}
3355
Jim Grosbach4b905842013-09-20 23:08:21 +00003356/// parseDirectiveFile
Paul Robinson29f5f982018-01-09 23:31:48 +00003357/// ::= .file filename
Scott Linder16c7bda2018-02-23 23:01:06 +00003358/// ::= .file number [directory] filename [md5 checksum] [source source-text]
Jim Grosbach4b905842013-09-20 23:08:21 +00003359bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003360 // FIXME: I'm not sure what this is.
3361 int64_t FileNumber = -1;
Eli Bendersky17233942013-01-15 22:59:42 +00003362 if (getLexer().is(AsmToken::Integer)) {
3363 FileNumber = getTok().getIntVal();
3364 Lex();
3365
Paul Robinsonb271f312018-03-29 17:16:41 +00003366 if (FileNumber < 0)
3367 return TokError("negative file number");
Eli Bendersky17233942013-01-15 22:59:42 +00003368 }
3369
Paul Robinson37fbb922018-06-20 16:12:03 +00003370 std::string Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003371
3372 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003373 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003374 if (check(getTok().isNot(AsmToken::String),
3375 "unexpected token in '.file' directive") ||
3376 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003377 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003378
3379 StringRef Directory;
3380 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003381 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003382 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003383 if (check(FileNumber == -1,
3384 "explicit path specified, but no file number") ||
3385 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003386 return true;
3387 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003388 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003389 } else {
3390 Filename = Path;
3391 }
3392
Paul Robinson01954692018-04-11 15:14:05 +00003393 uint64_t MD5Hi, MD5Lo;
3394 bool HasMD5 = false;
Scott Linder16c7bda2018-02-23 23:01:06 +00003395
3396 Optional<StringRef> Source;
3397 bool HasSource = false;
3398 std::string SourceString;
3399
3400 while (!parseOptionalToken(AsmToken::EndOfStatement)) {
Paul Robinson29f5f982018-01-09 23:31:48 +00003401 StringRef Keyword;
3402 if (check(getTok().isNot(AsmToken::Identifier),
3403 "unexpected token in '.file' directive") ||
Scott Linder16c7bda2018-02-23 23:01:06 +00003404 parseIdentifier(Keyword))
Paul Robinson29f5f982018-01-09 23:31:48 +00003405 return true;
Scott Linder16c7bda2018-02-23 23:01:06 +00003406 if (Keyword == "md5") {
Paul Robinson01954692018-04-11 15:14:05 +00003407 HasMD5 = true;
Scott Linder16c7bda2018-02-23 23:01:06 +00003408 if (check(FileNumber == -1,
3409 "MD5 checksum specified, but no file number") ||
Paul Robinson01954692018-04-11 15:14:05 +00003410 parseHexOcta(*this, MD5Hi, MD5Lo))
Scott Linder16c7bda2018-02-23 23:01:06 +00003411 return true;
3412 } else if (Keyword == "source") {
3413 HasSource = true;
3414 if (check(FileNumber == -1,
3415 "source specified, but no file number") ||
3416 check(getTok().isNot(AsmToken::String),
3417 "unexpected token in '.file' directive") ||
3418 parseEscapedString(SourceString))
3419 return true;
3420 } else {
3421 return TokError("unexpected token in '.file' directive");
3422 }
Paul Robinson29f5f982018-01-09 23:31:48 +00003423 }
Eli Bendersky17233942013-01-15 22:59:42 +00003424
Reid Kleckner98bbd072018-12-21 23:35:48 +00003425 if (FileNumber == -1) {
Reid Klecknerf38bc4f2019-02-05 21:14:09 +00003426 // Ignore the directive if there is no number and the target doesn't support
3427 // numberless .file directives. This allows some portability of assembler
3428 // between different object file formats.
3429 if (getContext().getAsmInfo()->hasSingleParameterDotFile())
3430 getStreamer().EmitFileDirective(Filename);
Reid Kleckner98bbd072018-12-21 23:35:48 +00003431 } else {
Brian Cain3e0ca572018-08-28 16:23:39 +00003432 // In case there is a -g option as well as debug info from directive .file,
3433 // we turn off the -g option, directly use the existing debug info instead.
Paul Robinson26cc5bc2019-06-21 13:10:19 +00003434 // Throw away any implicit file table for the assembler source.
Brian Cain3e0ca572018-08-28 16:23:39 +00003435 if (Ctx.getGenDwarfForAssembly()) {
Paul Robinson26cc5bc2019-06-21 13:10:19 +00003436 Ctx.getMCDwarfLineTable(0).resetFileTable();
Brian Cain3e0ca572018-08-28 16:23:39 +00003437 Ctx.setGenDwarfForAssembly(false);
3438 }
3439
Eric Christopher798e83b2019-04-04 23:34:38 +00003440 Optional<MD5::MD5Result> CKMem;
Paul Robinson01954692018-04-11 15:14:05 +00003441 if (HasMD5) {
Eric Christopher798e83b2019-04-04 23:34:38 +00003442 MD5::MD5Result Sum;
Paul Robinson01954692018-04-11 15:14:05 +00003443 for (unsigned i = 0; i != 8; ++i) {
Eric Christopher798e83b2019-04-04 23:34:38 +00003444 Sum.Bytes[i] = uint8_t(MD5Hi >> ((7 - i) * 8));
3445 Sum.Bytes[i + 8] = uint8_t(MD5Lo >> ((7 - i) * 8));
Paul Robinson01954692018-04-11 15:14:05 +00003446 }
Eric Christopher798e83b2019-04-04 23:34:38 +00003447 CKMem = Sum;
Paul Robinson29f5f982018-01-09 23:31:48 +00003448 }
Scott Linder16c7bda2018-02-23 23:01:06 +00003449 if (HasSource) {
3450 char *SourceBuf = static_cast<char *>(Ctx.allocate(SourceString.size()));
3451 memcpy(SourceBuf, SourceString.data(), SourceString.size());
3452 Source = StringRef(SourceBuf, SourceString.size());
3453 }
Paul Robinson547adca2018-06-21 16:42:03 +00003454 if (FileNumber == 0) {
3455 if (Ctx.getDwarfVersion() < 5)
3456 return Warning(DirectiveLoc, "file 0 not supported prior to DWARF-5");
Paul Robinsonb271f312018-03-29 17:16:41 +00003457 getStreamer().emitDwarfFile0Directive(Directory, Filename, CKMem, Source);
Paul Robinson547adca2018-06-21 16:42:03 +00003458 } else {
Paul Robinsonb271f312018-03-29 17:16:41 +00003459 Expected<unsigned> FileNumOrErr = getStreamer().tryEmitDwarfFileDirective(
3460 FileNumber, Directory, Filename, CKMem, Source);
3461 if (!FileNumOrErr)
3462 return Error(DirectiveLoc, toString(FileNumOrErr.takeError()));
Paul Robinsonb271f312018-03-29 17:16:41 +00003463 }
Paul Robinsoncc7344a2018-06-14 13:38:20 +00003464 // Alert the user if there are some .file directives with MD5 and some not.
3465 // But only do that once.
3466 if (!ReportedInconsistentMD5 && !Ctx.isDwarfMD5UsageConsistent(0)) {
3467 ReportedInconsistentMD5 = true;
3468 return Warning(DirectiveLoc, "inconsistent use of MD5 checksums");
3469 }
Eli Bendersky17233942013-01-15 22:59:42 +00003470 }
3471
3472 return false;
3473}
3474
Jim Grosbach4b905842013-09-20 23:08:21 +00003475/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003476/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003477bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003478 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003479 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003480 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3481 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003482 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003483 // FIXME: Do something with the .line.
3484 }
Nirav Davea645433c2016-07-18 15:24:03 +00003485 if (parseToken(AsmToken::EndOfStatement,
3486 "unexpected token in '.line' directive"))
3487 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003488
3489 return false;
3490}
3491
Jim Grosbach4b905842013-09-20 23:08:21 +00003492/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003493/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3494/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3495/// The first number is a file number, must have been previously assigned with
3496/// a .file directive, the second number is the line number and optionally the
3497/// third number is a column position (zero if not specified). The remaining
3498/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003499bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003500 int64_t FileNumber = 0, LineNumber = 0;
3501 SMLoc Loc = getTok().getLoc();
3502 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
Paul Robinson11539b02018-06-22 14:16:11 +00003503 check(FileNumber < 1 && Ctx.getDwarfVersion() < 5, Loc,
Nirav Davea645433c2016-07-18 15:24:03 +00003504 "file number less than one in '.loc' directive") ||
3505 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3506 "unassigned file number in '.loc' directive"))
3507 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003508
Nirav Davea645433c2016-07-18 15:24:03 +00003509 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003510 if (getLexer().is(AsmToken::Integer)) {
3511 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003512 if (LineNumber < 0)
3513 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003514 Lex();
3515 }
3516
3517 int64_t ColumnPos = 0;
3518 if (getLexer().is(AsmToken::Integer)) {
3519 ColumnPos = getTok().getIntVal();
3520 if (ColumnPos < 0)
3521 return TokError("column position less than zero in '.loc' directive");
3522 Lex();
3523 }
3524
3525 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3526 unsigned Isa = 0;
3527 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003528
Nirav Dave1a9044b2016-10-24 14:35:29 +00003529 auto parseLocOp = [&]() -> bool {
3530 StringRef Name;
3531 SMLoc Loc = getTok().getLoc();
3532 if (parseIdentifier(Name))
3533 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003534
Nirav Dave1a9044b2016-10-24 14:35:29 +00003535 if (Name == "basic_block")
3536 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3537 else if (Name == "prologue_end")
3538 Flags |= DWARF2_FLAG_PROLOGUE_END;
3539 else if (Name == "epilogue_begin")
3540 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3541 else if (Name == "is_stmt") {
3542 Loc = getTok().getLoc();
3543 const MCExpr *Value;
3544 if (parseExpression(Value))
3545 return true;
3546 // The expression must be the constant 0 or 1.
3547 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3548 int Value = MCE->getValue();
3549 if (Value == 0)
3550 Flags &= ~DWARF2_FLAG_IS_STMT;
3551 else if (Value == 1)
3552 Flags |= DWARF2_FLAG_IS_STMT;
3553 else
3554 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003555 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003556 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003557 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003558 } else if (Name == "isa") {
3559 Loc = getTok().getLoc();
3560 const MCExpr *Value;
3561 if (parseExpression(Value))
3562 return true;
3563 // The expression must be a constant greater or equal to 0.
3564 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3565 int Value = MCE->getValue();
3566 if (Value < 0)
3567 return Error(Loc, "isa number less than zero");
3568 Isa = Value;
3569 } else {
3570 return Error(Loc, "isa number not a constant value");
3571 }
3572 } else if (Name == "discriminator") {
3573 if (parseAbsoluteExpression(Discriminator))
3574 return true;
3575 } else {
3576 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003577 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003578 return false;
3579 };
3580
Nirav Davee2369aa2016-10-26 17:28:58 +00003581 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003582 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003583
3584 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3585 Isa, Discriminator, StringRef());
3586
3587 return false;
3588}
3589
Jim Grosbach4b905842013-09-20 23:08:21 +00003590/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003591/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003592bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003593 return TokError("unsupported directive '.stabs'");
3594}
3595
Reid Kleckner2214ed82016-01-29 00:49:42 +00003596/// parseDirectiveCVFile
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003597/// ::= .cv_file number filename [checksum] [checksumkind]
Reid Kleckner2214ed82016-01-29 00:49:42 +00003598bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003599 SMLoc FileNumberLoc = getTok().getLoc();
3600 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003601 std::string Filename;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003602 std::string Checksum;
3603 int64_t ChecksumKind = 0;
Nirav Davea645433c2016-07-18 15:24:03 +00003604
3605 if (parseIntToken(FileNumber,
3606 "expected file number in '.cv_file' directive") ||
3607 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3608 check(getTok().isNot(AsmToken::String),
3609 "unexpected token in '.cv_file' directive") ||
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003610 parseEscapedString(Filename))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003611 return true;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003612 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3613 if (check(getTok().isNot(AsmToken::String),
3614 "unexpected token in '.cv_file' directive") ||
3615 parseEscapedString(Checksum) ||
3616 parseIntToken(ChecksumKind,
3617 "expected checksum kind in '.cv_file' directive") ||
3618 parseToken(AsmToken::EndOfStatement,
3619 "unexpected token in '.cv_file' directive"))
3620 return true;
3621 }
Nirav Dave1ab71992016-07-18 19:35:21 +00003622
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003623 Checksum = fromHex(Checksum);
3624 void *CKMem = Ctx.allocate(Checksum.size(), 1);
3625 memcpy(CKMem, Checksum.data(), Checksum.size());
3626 ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem),
3627 Checksum.size());
3628
3629 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename, ChecksumAsBytes,
3630 static_cast<uint8_t>(ChecksumKind)))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003631 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003632
3633 return false;
3634}
3635
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003636bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3637 StringRef DirectiveName) {
3638 SMLoc Loc;
3639 return parseTokenLoc(Loc) ||
3640 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3641 "' directive") ||
3642 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3643 "expected function id within range [0, UINT_MAX)");
3644}
3645
3646bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3647 SMLoc Loc;
3648 return parseTokenLoc(Loc) ||
3649 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3650 "' directive") ||
3651 check(FileNumber < 1, Loc, "file number less than one in '" +
3652 DirectiveName + "' directive") ||
3653 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3654 "unassigned file number in '" + DirectiveName + "' directive");
3655}
3656
3657/// parseDirectiveCVFuncId
3658/// ::= .cv_func_id FunctionId
3659///
3660/// Introduces a function ID that can be used with .cv_loc.
3661bool AsmParser::parseDirectiveCVFuncId() {
3662 SMLoc FunctionIdLoc = getTok().getLoc();
3663 int64_t FunctionId;
3664
3665 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3666 parseToken(AsmToken::EndOfStatement,
3667 "unexpected token in '.cv_func_id' directive"))
3668 return true;
3669
3670 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003671 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003672
3673 return false;
3674}
3675
3676/// parseDirectiveCVInlineSiteId
3677/// ::= .cv_inline_site_id FunctionId
3678/// "within" IAFunc
3679/// "inlined_at" IAFile IALine [IACol]
3680///
3681/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3682/// at" source location information for use in the line table of the caller,
3683/// whether the caller is a real function or another inlined call site.
3684bool AsmParser::parseDirectiveCVInlineSiteId() {
3685 SMLoc FunctionIdLoc = getTok().getLoc();
3686 int64_t FunctionId;
3687 int64_t IAFunc;
3688 int64_t IAFile;
3689 int64_t IALine;
3690 int64_t IACol = 0;
3691
3692 // FunctionId
3693 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3694 return true;
3695
3696 // "within"
3697 if (check((getLexer().isNot(AsmToken::Identifier) ||
3698 getTok().getIdentifier() != "within"),
3699 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3700 return true;
3701 Lex();
3702
3703 // IAFunc
3704 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3705 return true;
3706
3707 // "inlined_at"
3708 if (check((getLexer().isNot(AsmToken::Identifier) ||
3709 getTok().getIdentifier() != "inlined_at"),
3710 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3711 "directive") )
3712 return true;
3713 Lex();
3714
3715 // IAFile IALine
3716 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3717 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3718 return true;
3719
3720 // [IACol]
3721 if (getLexer().is(AsmToken::Integer)) {
3722 IACol = getTok().getIntVal();
3723 Lex();
3724 }
3725
3726 if (parseToken(AsmToken::EndOfStatement,
3727 "unexpected token in '.cv_inline_site_id' directive"))
3728 return true;
3729
3730 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3731 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003732 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003733
3734 return false;
3735}
3736
Reid Kleckner2214ed82016-01-29 00:49:42 +00003737/// parseDirectiveCVLoc
3738/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3739/// [is_stmt VALUE]
3740/// The first number is a file number, must have been previously assigned with
3741/// a .file directive, the second number is the line number and optionally the
3742/// third number is a column position (zero if not specified). The remaining
3743/// optional items are .loc sub-directives.
3744bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003745 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003746 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003747 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3748 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003749 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003750
3751 int64_t LineNumber = 0;
3752 if (getLexer().is(AsmToken::Integer)) {
3753 LineNumber = getTok().getIntVal();
3754 if (LineNumber < 0)
3755 return TokError("line number less than zero in '.cv_loc' directive");
3756 Lex();
3757 }
3758
3759 int64_t ColumnPos = 0;
3760 if (getLexer().is(AsmToken::Integer)) {
3761 ColumnPos = getTok().getIntVal();
3762 if (ColumnPos < 0)
3763 return TokError("column position less than zero in '.cv_loc' directive");
3764 Lex();
3765 }
3766
3767 bool PrologueEnd = false;
3768 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003769
3770 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003771 StringRef Name;
3772 SMLoc Loc = getTok().getLoc();
3773 if (parseIdentifier(Name))
3774 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003775 if (Name == "prologue_end")
3776 PrologueEnd = true;
3777 else if (Name == "is_stmt") {
3778 Loc = getTok().getLoc();
3779 const MCExpr *Value;
3780 if (parseExpression(Value))
3781 return true;
3782 // The expression must be the constant 0 or 1.
3783 IsStmt = ~0ULL;
3784 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3785 IsStmt = MCE->getValue();
3786
3787 if (IsStmt > 1)
3788 return Error(Loc, "is_stmt value not 0 or 1");
3789 } else {
3790 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3791 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003792 return false;
3793 };
3794
3795 if (parseMany(parseOp, false /*hasComma*/))
3796 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003797
3798 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003799 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3800 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003801 return false;
3802}
3803
3804/// parseDirectiveCVLinetable
3805/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3806bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003807 int64_t FunctionId;
3808 StringRef FnStartName, FnEndName;
3809 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003810 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003811 parseToken(AsmToken::Comma,
3812 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003813 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3814 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003815 parseToken(AsmToken::Comma,
3816 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003817 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3818 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003819 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003820
3821 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3822 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3823
3824 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3825 return false;
3826}
3827
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003828/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003829/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003830bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003831 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3832 StringRef FnStartName, FnEndName;
3833 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003834 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003835 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003836 parseIntToken(
3837 SourceFileId,
3838 "expected SourceField in '.cv_inline_linetable' directive") ||
3839 check(SourceFileId <= 0, Loc,
3840 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003841 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003842 parseIntToken(
3843 SourceLineNum,
3844 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3845 check(SourceLineNum < 0, Loc,
3846 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003847 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3848 "expected identifier in directive") ||
3849 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3850 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003851 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003852
Nirav Davea645433c2016-07-18 15:24:03 +00003853 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3854 return true;
3855
3856 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3857 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003858 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3859 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003860 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003861 return false;
3862}
3863
Nilanjana Basuda60fc82019-08-05 14:16:58 +00003864void AsmParser::initializeCVDefRangeTypeMap() {
3865 CVDefRangeTypeMap["reg"] = CVDR_DEFRANGE_REGISTER;
3866 CVDefRangeTypeMap["frame_ptr_rel"] = CVDR_DEFRANGE_FRAMEPOINTER_REL;
3867 CVDefRangeTypeMap["subfield_reg"] = CVDR_DEFRANGE_SUBFIELD_REGISTER;
3868 CVDefRangeTypeMap["reg_rel"] = CVDR_DEFRANGE_REGISTER_REL;
3869}
3870
David Majnemer408b5e62016-02-05 01:55:49 +00003871/// parseDirectiveCVDefRange
3872/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3873bool AsmParser::parseDirectiveCVDefRange() {
3874 SMLoc Loc;
3875 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3876 while (getLexer().is(AsmToken::Identifier)) {
3877 Loc = getLexer().getLoc();
3878 StringRef GapStartName;
3879 if (parseIdentifier(GapStartName))
3880 return Error(Loc, "expected identifier in directive");
3881 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3882
3883 Loc = getLexer().getLoc();
3884 StringRef GapEndName;
3885 if (parseIdentifier(GapEndName))
3886 return Error(Loc, "expected identifier in directive");
3887 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3888
3889 Ranges.push_back({GapStartSym, GapEndSym});
3890 }
3891
Nilanjana Basuda60fc82019-08-05 14:16:58 +00003892 StringRef CVDefRangeTypeStr;
3893 if (parseToken(
3894 AsmToken::Comma,
3895 "expected comma before def_range type in .cv_def_range directive") ||
3896 parseIdentifier(CVDefRangeTypeStr))
3897 return Error(Loc, "expected def_range type in directive");
David Majnemer408b5e62016-02-05 01:55:49 +00003898
Nilanjana Basuda60fc82019-08-05 14:16:58 +00003899 StringMap<CVDefRangeType>::const_iterator CVTypeIt =
3900 CVDefRangeTypeMap.find(CVDefRangeTypeStr);
3901 CVDefRangeType CVDRType = (CVTypeIt == CVDefRangeTypeMap.end())
3902 ? CVDR_DEFRANGE
3903 : CVTypeIt->getValue();
3904 switch (CVDRType) {
3905 case CVDR_DEFRANGE_REGISTER: {
3906 int64_t DRRegister;
3907 if (parseToken(AsmToken::Comma, "expected comma before register number in "
3908 ".cv_def_range directive") ||
3909 parseAbsoluteExpression(DRRegister))
3910 return Error(Loc, "expected register number");
3911
Reid Kleckner7bbe7112019-10-19 01:44:09 +00003912 codeview::DefRangeRegisterHeader DRHdr;
Nilanjana Basuda60fc82019-08-05 14:16:58 +00003913 DRHdr.Register = DRRegister;
3914 DRHdr.MayHaveNoName = 0;
3915 getStreamer().EmitCVDefRangeDirective(Ranges, DRHdr);
3916 break;
3917 }
3918 case CVDR_DEFRANGE_FRAMEPOINTER_REL: {
3919 int64_t DROffset;
3920 if (parseToken(AsmToken::Comma,
3921 "expected comma before offset in .cv_def_range directive") ||
3922 parseAbsoluteExpression(DROffset))
3923 return Error(Loc, "expected offset value");
3924
Reid Kleckner7bbe7112019-10-19 01:44:09 +00003925 codeview::DefRangeFramePointerRelHeader DRHdr;
Nilanjana Basuda60fc82019-08-05 14:16:58 +00003926 DRHdr.Offset = DROffset;
3927 getStreamer().EmitCVDefRangeDirective(Ranges, DRHdr);
3928 break;
3929 }
3930 case CVDR_DEFRANGE_SUBFIELD_REGISTER: {
3931 int64_t DRRegister;
3932 int64_t DROffsetInParent;
3933 if (parseToken(AsmToken::Comma, "expected comma before register number in "
3934 ".cv_def_range directive") ||
3935 parseAbsoluteExpression(DRRegister))
3936 return Error(Loc, "expected register number");
3937 if (parseToken(AsmToken::Comma,
3938 "expected comma before offset in .cv_def_range directive") ||
3939 parseAbsoluteExpression(DROffsetInParent))
3940 return Error(Loc, "expected offset value");
3941
Reid Kleckner7bbe7112019-10-19 01:44:09 +00003942 codeview::DefRangeSubfieldRegisterHeader DRHdr;
Nilanjana Basuda60fc82019-08-05 14:16:58 +00003943 DRHdr.Register = DRRegister;
3944 DRHdr.MayHaveNoName = 0;
3945 DRHdr.OffsetInParent = DROffsetInParent;
3946 getStreamer().EmitCVDefRangeDirective(Ranges, DRHdr);
3947 break;
3948 }
3949 case CVDR_DEFRANGE_REGISTER_REL: {
3950 int64_t DRRegister;
3951 int64_t DRFlags;
3952 int64_t DRBasePointerOffset;
3953 if (parseToken(AsmToken::Comma, "expected comma before register number in "
3954 ".cv_def_range directive") ||
3955 parseAbsoluteExpression(DRRegister))
3956 return Error(Loc, "expected register value");
3957 if (parseToken(
3958 AsmToken::Comma,
3959 "expected comma before flag value in .cv_def_range directive") ||
3960 parseAbsoluteExpression(DRFlags))
3961 return Error(Loc, "expected flag value");
3962 if (parseToken(AsmToken::Comma, "expected comma before base pointer offset "
3963 "in .cv_def_range directive") ||
3964 parseAbsoluteExpression(DRBasePointerOffset))
3965 return Error(Loc, "expected base pointer offset value");
3966
Reid Kleckner7bbe7112019-10-19 01:44:09 +00003967 codeview::DefRangeRegisterRelHeader DRHdr;
Nilanjana Basuda60fc82019-08-05 14:16:58 +00003968 DRHdr.Register = DRRegister;
3969 DRHdr.Flags = DRFlags;
3970 DRHdr.BasePointerOffset = DRBasePointerOffset;
3971 getStreamer().EmitCVDefRangeDirective(Ranges, DRHdr);
3972 break;
3973 }
3974 default:
3975 return Error(Loc, "unexpected def_range type in .cv_def_range directive");
3976 }
3977 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003978}
3979
Reid Kleckner06d02d02018-09-07 21:30:52 +00003980/// parseDirectiveCVString
3981/// ::= .cv_stringtable "string"
3982bool AsmParser::parseDirectiveCVString() {
3983 std::string Data;
3984 if (checkForValidSection() || parseEscapedString(Data))
3985 return addErrorSuffix(" in '.cv_string' directive");
3986
3987 // Put the string in the table and emit the offset.
3988 std::pair<StringRef, unsigned> Insertion =
3989 getCVContext().addToStringTable(Data);
3990 getStreamer().EmitIntValue(Insertion.second, 4);
3991 return false;
3992}
3993
Reid Kleckner2214ed82016-01-29 00:49:42 +00003994/// parseDirectiveCVStringTable
3995/// ::= .cv_stringtable
3996bool AsmParser::parseDirectiveCVStringTable() {
3997 getStreamer().EmitCVStringTableDirective();
3998 return false;
3999}
4000
4001/// parseDirectiveCVFileChecksums
4002/// ::= .cv_filechecksums
4003bool AsmParser::parseDirectiveCVFileChecksums() {
4004 getStreamer().EmitCVFileChecksumsDirective();
4005 return false;
4006}
4007
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00004008/// parseDirectiveCVFileChecksumOffset
4009/// ::= .cv_filechecksumoffset fileno
4010bool AsmParser::parseDirectiveCVFileChecksumOffset() {
4011 int64_t FileNo;
4012 if (parseIntToken(FileNo, "expected identifier in directive"))
4013 return true;
4014 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
4015 return true;
4016 getStreamer().EmitCVFileChecksumOffsetDirective(FileNo);
4017 return false;
4018}
4019
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00004020/// parseDirectiveCVFPOData
4021/// ::= .cv_fpo_data procsym
4022bool AsmParser::parseDirectiveCVFPOData() {
4023 SMLoc DirLoc = getLexer().getLoc();
4024 StringRef ProcName;
4025 if (parseIdentifier(ProcName))
4026 return TokError("expected symbol name");
4027 if (parseEOL("unexpected tokens"))
4028 return addErrorSuffix(" in '.cv_fpo_data' directive");
4029 MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName);
4030 getStreamer().EmitCVFPOData(ProcSym, DirLoc);
4031 return false;
4032}
4033
Jim Grosbach4b905842013-09-20 23:08:21 +00004034/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00004035/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00004036bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00004037 StringRef Name;
4038 bool EH = false;
4039 bool Debug = false;
4040
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004041 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00004042 return TokError("Expected an identifier");
4043
4044 if (Name == ".eh_frame")
4045 EH = true;
4046 else if (Name == ".debug_frame")
4047 Debug = true;
4048
4049 if (getLexer().is(AsmToken::Comma)) {
4050 Lex();
4051
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004052 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00004053 return TokError("Expected an identifier");
4054
4055 if (Name == ".eh_frame")
4056 EH = true;
4057 else if (Name == ".debug_frame")
4058 Debug = true;
4059 }
4060
4061 getStreamer().EmitCFISections(EH, Debug);
4062 return false;
4063}
4064
Jim Grosbach4b905842013-09-20 23:08:21 +00004065/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00004066/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00004067bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00004068 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004069 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
4070 if (check(parseIdentifier(Simple) || Simple != "simple",
4071 "unexpected token") ||
4072 parseToken(AsmToken::EndOfStatement))
4073 return addErrorSuffix(" in '.cfi_startproc' directive");
4074 }
Wouter van Oortmerssencc75e772018-11-12 20:15:01 +00004075
Kristina Brooks1a41a112018-10-19 12:14:30 +00004076 // TODO(kristina): Deal with a corner case of incorrect diagnostic context
4077 // being produced if this directive is emitted as part of preprocessor macro
4078 // expansion which can *ONLY* happen if Clang's cc1as is the API consumer.
4079 // Tools like llvm-mc on the other hand are not affected by it, and report
4080 // correct context information.
4081 getStreamer().EmitCFIStartProc(!Simple.empty(), Lexer.getLoc());
Eli Bendersky17233942013-01-15 22:59:42 +00004082 return false;
4083}
4084
Jim Grosbach4b905842013-09-20 23:08:21 +00004085/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00004086/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00004087bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00004088 getStreamer().EmitCFIEndProc();
4089 return false;
4090}
4091
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004092/// parse register name or number.
Jim Grosbach4b905842013-09-20 23:08:21 +00004093bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00004094 SMLoc DirectiveLoc) {
4095 unsigned RegNo;
4096
4097 if (getLexer().isNot(AsmToken::Integer)) {
4098 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
4099 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00004100 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00004101 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004102 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00004103
4104 return false;
4105}
4106
Jim Grosbach4b905842013-09-20 23:08:21 +00004107/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00004108/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00004109bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004110 int64_t Register = 0, Offset = 0;
4111 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
4112 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4113 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00004114 return true;
4115
4116 getStreamer().EmitCFIDefCfa(Register, Offset);
4117 return false;
4118}
4119
Jim Grosbach4b905842013-09-20 23:08:21 +00004120/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00004121/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00004122bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00004123 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004124 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00004125 return true;
4126
4127 getStreamer().EmitCFIDefCfaOffset(Offset);
4128 return false;
4129}
4130
Jim Grosbach4b905842013-09-20 23:08:21 +00004131/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00004132/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00004133bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004134 int64_t Register1 = 0, Register2 = 0;
4135 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
4136 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4137 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004138 return true;
4139
4140 getStreamer().EmitCFIRegister(Register1, Register2);
4141 return false;
4142}
4143
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00004144/// parseDirectiveCFIWindowSave
4145/// ::= .cfi_window_save
4146bool AsmParser::parseDirectiveCFIWindowSave() {
4147 getStreamer().EmitCFIWindowSave();
4148 return false;
4149}
4150
Jim Grosbach4b905842013-09-20 23:08:21 +00004151/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00004152/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00004153bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00004154 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004155 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00004156 return true;
4157
4158 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
4159 return false;
4160}
4161
Jim Grosbach4b905842013-09-20 23:08:21 +00004162/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00004163/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00004164bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004165 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00004166 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004167 return true;
4168
4169 getStreamer().EmitCFIDefCfaRegister(Register);
4170 return false;
4171}
4172
Jim Grosbach4b905842013-09-20 23:08:21 +00004173/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00004174/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00004175bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004176 int64_t Register = 0;
4177 int64_t Offset = 0;
4178
Nirav Davea645433c2016-07-18 15:24:03 +00004179 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
4180 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4181 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00004182 return true;
4183
4184 getStreamer().EmitCFIOffset(Register, Offset);
4185 return false;
4186}
4187
Jim Grosbach4b905842013-09-20 23:08:21 +00004188/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00004189/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00004190bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004191 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00004192
Nirav Davea645433c2016-07-18 15:24:03 +00004193 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
4194 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4195 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00004196 return true;
4197
4198 getStreamer().EmitCFIRelOffset(Register, Offset);
4199 return false;
4200}
4201
4202static bool isValidEncoding(int64_t Encoding) {
4203 if (Encoding & ~0xff)
4204 return false;
4205
4206 if (Encoding == dwarf::DW_EH_PE_omit)
4207 return true;
4208
4209 const unsigned Format = Encoding & 0xf;
4210 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
4211 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
4212 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
4213 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
4214 return false;
4215
4216 const unsigned Application = Encoding & 0x70;
4217 if (Application != dwarf::DW_EH_PE_absptr &&
4218 Application != dwarf::DW_EH_PE_pcrel)
4219 return false;
4220
4221 return true;
4222}
4223
Jim Grosbach4b905842013-09-20 23:08:21 +00004224/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00004225/// IsPersonality true for cfi_personality, false for cfi_lsda
4226/// ::= .cfi_personality encoding, [symbol_name]
4227/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00004228bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00004229 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004230 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00004231 return true;
4232 if (Encoding == dwarf::DW_EH_PE_omit)
4233 return false;
4234
Eli Bendersky17233942013-01-15 22:59:42 +00004235 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004236 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
4237 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4238 check(parseIdentifier(Name), "expected identifier in directive"))
4239 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004240
Jim Grosbach6f482002015-05-18 18:43:14 +00004241 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004242
4243 if (IsPersonality)
4244 getStreamer().EmitCFIPersonality(Sym, Encoding);
4245 else
4246 getStreamer().EmitCFILsda(Sym, Encoding);
4247 return false;
4248}
4249
Jim Grosbach4b905842013-09-20 23:08:21 +00004250/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00004251/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004252bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004253 getStreamer().EmitCFIRememberState();
4254 return false;
4255}
4256
Jim Grosbach4b905842013-09-20 23:08:21 +00004257/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00004258/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004259bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004260 getStreamer().EmitCFIRestoreState();
4261 return false;
4262}
4263
Jim Grosbach4b905842013-09-20 23:08:21 +00004264/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00004265/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00004266bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004267 int64_t Register = 0;
4268
Jim Grosbach4b905842013-09-20 23:08:21 +00004269 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004270 return true;
4271
4272 getStreamer().EmitCFISameValue(Register);
4273 return false;
4274}
4275
Jim Grosbach4b905842013-09-20 23:08:21 +00004276/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00004277/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00004278bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004279 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00004280 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004281 return true;
4282
4283 getStreamer().EmitCFIRestore(Register);
4284 return false;
4285}
4286
Jim Grosbach4b905842013-09-20 23:08:21 +00004287/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00004288/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004289bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00004290 std::string Values;
4291 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004292 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004293 return true;
4294
4295 Values.push_back((uint8_t)CurrValue);
4296
4297 while (getLexer().is(AsmToken::Comma)) {
4298 Lex();
4299
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004300 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004301 return true;
4302
4303 Values.push_back((uint8_t)CurrValue);
4304 }
4305
4306 getStreamer().EmitCFIEscape(Values);
4307 return false;
4308}
4309
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00004310/// parseDirectiveCFIReturnColumn
4311/// ::= .cfi_return_column register
4312bool AsmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc) {
4313 int64_t Register = 0;
4314 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4315 return true;
4316 getStreamer().EmitCFIReturnColumn(Register);
4317 return false;
4318}
4319
Jim Grosbach4b905842013-09-20 23:08:21 +00004320/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00004321/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00004322bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00004323 if (parseToken(AsmToken::EndOfStatement,
4324 "unexpected token in '.cfi_signal_frame'"))
4325 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004326
4327 getStreamer().EmitCFISignalFrame();
4328 return false;
4329}
4330
Jim Grosbach4b905842013-09-20 23:08:21 +00004331/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00004332/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00004333bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004334 int64_t Register = 0;
4335
Jim Grosbach4b905842013-09-20 23:08:21 +00004336 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004337 return true;
4338
4339 getStreamer().EmitCFIUndefined(Register);
4340 return false;
4341}
4342
Michael Zuckerman56704612017-05-01 13:20:12 +00004343/// parseDirectiveAltmacro
4344/// ::= .altmacro
4345/// ::= .noaltmacro
4346bool AsmParser::parseDirectiveAltmacro(StringRef Directive) {
4347 if (getLexer().isNot(AsmToken::EndOfStatement))
4348 return TokError("unexpected token in '" + Directive + "' directive");
Craig Topperc81aff72018-09-25 20:55:55 +00004349 AltMacroMode = (Directive == ".altmacro");
Michael Zuckerman56704612017-05-01 13:20:12 +00004350 return false;
4351}
4352
Jim Grosbach4b905842013-09-20 23:08:21 +00004353/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00004354/// ::= .macros_on
4355/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00004356bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004357 if (parseToken(AsmToken::EndOfStatement,
4358 "unexpected token in '" + Directive + "' directive"))
4359 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004360
Jim Grosbach4b905842013-09-20 23:08:21 +00004361 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00004362 return false;
4363}
4364
Jim Grosbach4b905842013-09-20 23:08:21 +00004365/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004366/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00004367bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004368 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004369 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00004370 return TokError("expected identifier in '.macro' directive");
4371
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004372 if (getLexer().is(AsmToken::Comma))
4373 Lex();
4374
Eli Bendersky17233942013-01-15 22:59:42 +00004375 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00004376 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004377
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00004378 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004379 return Error(Lexer.getLoc(),
4380 "Vararg parameter '" + Parameters.back().Name +
4381 "' should be last one in the list of parameters.");
4382
David Majnemer91fc4c22014-01-29 18:57:46 +00004383 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004384 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00004385 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004386
Coby Tayreebedaae02017-04-08 20:29:03 +00004387 // Emit an error if two (or more) named parameters share the same name
4388 for (const MCAsmMacroParameter& CurrParam : Parameters)
4389 if (CurrParam.Name.equals(Parameter.Name))
4390 return TokError("macro '" + Name + "' has multiple parameters"
4391 " named '" + Parameter.Name + "'");
4392
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004393 if (Lexer.is(AsmToken::Colon)) {
4394 Lex(); // consume ':'
4395
4396 SMLoc QualLoc;
4397 StringRef Qualifier;
4398
4399 QualLoc = Lexer.getLoc();
4400 if (parseIdentifier(Qualifier))
4401 return Error(QualLoc, "missing parameter qualifier for "
4402 "'" + Parameter.Name + "' in macro '" + Name + "'");
4403
4404 if (Qualifier == "req")
4405 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00004406 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004407 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004408 else
4409 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
4410 "for '" + Parameter.Name + "' in macro '" + Name + "'");
4411 }
4412
David Majnemer91fc4c22014-01-29 18:57:46 +00004413 if (getLexer().is(AsmToken::Equal)) {
4414 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004415
4416 SMLoc ParamLoc;
4417
4418 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004419 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00004420 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004421
4422 if (Parameter.Required)
4423 Warning(ParamLoc, "pointless default value for required parameter "
4424 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00004425 }
David Majnemer91fc4c22014-01-29 18:57:46 +00004426
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00004427 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00004428
4429 if (getLexer().is(AsmToken::Comma))
4430 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004431 }
4432
Nirav Dave1180e6892016-06-02 17:15:05 +00004433 // Eat just the end of statement.
4434 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004435
Nirav Dave1180e6892016-06-02 17:15:05 +00004436 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00004437 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004438 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00004439 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004440 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00004441 // Ignore Lexing errors in macros.
4442 while (Lexer.is(AsmToken::Error)) {
4443 Lexer.Lex();
4444 }
4445
Eli Bendersky17233942013-01-15 22:59:42 +00004446 // Check whether we have reached the end of the file.
4447 if (getLexer().is(AsmToken::Eof))
4448 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
4449
4450 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004451 if (getLexer().is(AsmToken::Identifier)) {
4452 if (getTok().getIdentifier() == ".endm" ||
4453 getTok().getIdentifier() == ".endmacro") {
4454 if (MacroDepth == 0) { // Outermost macro.
4455 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00004456 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004457 if (getLexer().isNot(AsmToken::EndOfStatement))
4458 return TokError("unexpected token in '" + EndToken.getIdentifier() +
4459 "' directive");
4460 break;
4461 } else {
4462 // Otherwise we just found the end of an inner macro.
4463 --MacroDepth;
4464 }
4465 } else if (getTok().getIdentifier() == ".macro") {
4466 // We allow nested macros. Those aren't instantiated until the outermost
4467 // macro is expanded so just ignore them for now.
4468 ++MacroDepth;
4469 }
Eli Bendersky17233942013-01-15 22:59:42 +00004470 }
4471
4472 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004473 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00004474 }
4475
Rafael Espindola22c38a02018-02-14 16:34:27 +00004476 if (getContext().lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00004477 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
4478 }
4479
4480 const char *BodyStart = StartToken.getLoc().getPointer();
4481 const char *BodyEnd = EndToken.getLoc().getPointer();
4482 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00004483 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Oliver Stannardc3e7c6d2018-03-06 15:32:34 +00004484 MCAsmMacro Macro(Name, Body, std::move(Parameters));
4485 DEBUG_WITH_TYPE("asm-macros", dbgs() << "Defining new macro:\n";
4486 Macro.dump());
4487 getContext().defineMacro(Name, std::move(Macro));
Eli Bendersky17233942013-01-15 22:59:42 +00004488 return false;
4489}
4490
Jim Grosbach4b905842013-09-20 23:08:21 +00004491/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00004492///
4493/// With the support added for named parameters there may be code out there that
4494/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00004495/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00004496/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00004497/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00004498/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4499/// warning that the positional parameter found in body which have no effect.
4500/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00004501/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00004502/// intended or change the macro to use the named parameters. It is possible
4503/// this warning will trigger when the none of the named parameters are used
4504/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00004505void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00004506 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004507 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00004508 // If this macro is not defined with named parameters the warning we are
4509 // checking for here doesn't apply.
4510 unsigned NParameters = Parameters.size();
4511 if (NParameters == 0)
4512 return;
4513
4514 bool NamedParametersFound = false;
4515 bool PositionalParametersFound = false;
4516
4517 // Look at the body of the macro for use of both the named parameters and what
4518 // are likely to be positional parameters. This is what expandMacro() is
4519 // doing when it finds the parameters in the body.
4520 while (!Body.empty()) {
4521 // Scan for the next possible parameter.
4522 std::size_t End = Body.size(), Pos = 0;
4523 for (; Pos != End; ++Pos) {
4524 // Check for a substitution or escape.
4525 // This macro is defined with parameters, look for \foo, \bar, etc.
4526 if (Body[Pos] == '\\' && Pos + 1 != End)
4527 break;
4528
4529 // This macro should have parameters, but look for $0, $1, ..., $n too.
4530 if (Body[Pos] != '$' || Pos + 1 == End)
4531 continue;
4532 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004533 if (Next == '$' || Next == 'n' ||
4534 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004535 break;
4536 }
4537
4538 // Check if we reached the end.
4539 if (Pos == End)
4540 break;
4541
4542 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004543 switch (Body[Pos + 1]) {
4544 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004545 case '$':
4546 break;
4547
Jim Grosbach4b905842013-09-20 23:08:21 +00004548 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004549 case 'n':
4550 PositionalParametersFound = true;
4551 break;
4552
Jim Grosbach4b905842013-09-20 23:08:21 +00004553 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004554 default: {
4555 PositionalParametersFound = true;
4556 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004557 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004558 }
4559 Pos += 2;
4560 } else {
4561 unsigned I = Pos + 1;
4562 while (isIdentifierChar(Body[I]) && I + 1 != End)
4563 ++I;
4564
Jim Grosbach4b905842013-09-20 23:08:21 +00004565 const char *Begin = Body.data() + Pos + 1;
4566 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004567 unsigned Index = 0;
4568 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004569 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004570 break;
4571
4572 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004573 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4574 Pos += 3;
4575 else {
4576 Pos = I;
4577 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004578 } else {
4579 NamedParametersFound = true;
4580 Pos += 1 + Argument.size();
4581 }
4582 }
4583 // Update the scan point.
4584 Body = Body.substr(Pos);
4585 }
4586
4587 if (!NamedParametersFound && PositionalParametersFound)
4588 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4589 "used in macro body, possible positional parameter "
4590 "found in body which will have no effect");
4591}
4592
Nico Weber155dccd12014-07-24 17:08:39 +00004593/// parseDirectiveExitMacro
4594/// ::= .exitm
4595bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004596 if (parseToken(AsmToken::EndOfStatement,
4597 "unexpected token in '" + Directive + "' directive"))
4598 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004599
4600 if (!isInsideMacroInstantiation())
4601 return TokError("unexpected '" + Directive + "' in file, "
4602 "no current macro definition");
4603
4604 // Exit all conditionals that are active in the current macro.
4605 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4606 TheCondState = TheCondStack.back();
4607 TheCondStack.pop_back();
4608 }
4609
4610 handleMacroExit();
4611 return false;
4612}
4613
Jim Grosbach4b905842013-09-20 23:08:21 +00004614/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004615/// ::= .endm
4616/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004617bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004618 if (getLexer().isNot(AsmToken::EndOfStatement))
4619 return TokError("unexpected token in '" + Directive + "' directive");
4620
4621 // If we are inside a macro instantiation, terminate the current
4622 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004623 if (isInsideMacroInstantiation()) {
4624 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004625 return false;
4626 }
4627
4628 // Otherwise, this .endmacro is a stray entry in the file; well formed
4629 // .endmacro directives are handled during the macro definition parsing.
4630 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004631 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004632}
4633
Jim Grosbach4b905842013-09-20 23:08:21 +00004634/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004635/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004636bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004637 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004638 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004639 if (parseTokenLoc(Loc) ||
4640 check(parseIdentifier(Name), Loc,
4641 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004642 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004643 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004644 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004645
Rafael Espindola22c38a02018-02-14 16:34:27 +00004646 if (!getContext().lookupMacro(Name))
Nirav Dave1ab71992016-07-18 19:35:21 +00004647 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4648
Rafael Espindola22c38a02018-02-14 16:34:27 +00004649 getContext().undefineMacro(Name);
Oliver Stannardc3e7c6d2018-03-06 15:32:34 +00004650 DEBUG_WITH_TYPE("asm-macros", dbgs()
4651 << "Un-defining macro: " << Name << "\n");
Eli Bendersky17233942013-01-15 22:59:42 +00004652 return false;
4653}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004654
Jim Grosbach4b905842013-09-20 23:08:21 +00004655/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004656/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004657bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004658 // Expect a single argument: an expression that evaluates to a constant
4659 // in the inclusive range 0-30.
4660 SMLoc ExprLoc = getLexer().getLoc();
4661 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004662 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004663 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4664 "in '.bundle_align_mode' "
4665 "directive") ||
4666 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4667 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004668 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004669
4670 // Because of AlignSizePow2's verified range we can safely truncate it to
4671 // unsigned.
4672 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4673 return false;
4674}
4675
Jim Grosbach4b905842013-09-20 23:08:21 +00004676/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004677/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004678bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004679 if (checkForValidSection())
4680 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004681 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004682
Nirav Dave1a9044b2016-10-24 14:35:29 +00004683 StringRef Option;
4684 SMLoc Loc = getTok().getLoc();
4685 const char *kInvalidOptionError =
4686 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004687
Nirav Dave1a9044b2016-10-24 14:35:29 +00004688 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004689 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4690 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004691 parseToken(AsmToken::EndOfStatement,
4692 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004693 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004694 AlignToEnd = true;
4695 }
4696
Eli Bendersky802b6282013-01-07 21:51:08 +00004697 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004698 return false;
4699}
4700
Jim Grosbach4b905842013-09-20 23:08:21 +00004701/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004702/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004703bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004704 if (checkForValidSection() ||
4705 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004706 "unexpected token in '.bundle_unlock' directive"))
4707 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004708
4709 getStreamer().EmitBundleUnlock();
4710 return false;
4711}
4712
Jim Grosbach4b905842013-09-20 23:08:21 +00004713/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004714/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004715bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Petr Hosek67a94a72016-05-28 05:57:48 +00004716 SMLoc NumBytesLoc = Lexer.getLoc();
4717 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004718 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004719 return true;
4720
4721 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004722 if (parseOptionalToken(AsmToken::Comma))
4723 if (parseAbsoluteExpression(FillExpr))
4724 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4725 if (parseToken(AsmToken::EndOfStatement))
4726 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004727
Eli Bendersky17233942013-01-15 22:59:42 +00004728 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004729 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004730
4731 return false;
4732}
4733
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004734/// parseDirectiveDCB
4735/// ::= .dcb.{b, l, w} expression, expression
4736bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004737 SMLoc NumValuesLoc = Lexer.getLoc();
4738 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004739 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004740 return true;
4741
4742 if (NumValues < 0) {
4743 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4744 return false;
4745 }
4746
4747 if (parseToken(AsmToken::Comma,
4748 "unexpected token in '" + Twine(IDVal) + "' directive"))
4749 return true;
4750
4751 const MCExpr *Value;
4752 SMLoc ExprLoc = getLexer().getLoc();
4753 if (parseExpression(Value))
4754 return true;
4755
4756 // Special case constant expressions to match code generator.
4757 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4758 assert(Size <= 8 && "Invalid size");
4759 uint64_t IntValue = MCE->getValue();
4760 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4761 return Error(ExprLoc, "literal value out of range for directive");
4762 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4763 getStreamer().EmitIntValue(IntValue, Size);
4764 } else {
4765 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4766 getStreamer().EmitValue(Value, Size, ExprLoc);
4767 }
4768
4769 if (parseToken(AsmToken::EndOfStatement,
4770 "unexpected token in '" + Twine(IDVal) + "' directive"))
4771 return true;
4772
4773 return false;
4774}
4775
4776/// parseDirectiveRealDCB
4777/// ::= .dcb.{d, s} expression, expression
4778bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004779 SMLoc NumValuesLoc = Lexer.getLoc();
4780 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004781 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004782 return true;
4783
4784 if (NumValues < 0) {
4785 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4786 return false;
4787 }
4788
4789 if (parseToken(AsmToken::Comma,
4790 "unexpected token in '" + Twine(IDVal) + "' directive"))
4791 return true;
4792
4793 APInt AsInt;
4794 if (parseRealValue(Semantics, AsInt))
4795 return true;
4796
4797 if (parseToken(AsmToken::EndOfStatement,
4798 "unexpected token in '" + Twine(IDVal) + "' directive"))
4799 return true;
4800
4801 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4802 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4803 AsInt.getBitWidth() / 8);
4804
4805 return false;
4806}
4807
Petr Hosek85b2f672016-09-23 21:53:36 +00004808/// parseDirectiveDS
4809/// ::= .ds.{b, d, l, p, s, w, x} expression
4810bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004811 SMLoc NumValuesLoc = Lexer.getLoc();
4812 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004813 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004814 return true;
4815
4816 if (NumValues < 0) {
4817 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4818 return false;
4819 }
4820
4821 if (parseToken(AsmToken::EndOfStatement,
4822 "unexpected token in '" + Twine(IDVal) + "' directive"))
4823 return true;
4824
4825 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4826 getStreamer().emitFill(Size, 0);
4827
4828 return false;
4829}
4830
Jim Grosbach4b905842013-09-20 23:08:21 +00004831/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004832/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004833bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004834 if (checkForValidSection())
4835 return true;
4836
Nirav Dave1a9044b2016-10-24 14:35:29 +00004837 auto parseOp = [&]() -> bool {
4838 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004839 if (parseExpression(Value))
4840 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004841 if (Signed)
4842 getStreamer().EmitSLEB128Value(Value);
4843 else
4844 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004845 return false;
4846 };
Eli Bendersky17233942013-01-15 22:59:42 +00004847
Nirav Dave1a9044b2016-10-24 14:35:29 +00004848 if (parseMany(parseOp))
4849 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004850
4851 return false;
4852}
4853
Jim Grosbach4b905842013-09-20 23:08:21 +00004854/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004855/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004856bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004857 auto parseOp = [&]() -> bool {
4858 StringRef Name;
4859 SMLoc Loc = getTok().getLoc();
4860 if (parseIdentifier(Name))
4861 return Error(Loc, "expected identifier");
4862 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004863
Nirav Dave1a9044b2016-10-24 14:35:29 +00004864 // Assembler local symbols don't make any sense here. Complain loudly.
4865 if (Sym->isTemporary())
4866 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004867
Nirav Dave1a9044b2016-10-24 14:35:29 +00004868 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4869 return Error(Loc, "unable to emit symbol attribute");
4870 return false;
4871 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004872
Nirav Dave1a9044b2016-10-24 14:35:29 +00004873 if (parseMany(parseOp))
4874 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004875 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004876}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004877
Jim Grosbach4b905842013-09-20 23:08:21 +00004878/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004879/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004880bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004881 if (checkForValidSection())
4882 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004883
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004884 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004885 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004886 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004887 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004888
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004889 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004890 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004891
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004892 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004893 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004894 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004895
4896 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004897 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004898 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004899 return true;
4900
4901 int64_t Pow2Alignment = 0;
4902 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004903 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004904 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004905 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004906 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004907 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004908
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004909 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4910 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004911 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4912
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004913 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004914 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4915 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004916 if (!isPowerOf2_64(Pow2Alignment))
4917 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4918 Pow2Alignment = Log2_64(Pow2Alignment);
4919 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004920 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004921
Nirav Dave1a9044b2016-10-24 14:35:29 +00004922 if (parseToken(AsmToken::EndOfStatement,
4923 "unexpected token in '.comm' or '.lcomm' directive"))
4924 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004925
Chris Lattner28ad7542009-07-09 17:25:12 +00004926 // NOTE: a size of zero for a .comm should create a undefined symbol
4927 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004928 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004929 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004930 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004931
Eric Christopherbc818852010-05-14 01:38:54 +00004932 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004933 // may internally end up wanting an alignment in bytes.
4934 // FIXME: Diagnose overflow.
4935 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004936 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004937 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004938
Rafael Espindola13a79bb2017-02-02 21:26:06 +00004939 Sym->redefineIfPossible();
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004940 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004941 return Error(IDLoc, "invalid symbol redefinition");
4942
Chris Lattner28ad7542009-07-09 17:25:12 +00004943 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004944 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004945 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004946 return false;
4947 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004948
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004949 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004950 return false;
4951}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004952
Jim Grosbach4b905842013-09-20 23:08:21 +00004953/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004954/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004955bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004956 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004957 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004958
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004959 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004960 if (parseToken(AsmToken::EndOfStatement,
4961 "unexpected token in '.abort' directive"))
4962 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004963
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004964 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004965 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004966 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004967 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004968 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004969
4970 return false;
4971}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004972
Jim Grosbach4b905842013-09-20 23:08:21 +00004973/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004974/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004975bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004976 // Allow the strings to have escaped octal character sequence.
4977 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004978 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004979
Nirav Davea645433c2016-07-18 15:24:03 +00004980 if (check(getTok().isNot(AsmToken::String),
4981 "expected string in '.include' directive") ||
4982 parseEscapedString(Filename) ||
4983 check(getTok().isNot(AsmToken::EndOfStatement),
4984 "unexpected token in '.include' directive") ||
4985 // Attempt to switch the lexer to the included file before consuming the
4986 // end of statement to avoid losing it when we switch.
4987 check(enterIncludeFile(Filename), IncludeLoc,
4988 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004989 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004990
4991 return false;
4992}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004993
Jim Grosbach4b905842013-09-20 23:08:21 +00004994/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004995/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004996bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004997 // Allow the strings to have escaped octal character sequence.
4998 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004999 SMLoc IncbinLoc = getTok().getLoc();
5000 if (check(getTok().isNot(AsmToken::String),
5001 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00005002 parseEscapedString(Filename))
5003 return true;
5004
5005 int64_t Skip = 0;
5006 const MCExpr *Count = nullptr;
5007 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00005008 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00005009 // The skip expression can be omitted while specifying the count, e.g:
5010 // .incbin "filename",,4
5011 if (getTok().isNot(AsmToken::Comma)) {
5012 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
5013 return true;
5014 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00005015 if (parseOptionalToken(AsmToken::Comma)) {
5016 CountLoc = getTok().getLoc();
5017 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00005018 return true;
5019 }
5020 }
5021
5022 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00005023 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00005024 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00005025
Petr Hosek2f4ac442016-09-23 00:41:06 +00005026 if (check(Skip < 0, SkipLoc, "skip is negative"))
5027 return true;
5028
Nirav Dave1ab71992016-07-18 19:35:21 +00005029 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00005030 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00005031 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00005032 return false;
5033}
5034
Jim Grosbach4b905842013-09-20 23:08:21 +00005035/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00005036/// ::= .if{,eq,ge,gt,le,lt,ne} expression
5037bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005038 TheCondStack.push_back(TheCondState);
5039 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00005040 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005041 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00005042 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005043 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00005044 if (parseAbsoluteExpression(ExprValue) ||
5045 parseToken(AsmToken::EndOfStatement,
5046 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005047 return true;
5048
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00005049 switch (DirKind) {
5050 default:
5051 llvm_unreachable("unsupported directive");
5052 case DK_IF:
5053 case DK_IFNE:
5054 break;
5055 case DK_IFEQ:
5056 ExprValue = ExprValue == 0;
5057 break;
5058 case DK_IFGE:
5059 ExprValue = ExprValue >= 0;
5060 break;
5061 case DK_IFGT:
5062 ExprValue = ExprValue > 0;
5063 break;
5064 case DK_IFLE:
5065 ExprValue = ExprValue <= 0;
5066 break;
5067 case DK_IFLT:
5068 ExprValue = ExprValue < 0;
5069 break;
5070 }
5071
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005072 TheCondState.CondMet = ExprValue;
5073 TheCondState.Ignore = !TheCondState.CondMet;
5074 }
5075
5076 return false;
5077}
5078
Jim Grosbach4b905842013-09-20 23:08:21 +00005079/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00005080/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00005081bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00005082 TheCondStack.push_back(TheCondState);
5083 TheCondState.TheCond = AsmCond::IfCond;
5084
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00005085 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005086 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00005087 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005088 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00005089
Nirav Davea645433c2016-07-18 15:24:03 +00005090 if (parseToken(AsmToken::EndOfStatement,
5091 "unexpected token in '.ifb' directive"))
5092 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00005093
5094 TheCondState.CondMet = ExpectBlank == Str.empty();
5095 TheCondState.Ignore = !TheCondState.CondMet;
5096 }
5097
5098 return false;
5099}
5100
Jim Grosbach4b905842013-09-20 23:08:21 +00005101/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00005102/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00005103/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00005104bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00005105 TheCondStack.push_back(TheCondState);
5106 TheCondState.TheCond = AsmCond::IfCond;
5107
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00005108 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005109 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00005110 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00005111 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00005112
Nirav Davea645433c2016-07-18 15:24:03 +00005113 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
5114 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00005115
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005116 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00005117
Nirav Davea645433c2016-07-18 15:24:03 +00005118 if (parseToken(AsmToken::EndOfStatement,
5119 "unexpected token in '.ifc' directive"))
5120 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00005121
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00005122 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00005123 TheCondState.Ignore = !TheCondState.CondMet;
5124 }
5125
5126 return false;
5127}
5128
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005129/// parseDirectiveIfeqs
5130/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00005131bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005132 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00005133 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00005134 return TokError("expected string parameter for '.ifeqs' directive");
5135 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005136 }
5137
5138 StringRef String1 = getTok().getStringContents();
5139 Lex();
5140
5141 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00005142 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00005143 return TokError(
5144 "expected comma after first string for '.ifeqs' directive");
5145 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005146 }
5147
5148 Lex();
5149
5150 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00005151 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00005152 return TokError("expected string parameter for '.ifeqs' directive");
5153 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005154 }
5155
5156 StringRef String2 = getTok().getStringContents();
5157 Lex();
5158
5159 TheCondStack.push_back(TheCondState);
5160 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00005161 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005162 TheCondState.Ignore = !TheCondState.CondMet;
5163
5164 return false;
5165}
5166
Jim Grosbach4b905842013-09-20 23:08:21 +00005167/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00005168/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00005169bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005170 StringRef Name;
5171 TheCondStack.push_back(TheCondState);
5172 TheCondState.TheCond = AsmCond::IfCond;
5173
5174 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005175 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005176 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00005177 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
5178 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
5179 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005180
Jim Grosbach6f482002015-05-18 18:43:14 +00005181 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005182
5183 if (expect_defined)
Scott Linderb5d62922019-01-28 19:32:08 +00005184 TheCondState.CondMet = (Sym && !Sym->isUndefined(false));
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005185 else
Scott Linderb5d62922019-01-28 19:32:08 +00005186 TheCondState.CondMet = (!Sym || Sym->isUndefined(false));
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005187 TheCondState.Ignore = !TheCondState.CondMet;
5188 }
5189
5190 return false;
5191}
5192
Jim Grosbach4b905842013-09-20 23:08:21 +00005193/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005194/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00005195bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005196 if (TheCondState.TheCond != AsmCond::IfCond &&
5197 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00005198 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
5199 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005200 TheCondState.TheCond = AsmCond::ElseIfCond;
5201
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005202 bool LastIgnoreState = false;
5203 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00005204 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005205 if (LastIgnoreState || TheCondState.CondMet) {
5206 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005207 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00005208 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005209 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005210 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005211 return true;
5212
Nirav Dave1a9044b2016-10-24 14:35:29 +00005213 if (parseToken(AsmToken::EndOfStatement,
5214 "unexpected token in '.elseif' directive"))
5215 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00005216
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005217 TheCondState.CondMet = ExprValue;
5218 TheCondState.Ignore = !TheCondState.CondMet;
5219 }
5220
5221 return false;
5222}
5223
Jim Grosbach4b905842013-09-20 23:08:21 +00005224/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005225/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00005226bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005227 if (parseToken(AsmToken::EndOfStatement,
5228 "unexpected token in '.else' directive"))
5229 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005230
5231 if (TheCondState.TheCond != AsmCond::IfCond &&
5232 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00005233 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
5234 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005235 TheCondState.TheCond = AsmCond::ElseCond;
5236 bool LastIgnoreState = false;
5237 if (!TheCondStack.empty())
5238 LastIgnoreState = TheCondStack.back().Ignore;
5239 if (LastIgnoreState || TheCondState.CondMet)
5240 TheCondState.Ignore = true;
5241 else
5242 TheCondState.Ignore = false;
5243
5244 return false;
5245}
5246
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005247/// parseDirectiveEnd
5248/// ::= .end
5249bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005250 if (parseToken(AsmToken::EndOfStatement,
5251 "unexpected token in '.end' directive"))
5252 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005253
5254 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00005255 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005256
5257 return false;
5258}
5259
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005260/// parseDirectiveError
5261/// ::= .err
5262/// ::= .error [string]
5263bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
5264 if (!TheCondStack.empty()) {
5265 if (TheCondStack.back().Ignore) {
5266 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005267 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005268 }
5269 }
5270
5271 if (!WithMessage)
5272 return Error(L, ".err encountered");
5273
5274 StringRef Message = ".error directive invoked in source file";
5275 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005276 if (Lexer.isNot(AsmToken::String))
5277 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005278
5279 Message = getTok().getStringContents();
5280 Lex();
5281 }
5282
Nirav Dave2364748a2016-09-16 18:30:20 +00005283 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005284}
5285
Nico Weber404012b2014-07-24 16:26:06 +00005286/// parseDirectiveWarning
5287/// ::= .warning [string]
5288bool AsmParser::parseDirectiveWarning(SMLoc L) {
5289 if (!TheCondStack.empty()) {
5290 if (TheCondStack.back().Ignore) {
5291 eatToEndOfStatement();
5292 return false;
5293 }
5294 }
5295
5296 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00005297
5298 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005299 if (Lexer.isNot(AsmToken::String))
5300 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00005301
5302 Message = getTok().getStringContents();
5303 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00005304 if (parseToken(AsmToken::EndOfStatement,
5305 "expected end of statement in '.warning' directive"))
5306 return true;
Nico Weber404012b2014-07-24 16:26:06 +00005307 }
5308
Nirav Dave2364748a2016-09-16 18:30:20 +00005309 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00005310}
5311
Jim Grosbach4b905842013-09-20 23:08:21 +00005312/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005313/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00005314bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005315 if (parseToken(AsmToken::EndOfStatement,
5316 "unexpected token in '.endif' directive"))
5317 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005318
Jim Grosbach4b905842013-09-20 23:08:21 +00005319 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00005320 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
5321 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005322 if (!TheCondStack.empty()) {
5323 TheCondState = TheCondStack.back();
5324 TheCondStack.pop_back();
5325 }
5326
5327 return false;
5328}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00005329
Eli Bendersky17233942013-01-15 22:59:42 +00005330void AsmParser::initializeDirectiveKindMap() {
5331 DirectiveKindMap[".set"] = DK_SET;
5332 DirectiveKindMap[".equ"] = DK_EQU;
5333 DirectiveKindMap[".equiv"] = DK_EQUIV;
5334 DirectiveKindMap[".ascii"] = DK_ASCII;
5335 DirectiveKindMap[".asciz"] = DK_ASCIZ;
5336 DirectiveKindMap[".string"] = DK_STRING;
5337 DirectiveKindMap[".byte"] = DK_BYTE;
5338 DirectiveKindMap[".short"] = DK_SHORT;
5339 DirectiveKindMap[".value"] = DK_VALUE;
5340 DirectiveKindMap[".2byte"] = DK_2BYTE;
5341 DirectiveKindMap[".long"] = DK_LONG;
5342 DirectiveKindMap[".int"] = DK_INT;
5343 DirectiveKindMap[".4byte"] = DK_4BYTE;
5344 DirectiveKindMap[".quad"] = DK_QUAD;
5345 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00005346 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00005347 DirectiveKindMap[".single"] = DK_SINGLE;
5348 DirectiveKindMap[".float"] = DK_FLOAT;
5349 DirectiveKindMap[".double"] = DK_DOUBLE;
5350 DirectiveKindMap[".align"] = DK_ALIGN;
5351 DirectiveKindMap[".align32"] = DK_ALIGN32;
5352 DirectiveKindMap[".balign"] = DK_BALIGN;
5353 DirectiveKindMap[".balignw"] = DK_BALIGNW;
5354 DirectiveKindMap[".balignl"] = DK_BALIGNL;
5355 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
5356 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
5357 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
5358 DirectiveKindMap[".org"] = DK_ORG;
5359 DirectiveKindMap[".fill"] = DK_FILL;
5360 DirectiveKindMap[".zero"] = DK_ZERO;
5361 DirectiveKindMap[".extern"] = DK_EXTERN;
5362 DirectiveKindMap[".globl"] = DK_GLOBL;
5363 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00005364 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
5365 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
5366 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
5367 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
5368 DirectiveKindMap[".reference"] = DK_REFERENCE;
5369 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
5370 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
5371 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
Vedant Kumar13ef84f2019-01-25 18:30:22 +00005372 DirectiveKindMap[".cold"] = DK_COLD;
Eli Bendersky17233942013-01-15 22:59:42 +00005373 DirectiveKindMap[".comm"] = DK_COMM;
5374 DirectiveKindMap[".common"] = DK_COMMON;
5375 DirectiveKindMap[".lcomm"] = DK_LCOMM;
5376 DirectiveKindMap[".abort"] = DK_ABORT;
5377 DirectiveKindMap[".include"] = DK_INCLUDE;
5378 DirectiveKindMap[".incbin"] = DK_INCBIN;
5379 DirectiveKindMap[".code16"] = DK_CODE16;
5380 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
5381 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005382 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00005383 DirectiveKindMap[".irp"] = DK_IRP;
5384 DirectiveKindMap[".irpc"] = DK_IRPC;
5385 DirectiveKindMap[".endr"] = DK_ENDR;
5386 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
5387 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
5388 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
5389 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00005390 DirectiveKindMap[".ifeq"] = DK_IFEQ;
5391 DirectiveKindMap[".ifge"] = DK_IFGE;
5392 DirectiveKindMap[".ifgt"] = DK_IFGT;
5393 DirectiveKindMap[".ifle"] = DK_IFLE;
5394 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00005395 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00005396 DirectiveKindMap[".ifb"] = DK_IFB;
5397 DirectiveKindMap[".ifnb"] = DK_IFNB;
5398 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005399 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00005400 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00005401 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00005402 DirectiveKindMap[".ifdef"] = DK_IFDEF;
5403 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
5404 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
5405 DirectiveKindMap[".elseif"] = DK_ELSEIF;
5406 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005407 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00005408 DirectiveKindMap[".endif"] = DK_ENDIF;
5409 DirectiveKindMap[".skip"] = DK_SKIP;
5410 DirectiveKindMap[".space"] = DK_SPACE;
5411 DirectiveKindMap[".file"] = DK_FILE;
5412 DirectiveKindMap[".line"] = DK_LINE;
5413 DirectiveKindMap[".loc"] = DK_LOC;
5414 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005415 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005416 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005417 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
5418 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00005419 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005420 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00005421 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner06d02d02018-09-07 21:30:52 +00005422 DirectiveKindMap[".cv_string"] = DK_CV_STRING;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005423 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
5424 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00005425 DirectiveKindMap[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET;
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00005426 DirectiveKindMap[".cv_fpo_data"] = DK_CV_FPO_DATA;
Eli Bendersky17233942013-01-15 22:59:42 +00005427 DirectiveKindMap[".sleb128"] = DK_SLEB128;
5428 DirectiveKindMap[".uleb128"] = DK_ULEB128;
5429 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
5430 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
5431 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
5432 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
5433 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
5434 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
5435 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
5436 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
5437 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
5438 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
5439 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
5440 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
5441 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
5442 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
5443 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
5444 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00005445 DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN;
Eli Bendersky17233942013-01-15 22:59:42 +00005446 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
5447 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
5448 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00005449 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Luke Cheeseman41a9e532018-12-21 10:45:08 +00005450 DirectiveKindMap[".cfi_b_key_frame"] = DK_CFI_B_KEY_FRAME;
Eli Bendersky17233942013-01-15 22:59:42 +00005451 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
5452 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
5453 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00005454 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00005455 DirectiveKindMap[".endm"] = DK_ENDM;
5456 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
5457 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005458 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005459 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00005460 DirectiveKindMap[".warning"] = DK_WARNING;
Michael Zuckerman56704612017-05-01 13:20:12 +00005461 DirectiveKindMap[".altmacro"] = DK_ALTMACRO;
5462 DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00005463 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00005464 DirectiveKindMap[".dc"] = DK_DC;
5465 DirectiveKindMap[".dc.a"] = DK_DC_A;
5466 DirectiveKindMap[".dc.b"] = DK_DC_B;
5467 DirectiveKindMap[".dc.d"] = DK_DC_D;
5468 DirectiveKindMap[".dc.l"] = DK_DC_L;
5469 DirectiveKindMap[".dc.s"] = DK_DC_S;
5470 DirectiveKindMap[".dc.w"] = DK_DC_W;
5471 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00005472 DirectiveKindMap[".dcb"] = DK_DCB;
5473 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
5474 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
5475 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
5476 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
5477 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
5478 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00005479 DirectiveKindMap[".ds"] = DK_DS;
5480 DirectiveKindMap[".ds.b"] = DK_DS_B;
5481 DirectiveKindMap[".ds.d"] = DK_DS_D;
5482 DirectiveKindMap[".ds.l"] = DK_DS_L;
5483 DirectiveKindMap[".ds.p"] = DK_DS_P;
5484 DirectiveKindMap[".ds.s"] = DK_DS_S;
5485 DirectiveKindMap[".ds.w"] = DK_DS_W;
5486 DirectiveKindMap[".ds.x"] = DK_DS_X;
Coby Tayree01e53202017-10-02 14:36:31 +00005487 DirectiveKindMap[".print"] = DK_PRINT;
Peter Collingbourne3e227332018-07-17 22:17:18 +00005488 DirectiveKindMap[".addrsig"] = DK_ADDRSIG;
5489 DirectiveKindMap[".addrsig_sym"] = DK_ADDRSIG_SYM;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00005490}
5491
Jim Grosbach4b905842013-09-20 23:08:21 +00005492MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005493 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005494
Rafael Espindola34b9c512012-06-03 23:57:14 +00005495 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005496 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005497 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00005498 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005499 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00005500 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005501 }
5502
Rafael Espindola34b9c512012-06-03 23:57:14 +00005503 if (Lexer.is(AsmToken::Identifier) &&
Nirav Davee24fcd52018-07-18 16:17:03 +00005504 (getTok().getIdentifier() == ".rep" ||
5505 getTok().getIdentifier() == ".rept" ||
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00005506 getTok().getIdentifier() == ".irp" ||
5507 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005508 ++NestLevel;
5509 }
5510
5511 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00005512 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005513 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005514 EndToken = getTok();
5515 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005516 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005517 printError(getTok().getLoc(),
5518 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00005519 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005520 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005521 break;
5522 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005523 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005524 }
5525
Rafael Espindola34b9c512012-06-03 23:57:14 +00005526 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005527 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005528 }
5529
5530 const char *BodyStart = StartToken.getLoc().getPointer();
5531 const char *BodyEnd = EndToken.getLoc().getPointer();
5532 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5533
Rafael Espindola34b9c512012-06-03 23:57:14 +00005534 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005535 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00005536 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005537}
5538
Jim Grosbach4b905842013-09-20 23:08:21 +00005539void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005540 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005541 OS << ".endr\n";
5542
Rafael Espindola3560ff22014-08-27 20:03:13 +00005543 std::unique_ptr<MemoryBuffer> Instantiation =
5544 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005545
Rafael Espindola34b9c512012-06-03 23:57:14 +00005546 // Create the macro instantiation object and add to the current macro
5547 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005548 MacroInstantiation *MI = new MacroInstantiation(
5549 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005550 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005551
Rafael Espindola34b9c512012-06-03 23:57:14 +00005552 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005553 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005554 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005555 Lex();
5556}
5557
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005558/// parseDirectiveRept
5559/// ::= .rep | .rept count
5560bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005561 const MCExpr *CountExpr;
5562 SMLoc CountLoc = getTok().getLoc();
5563 if (parseExpression(CountExpr))
5564 return true;
5565
Rafael Espindola34b9c512012-06-03 23:57:14 +00005566 int64_t Count;
Nirav Dave6c0665e2018-04-30 19:22:40 +00005567 if (!CountExpr->evaluateAsAbsolute(Count, getStreamer().getAssemblerPtr())) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005568 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5569 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005570
Nirav Davea645433c2016-07-18 15:24:03 +00005571 if (check(Count < 0, CountLoc, "Count is negative") ||
5572 parseToken(AsmToken::EndOfStatement,
5573 "unexpected token in '" + Dir + "' directive"))
5574 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005575
5576 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005577 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005578 if (!M)
5579 return true;
5580
5581 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5582 // to hold the macro body with substitutions.
5583 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005584 raw_svector_ostream OS(Buf);
5585 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005586 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5587 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005588 return true;
5589 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005590 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005591
5592 return false;
5593}
5594
Jim Grosbach4b905842013-09-20 23:08:21 +00005595/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005596/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005597bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005598 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005599 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005600 if (check(parseIdentifier(Parameter.Name),
5601 "expected identifier in '.irp' directive") ||
5602 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5603 parseMacroArguments(nullptr, A) ||
5604 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005605 return true;
5606
Rafael Espindola768b41c2012-06-15 14:02:34 +00005607 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005608 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005609 if (!M)
5610 return true;
5611
5612 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5613 // to hold the macro body with substitutions.
5614 SmallString<256> Buf;
5615 raw_svector_ostream OS(Buf);
5616
Craig Topper84008482015-10-10 05:38:14 +00005617 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005618 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5619 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005620 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005621 return true;
5622 }
5623
Jim Grosbach4b905842013-09-20 23:08:21 +00005624 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005625
5626 return false;
5627}
5628
Jim Grosbach4b905842013-09-20 23:08:21 +00005629/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005630/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005631bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005632 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005633 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005634
5635 if (check(parseIdentifier(Parameter.Name),
5636 "expected identifier in '.irpc' directive") ||
5637 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5638 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005639 return true;
5640
5641 if (A.size() != 1 || A.front().size() != 1)
5642 return TokError("unexpected token in '.irpc' directive");
5643
5644 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005645 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5646 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005647
5648 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005649 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005650 if (!M)
5651 return true;
5652
5653 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5654 // to hold the macro body with substitutions.
5655 SmallString<256> Buf;
5656 raw_svector_ostream OS(Buf);
5657
5658 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005659 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005660 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005661 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005662
Toma Tabacu217116e2015-04-27 10:50:29 +00005663 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5664 // This is undocumented, but GAS seems to support it.
5665 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005666 return true;
5667 }
5668
Jim Grosbach4b905842013-09-20 23:08:21 +00005669 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005670
5671 return false;
5672}
5673
Jim Grosbach4b905842013-09-20 23:08:21 +00005674bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005675 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005676 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005677
5678 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005679 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005680 assert(getLexer().is(AsmToken::EndOfStatement));
5681
Jim Grosbach4b905842013-09-20 23:08:21 +00005682 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005683 return false;
5684}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005685
Jim Grosbach4b905842013-09-20 23:08:21 +00005686bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005687 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005688 const MCExpr *Value;
5689 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005690 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005691 return true;
5692 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5693 if (!MCE)
5694 return Error(ExprLoc, "unexpected expression in _emit");
5695 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005696 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005697 return Error(ExprLoc, "literal value out of range for directive");
5698
Craig Topper7d5b2312015-10-10 05:25:02 +00005699 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005700 return false;
5701}
5702
Jim Grosbach4b905842013-09-20 23:08:21 +00005703bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005704 const MCExpr *Value;
5705 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005706 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005707 return true;
5708 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5709 if (!MCE)
5710 return Error(ExprLoc, "unexpected expression in align");
5711 uint64_t IntValue = MCE->getValue();
5712 if (!isPowerOf2_64(IntValue))
5713 return Error(ExprLoc, "literal value not a power of two greater then zero");
5714
Craig Topper7d5b2312015-10-10 05:25:02 +00005715 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005716 return false;
5717}
5718
Coby Tayree01e53202017-10-02 14:36:31 +00005719bool AsmParser::parseDirectivePrint(SMLoc DirectiveLoc) {
5720 const AsmToken StrTok = getTok();
5721 Lex();
5722 if (StrTok.isNot(AsmToken::String) || StrTok.getString().front() != '"')
5723 return Error(DirectiveLoc, "expected double quoted string after .print");
5724 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5725 return true;
5726 llvm::outs() << StrTok.getStringContents() << '\n';
5727 return false;
5728}
5729
Peter Collingbourne3e227332018-07-17 22:17:18 +00005730bool AsmParser::parseDirectiveAddrsig() {
5731 getStreamer().EmitAddrsig();
5732 return false;
5733}
5734
5735bool AsmParser::parseDirectiveAddrsigSym() {
5736 StringRef Name;
5737 if (check(parseIdentifier(Name),
5738 "expected identifier in '.addrsig_sym' directive"))
5739 return true;
5740 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
5741 getStreamer().EmitAddrsigSym(Sym);
5742 return false;
5743}
5744
Chad Rosierf43fcf52013-02-13 21:27:17 +00005745// We are comparing pointers, but the pointers are relative to a single string.
5746// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005747static int rewritesSort(const AsmRewrite *AsmRewriteA,
5748 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005749 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5750 return -1;
5751 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5752 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005753
Chad Rosierfce4fab2013-04-08 17:43:47 +00005754 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5755 // rewrite to the same location. Make sure the SizeDirective rewrite is
5756 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5757 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005758 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5759 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005760 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005761
Jim Grosbach4b905842013-09-20 23:08:21 +00005762 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5763 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005764 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005765 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005766}
5767
Jim Grosbach4b905842013-09-20 23:08:21 +00005768bool AsmParser::parseMSInlineAsm(
5769 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00005770 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
Jim Grosbach4b905842013-09-20 23:08:21 +00005771 SmallVectorImpl<std::string> &Constraints,
5772 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5773 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005774 SmallVector<void *, 4> InputDecls;
5775 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005776 SmallVector<bool, 4> InputDeclsAddressOf;
5777 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005778 SmallVector<std::string, 4> InputConstraints;
5779 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005780 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005781
Benjamin Kramer1a136112013-02-15 20:37:21 +00005782 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005783
5784 // Prime the lexer.
5785 Lex();
5786
5787 // While we have input, parse each statement.
5788 unsigned InputIdx = 0;
5789 unsigned OutputIdx = 0;
5790 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005791 // Parse curly braces marking block start/end
5792 if (parseCurlyBlockScope(AsmStrRewrites))
5793 continue;
5794
Eli Friedman0f4871d2012-10-22 23:58:19 +00005795 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005796 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005797
Nirav Dave2364748a2016-09-16 18:30:20 +00005798 if (StatementErr || Info.ParseError) {
5799 // Emit pending errors if any exist.
5800 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005801 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005802 }
5803
5804 // No pending error should exist here.
5805 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005806
Benjamin Kramer1a136112013-02-15 20:37:21 +00005807 if (Info.Opcode == ~0U)
5808 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005809
Benjamin Kramer1a136112013-02-15 20:37:21 +00005810 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005811
Benjamin Kramer1a136112013-02-15 20:37:21 +00005812 // Build the list of clobbers, outputs and inputs.
5813 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005814 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005815
Benjamin Kramer1a136112013-02-15 20:37:21 +00005816 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005817 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005818 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005819
Benjamin Kramer1a136112013-02-15 20:37:21 +00005820 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005821 if (Operand.isReg() && !Operand.needAddressOf() &&
5822 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005823 unsigned NumDefs = Desc.getNumDefs();
5824 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005825 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5826 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005827 continue;
5828 }
5829
5830 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005831 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005832 if (SymName.empty())
5833 continue;
5834
David Blaikie960ea3f2014-06-08 16:18:35 +00005835 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005836 if (!OpDecl)
5837 continue;
5838
5839 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005840 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005841 if (isOutput) {
5842 ++InputIdx;
5843 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005844 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005845 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005846 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005847 } else {
5848 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005849 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5850 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005851 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005852 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005853 }
Reid Kleckneree088972013-12-10 18:27:32 +00005854
5855 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005856 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5857 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005858 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005859 }
5860
5861 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005862 NumOutputs = OutputDecls.size();
5863 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005864
5865 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005866 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5867 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5868 ClobberRegs.end());
5869 Clobbers.assign(ClobberRegs.size(), std::string());
5870 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5871 raw_string_ostream OS(Clobbers[I]);
5872 IP->printRegName(OS, ClobberRegs[I]);
5873 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005874
5875 // Merge the various outputs and inputs. Output are expected first.
5876 if (NumOutputs || NumInputs) {
5877 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005878 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005879 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005880 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005881 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005882 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005883 }
5884 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005885 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005886 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005887 }
5888 }
5889
5890 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005891 std::string AsmStringIR;
5892 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005893 StringRef ASMString =
5894 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5895 const char *AsmStart = ASMString.begin();
5896 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005897 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005898 for (const AsmRewrite &AR : AsmStrRewrites) {
5899 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005900
David Majnemer8114c1a2014-06-23 02:17:16 +00005901 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005902 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005903
Chad Rosier120eefd2013-03-19 17:32:17 +00005904 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005905 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005906 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005907
Chad Rosier37e755c2012-10-23 17:43:43 +00005908 // Skip the original expression.
5909 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005910 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005911 continue;
5912 }
5913
Chad Rosierff10ed12013-04-12 16:26:42 +00005914 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005915 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005916 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005917 default:
5918 break;
Coby Tayreed8912892017-08-24 08:46:25 +00005919 case AOK_IntelExpr:
5920 assert(AR.IntelExp.isValid() && "cannot write invalid intel expression");
5921 if (AR.IntelExp.NeedBracs)
5922 OS << "[";
5923 if (AR.IntelExp.hasBaseReg())
5924 OS << AR.IntelExp.BaseReg;
5925 if (AR.IntelExp.hasIndexReg())
5926 OS << (AR.IntelExp.hasBaseReg() ? " + " : "")
5927 << AR.IntelExp.IndexReg;
5928 if (AR.IntelExp.Scale > 1)
5929 OS << " * $$" << AR.IntelExp.Scale;
5930 if (AR.IntelExp.Imm || !AR.IntelExp.hasRegs())
5931 OS << (AR.IntelExp.hasRegs() ? " + $$" : "$$") << AR.IntelExp.Imm;
5932 if (AR.IntelExp.NeedBracs)
5933 OS << "]";
Chad Rosier8bce6642012-10-18 15:49:34 +00005934 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005935 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005936 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005937 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005938 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005939 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005940 break;
5941 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005942 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005943 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005944 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005945 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005946 default: break;
5947 case 8: OS << "byte ptr "; break;
5948 case 16: OS << "word ptr "; break;
5949 case 32: OS << "dword ptr "; break;
5950 case 64: OS << "qword ptr "; break;
5951 case 80: OS << "xword ptr "; break;
5952 case 128: OS << "xmmword ptr "; break;
5953 case 256: OS << "ymmword ptr "; break;
5954 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005955 break;
5956 case AOK_Emit:
5957 OS << ".byte";
5958 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005959 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005960 // MS alignment directives are measured in bytes. If the native assembler
5961 // measures alignment in bytes, we can pass it straight through.
5962 OS << ".align";
5963 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5964 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005965
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005966 // Alignment is in log2 form, so print that instead and skip the original
5967 // immediate.
5968 unsigned Val = AR.Val;
5969 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005970 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005971 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5972 break;
5973 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005974 case AOK_EVEN:
5975 OS << ".even";
5976 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005977 case AOK_EndOfStatement:
5978 OS << "\n\t";
5979 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005980 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005981
Chad Rosier8bce6642012-10-18 15:49:34 +00005982 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005983 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005984 }
5985
5986 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005987 if (AsmStart != AsmEnd)
5988 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005989
5990 AsmString = OS.str();
5991 return false;
5992}
5993
Pete Cooper80d21cb2015-06-22 19:35:57 +00005994namespace llvm {
5995namespace MCParserUtils {
5996
5997/// Returns whether the given symbol is used anywhere in the given expression,
5998/// or subexpressions.
5999static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
6000 switch (Value->getKind()) {
6001 case MCExpr::Binary: {
6002 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
6003 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
6004 isSymbolUsedInExpression(Sym, BE->getRHS());
6005 }
6006 case MCExpr::Target:
6007 case MCExpr::Constant:
6008 return false;
6009 case MCExpr::SymbolRef: {
6010 const MCSymbol &S =
6011 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
6012 if (S.isVariable())
6013 return isSymbolUsedInExpression(Sym, S.getVariableValue());
6014 return &S == Sym;
6015 }
6016 case MCExpr::Unary:
6017 return isSymbolUsedInExpression(
6018 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
6019 }
6020
6021 llvm_unreachable("Unknown expr kind!");
6022}
6023
6024bool parseAssignmentExpression(StringRef Name, bool allow_redef,
6025 MCAsmParser &Parser, MCSymbol *&Sym,
Nirav Dave7fd992a2018-08-16 16:31:14 +00006026 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00006027
6028 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00006029 SMLoc EqualLoc = Parser.getTok().getLoc();
Nirav Dave7fd992a2018-08-16 16:31:14 +00006030 if (Parser.parseExpression(Value))
6031 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00006032
6033 // Note: we don't count b as used in "a = b". This is to allow
6034 // a = b
6035 // b = c
6036
Nirav Dave1a9044b2016-10-24 14:35:29 +00006037 if (Parser.parseToken(AsmToken::EndOfStatement))
6038 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00006039
6040 // Validate that the LHS is allowed to be a variable (either it has not been
6041 // used as a symbol, or it is an absolute symbol).
6042 Sym = Parser.getContext().lookupSymbol(Name);
6043 if (Sym) {
6044 // Diagnose assignment to a label.
6045 //
6046 // FIXME: Diagnostics. Note the location of the definition as a label.
6047 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
6048 if (isSymbolUsedInExpression(Sym, Value))
6049 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00006050 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
6051 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00006052 ; // Allow redefinitions of undefined symbols only used in directives.
6053 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
6054 ; // Allow redefinitions of variables that haven't yet been used.
6055 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
6056 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
6057 else if (!Sym->isVariable())
6058 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
6059 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
6060 return Parser.Error(EqualLoc,
6061 "invalid reassignment of non-absolute variable '" +
6062 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00006063 } else if (Name == ".") {
Oliver Stannard268f42f2016-12-14 10:43:58 +00006064 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
Pete Cooper80d21cb2015-06-22 19:35:57 +00006065 return false;
6066 } else
6067 Sym = Parser.getContext().getOrCreateSymbol(Name);
6068
6069 Sym->setRedefinable(allow_redef);
6070
6071 return false;
6072}
6073
Eugene Zelenko33d7b762016-08-23 17:14:32 +00006074} // end namespace MCParserUtils
6075} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00006076
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006077/// Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00006078MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
Sanne Wouda29338752017-02-08 14:48:05 +00006079 MCStreamer &Out, const MCAsmInfo &MAI,
6080 unsigned CB) {
6081 return new AsmParser(SM, C, Out, MAI, CB);
Daniel Dunbar01e36072010-07-17 02:26:10 +00006082}