blob: 7fe4f9e669d87381880ee72dce5c7173e9ece854 [file] [log] [blame]
Chris Lattnerb0133452009-06-21 20:16:42 +00001//===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This class implements the parser for assembly files.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar2af16532010-09-24 01:59:56 +000014#include "llvm/ADT/APFloat.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000015#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/None.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000018#include "llvm/ADT/SmallString.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000019#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/STLExtras.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000021#include "llvm/ADT/StringMap.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000022#include "llvm/ADT/StringRef.h"
Daniel Dunbareb6bb322009-07-27 23:20:52 +000023#include "llvm/ADT/Twine.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000024#include "llvm/MC/MCAsmInfo.h"
Reid Klecknera5b1eef2016-08-26 17:58:37 +000025#include "llvm/MC/MCCodeView.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000026#include "llvm/MC/MCContext.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000027#include "llvm/MC/MCDirectives.h"
Evan Cheng11424442011-07-26 00:24:13 +000028#include "llvm/MC/MCDwarf.h"
Daniel Dunbar115e4d62009-08-31 08:06:59 +000029#include "llvm/MC/MCExpr.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000030#include "llvm/MC/MCInstPrinter.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000031#include "llvm/MC/MCInstrDesc.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000032#include "llvm/MC/MCInstrInfo.h"
Rafael Espindolae28610d2013-12-09 20:26:40 +000033#include "llvm/MC/MCObjectFileInfo.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000034#include "llvm/MC/MCParser/AsmCond.h"
35#include "llvm/MC/MCParser/AsmLexer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000036#include "llvm/MC/MCParser/MCAsmLexer.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000037#include "llvm/MC/MCParser/MCAsmParser.h"
Pete Cooper80d21cb2015-06-22 19:35:57 +000038#include "llvm/MC/MCParser/MCAsmParserUtils.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000039#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000040#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Cheng76792992011-07-20 05:58:47 +000041#include "llvm/MC/MCRegisterInfo.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000042#include "llvm/MC/MCSection.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000043#include "llvm/MC/MCStreamer.h"
Daniel Dunbarae7ac012009-06-29 23:43:14 +000044#include "llvm/MC/MCSymbol.h"
Daniel Sanders9f6ad492015-11-12 13:33:00 +000045#include "llvm/MC/MCValue.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000046#include "llvm/Support/Casting.h"
Davide Italiano7c9fc732016-07-27 05:51:56 +000047#include "llvm/Support/CommandLine.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000048#include "llvm/Support/Dwarf.h"
Benjamin Kramer4efe5062012-01-28 15:28:41 +000049#include "llvm/Support/ErrorHandling.h"
Jim Grosbach76346c32011-06-29 16:05:14 +000050#include "llvm/Support/MathExtras.h"
Kevin Enderbye233dda2010-06-28 21:45:58 +000051#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000052#include "llvm/Support/SMLoc.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000053#include "llvm/Support/SourceMgr.h"
Chris Lattner36e02122009-06-21 20:54:55 +000054#include "llvm/Support/raw_ostream.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000055#include <algorithm>
56#include <cassert>
Nick Lewycky0de20af2010-12-19 20:43:38 +000057#include <cctype>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000058#include <cstddef>
59#include <cstdint>
Benjamin Kramerd59664f2014-04-29 23:26:49 +000060#include <deque>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000061#include <memory>
Davide Italiano7c9fc732016-07-27 05:51:56 +000062#include <sstream>
Chad Rosier8bce6642012-10-18 15:49:34 +000063#include <string>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000064#include <tuple>
65#include <utility>
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000066#include <vector>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000067
Chris Lattnerb0133452009-06-21 20:16:42 +000068using namespace llvm;
69
Eric Christophera7c32732012-12-18 00:30:54 +000070MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
Nick Lewyckyac612272012-10-19 07:00:09 +000071
Davide Italiano7c9fc732016-07-27 05:51:56 +000072static cl::opt<unsigned> AsmMacroMaxNestingDepth(
73 "asm-macro-max-nesting-depth", cl::init(20), cl::Hidden,
74 cl::desc("The maximum nesting depth allowed for assembly macros."));
75
Daniel Dunbar86033402010-07-12 17:54:38 +000076namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +000077
Eli Benderskya313ae62013-01-16 18:56:50 +000078/// \brief Helper types for tracking macro definitions.
79typedef std::vector<AsmToken> MCAsmMacroArgument;
80typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000081
82struct MCAsmMacroParameter {
83 StringRef Name;
84 MCAsmMacroArgument Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000085 bool Required;
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +000086 bool Vararg;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000087
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +000088 MCAsmMacroParameter() : Required(false), Vararg(false) {}
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000089};
90
Eli Benderskya313ae62013-01-16 18:56:50 +000091typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
92
93struct MCAsmMacro {
94 StringRef Name;
95 StringRef Body;
96 MCAsmMacroParameters Parameters;
97
98public:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +000099 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
100 : Name(N), Body(B), Parameters(std::move(P)) {}
Eli Benderskya313ae62013-01-16 18:56:50 +0000101};
102
Daniel Dunbar43235712010-07-18 18:54:11 +0000103/// \brief Helper class for storing information about an active macro
104/// instantiation.
105struct MacroInstantiation {
Daniel Dunbar43235712010-07-18 18:54:11 +0000106 /// The location of the instantiation.
107 SMLoc InstantiationLoc;
108
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000109 /// The buffer where parsing should resume upon instantiation completion.
110 int ExitBuffer;
111
Daniel Dunbar43235712010-07-18 18:54:11 +0000112 /// The location where parsing should resume upon instantiation completion.
113 SMLoc ExitLoc;
114
Nico Weber155dccd12014-07-24 17:08:39 +0000115 /// The depth of TheCondStack at the start of the instantiation.
116 size_t CondStackDepth;
117
Daniel Dunbar43235712010-07-18 18:54:11 +0000118public:
Rafael Espindola9eef18c2014-08-27 19:49:03 +0000119 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
Daniel Dunbar43235712010-07-18 18:54:11 +0000120};
121
Eli Friedman0f4871d2012-10-22 23:58:19 +0000122struct ParseStatementInfo {
Jim Grosbach4b905842013-09-20 23:08:21 +0000123 /// \brief The parsed operands from the last parsed statement.
David Blaikie960ea3f2014-06-08 16:18:35 +0000124 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000125
Jim Grosbach4b905842013-09-20 23:08:21 +0000126 /// \brief The opcode from the last parsed instruction.
Eli Friedman0f4871d2012-10-22 23:58:19 +0000127 unsigned Opcode;
128
Jim Grosbach4b905842013-09-20 23:08:21 +0000129 /// \brief Was there an error parsing the inline assembly?
Chad Rosier149e8e02012-12-12 22:45:52 +0000130 bool ParseError;
131
Eli Friedman0f4871d2012-10-22 23:58:19 +0000132 SmallVectorImpl<AsmRewrite> *AsmRewrites;
133
Craig Topper353eda42014-04-24 06:44:33 +0000134 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000135 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier149e8e02012-12-12 22:45:52 +0000136 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000137};
138
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000139/// \brief The concrete assembly parser instance.
140class AsmParser : public MCAsmParser {
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000141 AsmParser(const AsmParser &) = delete;
142 void operator=(const AsmParser &) = delete;
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000143
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000144private:
145 AsmLexer Lexer;
146 MCContext &Ctx;
147 MCStreamer &Out;
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000148 const MCAsmInfo &MAI;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000149 SourceMgr &SrcMgr;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000150 SourceMgr::DiagHandlerTy SavedDiagHandler;
151 void *SavedDiagContext;
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000152 std::unique_ptr<MCAsmParserExtension> PlatformParser;
Rafael Espindola82065cb2011-04-11 21:49:50 +0000153
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000154 /// This is the current buffer index we're lexing from as managed by the
155 /// SourceMgr object.
Alp Tokera55b95b2014-07-06 10:33:31 +0000156 unsigned CurBuffer;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000157
158 AsmCond TheCondState;
159 std::vector<AsmCond> TheCondStack;
160
Jim Grosbach4b905842013-09-20 23:08:21 +0000161 /// \brief maps directive names to handler methods in parser
Eli Bendersky17233942013-01-15 22:59:42 +0000162 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000163 /// addDirectiveHandler.
Eli Bendersky17233942013-01-15 22:59:42 +0000164 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000165
Jim Grosbach4b905842013-09-20 23:08:21 +0000166 /// \brief Map of currently defined macros.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000167 StringMap<MCAsmMacro> MacroMap;
Daniel Dunbarc1f58ec2010-07-18 18:47:21 +0000168
Jim Grosbach4b905842013-09-20 23:08:21 +0000169 /// \brief Stack of active macro instantiations.
Daniel Dunbar43235712010-07-18 18:54:11 +0000170 std::vector<MacroInstantiation*> ActiveMacros;
171
Jim Grosbach4b905842013-09-20 23:08:21 +0000172 /// \brief List of bodies of anonymous macros.
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +0000173 std::deque<MCAsmMacro> MacroLikeBodies;
174
Daniel Dunbar828984f2010-07-18 18:38:02 +0000175 /// Boolean tracking whether macro substitution is enabled.
Eli Benderskyc2f6f922013-01-14 18:08:41 +0000176 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000177
Toma Tabacu217116e2015-04-27 10:50:29 +0000178 /// \brief Keeps track of how many .macro's have been instantiated.
179 unsigned NumOfMacroInstantiations;
180
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000181 /// The values from the last parsed cpp hash file line comment if any.
Tim Northoverc0bef992016-04-13 19:46:54 +0000182 struct CppHashInfoTy {
183 StringRef Filename;
Andrew Kaylorca196472016-04-21 20:09:35 +0000184 int64_t LineNumber = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000185 SMLoc Loc;
Andrew Kaylorca196472016-04-21 20:09:35 +0000186 unsigned Buf = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000187 };
188 CppHashInfoTy CppHashInfo;
189
190 /// \brief List of forward directional labels for diagnosis at the end.
191 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
192
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000193 /// When generating dwarf for assembly source files we need to calculate the
194 /// logical line number based on the last parsed cpp hash file line comment
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000195 /// and current line. Since this is slow and messes up the SourceMgr's
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000196 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
197 SMLoc LastQueryIDLoc;
Alp Tokera55b95b2014-07-06 10:33:31 +0000198 unsigned LastQueryBuffer;
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000199 unsigned LastQueryLine;
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000200
Devang Patela173ee52012-01-31 18:14:05 +0000201 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
202 unsigned AssemblerDialect;
203
Jim Grosbach4b905842013-09-20 23:08:21 +0000204 /// \brief is Darwin compatibility enabled?
Preston Gurd05500642012-09-19 20:36:12 +0000205 bool IsDarwin;
206
Jim Grosbach4b905842013-09-20 23:08:21 +0000207 /// \brief Are we parsing ms-style inline assembly?
Chad Rosier49963552012-10-13 00:26:04 +0000208 bool ParsingInlineAsm;
209
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000210public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000211 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000212 const MCAsmInfo &MAI);
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000213 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000214
Craig Topper59be68f2014-03-08 07:14:16 +0000215 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000216
Craig Topper59be68f2014-03-08 07:14:16 +0000217 void addDirectiveHandler(StringRef Directive,
218 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000219 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000220 }
221
Toma Tabacu11e14a92015-04-21 11:50:52 +0000222 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
223 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
224 }
225
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000226public:
227 /// @name MCAsmParser Interface
228 /// {
229
Craig Topper59be68f2014-03-08 07:14:16 +0000230 SourceMgr &getSourceManager() override { return SrcMgr; }
231 MCAsmLexer &getLexer() override { return Lexer; }
232 MCContext &getContext() override { return Ctx; }
233 MCStreamer &getStreamer() override { return Out; }
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000234
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000235 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
236
Craig Topper59be68f2014-03-08 07:14:16 +0000237 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000238 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000239 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000240 else
241 return AssemblerDialect;
242 }
Craig Topper59be68f2014-03-08 07:14:16 +0000243 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000244 AssemblerDialect = i;
245 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000246
Nirav Dave2364748a2016-09-16 18:30:20 +0000247 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
248 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
249 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000250
Craig Topper59be68f2014-03-08 07:14:16 +0000251 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000252
Yunzhong Gao27ea29b2016-09-02 23:15:29 +0000253 void setParsingInlineAsm(bool V) override {
254 ParsingInlineAsm = V;
255 Lexer.setParsingMSInlineAsm(V);
256 }
Craig Topper59be68f2014-03-08 07:14:16 +0000257 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000258
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000259 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000260 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier37e755c2012-10-23 17:43:43 +0000261 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000262 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000263 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000264 const MCInstrInfo *MII, const MCInstPrinter *IP,
265 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000266
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000267 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000268 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
269 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
270 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000271 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
272 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000273 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000274
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000275 /// \brief Parse a floating point expression using the float \p Semantics
276 /// and set \p Res to the value.
277 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
278
Jim Grosbach4b905842013-09-20 23:08:21 +0000279 /// \brief Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000280 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000281 bool parseIdentifier(StringRef &Res) override;
282 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000283
Nirav Davef43cc9f2016-10-10 15:24:54 +0000284 bool checkForValidSection() override;
Nirav Davea645433c2016-07-18 15:24:03 +0000285
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000286 /// }
287
288private:
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000289 bool parseStatement(ParseStatementInfo &Info,
290 MCAsmParserSemaCallback *SI);
Marina Yatsina5f5de9f2016-03-07 18:11:16 +0000291 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
Craig Topper3c76c522015-09-20 23:35:59 +0000292 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000293
Jim Grosbach4b905842013-09-20 23:08:21 +0000294 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000295 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000296 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000297 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000298 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000299 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000300
Eli Benderskya313ae62013-01-16 18:56:50 +0000301 /// \brief Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000302 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000303
304 /// \brief Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000305 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000306
307 /// \brief Lookup a previously defined macro.
308 /// \param Name Macro name.
309 /// \returns Pointer to macro. NULL if no such macro was defined.
Jim Grosbach4b905842013-09-20 23:08:21 +0000310 const MCAsmMacro* lookupMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000311
312 /// \brief Define a new macro with the given name and information.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000313 void defineMacro(StringRef Name, MCAsmMacro Macro);
Eli Benderskya313ae62013-01-16 18:56:50 +0000314
315 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
Jim Grosbach4b905842013-09-20 23:08:21 +0000316 void undefineMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000317
318 /// \brief Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000319 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000320
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000321 /// \brief Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000322 ///
323 /// \param M The macro.
324 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000325 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000326
327 /// \brief Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000328 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000329
David Majnemer91fc4c22014-01-29 18:57:46 +0000330 /// \brief Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000331 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000332
333 /// \brief Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000334 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000335
Jim Grosbach4b905842013-09-20 23:08:21 +0000336 void printMacroInstantiations();
337 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Nirav Dave2364748a2016-09-16 18:30:20 +0000338 SMRange Range = None) const {
339 ArrayRef<SMRange> Ranges(Range);
Chris Lattner72845262011-10-16 05:47:55 +0000340 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000341 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000342 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000343
Jim Grosbach4b905842013-09-20 23:08:21 +0000344 /// \brief Enter the specified file. This returns true on failure.
345 bool enterIncludeFile(const std::string &Filename);
346
347 /// \brief Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000348 /// This returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000349 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
350 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
Daniel Dunbar43235712010-07-18 18:54:11 +0000351
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000352 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000353 /// current token is not set; clients should ensure Lex() is called
354 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000355 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000356 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000357 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000358 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000359
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000360 /// \brief Parse up to the end of statement and a return the contents from the
361 /// current token until the end of the statement; the current token on exit
362 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000363 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000364
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000365 /// \brief Parse until the end of a statement or a comma is encountered,
366 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000367 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000368
Jim Grosbach4b905842013-09-20 23:08:21 +0000369 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +0000370 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000371
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000372 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
373 MCBinaryExpr::Opcode &Kind);
374
Jim Grosbach4b905842013-09-20 23:08:21 +0000375 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
376 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
377 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000378
Jim Grosbach4b905842013-09-20 23:08:21 +0000379 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000380
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000381 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
382 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
383
Eli Bendersky17233942013-01-15 22:59:42 +0000384 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000385 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000386 DK_NO_DIRECTIVE, // Placeholder
387 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000388 DK_RELOC,
David Woodhoused6de0d92014-02-01 16:20:59 +0000389 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
Petr Hosek731bb9c2016-08-23 21:34:53 +0000390 DK_DC, DK_DC_A, DK_DC_B, DK_DC_D, DK_DC_L, DK_DC_S, DK_DC_W, DK_DC_X,
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000391 DK_DCB, DK_DCB_B, DK_DCB_D, DK_DCB_L, DK_DCB_S, DK_DCB_W, DK_DCB_X,
Petr Hosek85b2f672016-09-23 21:53:36 +0000392 DK_DS, DK_DS_B, DK_DS_D, DK_DS_L, DK_DS_P, DK_DS_S, DK_DS_W, DK_DS_X,
David Woodhoused6de0d92014-02-01 16:20:59 +0000393 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky96522722013-01-11 22:55:28 +0000394 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000395 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
Kevin Enderby3aeada22013-08-28 17:50:59 +0000396 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
Lang Hamesf9033bb2016-04-11 18:33:45 +0000397 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER,
Lang Hames1b640e02016-03-15 01:43:05 +0000398 DK_PRIVATE_EXTERN, DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000399 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
400 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000401 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
Sid Manning51c35602015-03-18 14:20:54 +0000402 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
403 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
Eli Bendersky17233942013-01-15 22:59:42 +0000404 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000405 DK_CV_FILE, DK_CV_FUNC_ID, DK_CV_INLINE_SITE_ID, DK_CV_LOC, DK_CV_LINETABLE,
406 DK_CV_INLINE_LINETABLE, DK_CV_DEF_RANGE, DK_CV_STRINGTABLE,
407 DK_CV_FILECHECKSUMS,
Eli Bendersky17233942013-01-15 22:59:42 +0000408 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
409 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
410 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
411 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
412 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000413 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
Nico Weber155dccd12014-07-24 17:08:39 +0000414 DK_MACROS_ON, DK_MACROS_OFF,
415 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000416 DK_SLEB128, DK_ULEB128,
Nico Weber404012b2014-07-24 16:26:06 +0000417 DK_ERR, DK_ERROR, DK_WARNING,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000418 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000419 };
420
Jim Grosbach4b905842013-09-20 23:08:21 +0000421 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000422 /// directives parsed by this class.
423 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000424
425 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000426 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000427 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Nirav Dave1a9044b2016-10-24 14:35:29 +0000428 bool parseDirectiveValue(StringRef IDVal,
429 unsigned Size); // ".byte", ".long", ...
430 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
431 bool parseDirectiveRealValue(StringRef IDVal,
432 const fltSemantics &); // ".single", ...
Jim Grosbach4b905842013-09-20 23:08:21 +0000433 bool parseDirectiveFill(); // ".fill"
434 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000435 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000436 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
437 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000438 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000439 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000440
Eli Bendersky17233942013-01-15 22:59:42 +0000441 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000442 bool parseDirectiveFile(SMLoc DirectiveLoc);
443 bool parseDirectiveLine();
444 bool parseDirectiveLoc();
445 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000446
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000447 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
448 // ".cv_inline_linetable", ".cv_def_range"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000449 bool parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000450 bool parseDirectiveCVFuncId();
451 bool parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000452 bool parseDirectiveCVLoc();
453 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000454 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000455 bool parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000456 bool parseDirectiveCVStringTable();
457 bool parseDirectiveCVFileChecksums();
458
Eli Bendersky17233942013-01-15 22:59:42 +0000459 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000460 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000461 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000462 bool parseDirectiveCFISections();
463 bool parseDirectiveCFIStartProc();
464 bool parseDirectiveCFIEndProc();
465 bool parseDirectiveCFIDefCfaOffset();
466 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
467 bool parseDirectiveCFIAdjustCfaOffset();
468 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
469 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
470 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
471 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
472 bool parseDirectiveCFIRememberState();
473 bool parseDirectiveCFIRestoreState();
474 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
475 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
476 bool parseDirectiveCFIEscape();
477 bool parseDirectiveCFISignalFrame();
478 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000479
480 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000481 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000482 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000483 bool parseDirectiveEndMacro(StringRef Directive);
484 bool parseDirectiveMacro(SMLoc DirectiveLoc);
485 bool parseDirectiveMacrosOnOff(StringRef Directive);
Eli Bendersky17233942013-01-15 22:59:42 +0000486
Eli Benderskyf483ff92012-12-20 19:05:53 +0000487 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000488 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000489 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000490 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000491 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000492 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000493
Eli Bendersky17233942013-01-15 22:59:42 +0000494 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000495 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000496
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000497 // ".dcb"
498 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
499 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
Petr Hosek85b2f672016-09-23 21:53:36 +0000500 // ".ds"
501 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000502
Eli Bendersky17233942013-01-15 22:59:42 +0000503 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000504 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000505
Jim Grosbach4b905842013-09-20 23:08:21 +0000506 /// \brief Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000507 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000508 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000509
Jim Grosbach4b905842013-09-20 23:08:21 +0000510 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000511
Jim Grosbach4b905842013-09-20 23:08:21 +0000512 bool parseDirectiveAbort(); // ".abort"
513 bool parseDirectiveInclude(); // ".include"
514 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000515
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000516 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
517 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000518 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000519 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000520 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000521 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000522 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
523 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000524 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000525 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
526 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
527 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
528 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000529 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000530
Jim Grosbach4b905842013-09-20 23:08:21 +0000531 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000532 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000533
Rafael Espindola34b9c512012-06-03 23:57:14 +0000534 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000535 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
536 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000537 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000538 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000539 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
540 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
541 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000542
Chad Rosierc7f552c2013-02-12 21:33:51 +0000543 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000544 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000545 size_t Len);
546
547 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000548 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000549
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000550 // "end"
551 bool parseDirectiveEnd(SMLoc DirectiveLoc);
552
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000553 // ".err" or ".error"
554 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000555
Nico Weber404012b2014-07-24 16:26:06 +0000556 // ".warning"
557 bool parseDirectiveWarning(SMLoc DirectiveLoc);
558
Eli Bendersky17233942013-01-15 22:59:42 +0000559 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000560};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000561
562} // end anonymous namespace
Daniel Dunbar86033402010-07-12 17:54:38 +0000563
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000564namespace llvm {
565
566extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000567extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000568extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000569
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000570} // end namespace llvm
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000571
Chris Lattnerc35681b2010-01-19 19:46:13 +0000572enum { DEFAULT_ADDRSPACE = 0 };
573
David Blaikie9f380a32015-03-16 18:06:57 +0000574AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
575 const MCAsmInfo &MAI)
576 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
577 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
Nirav Dave2364748a2016-09-16 18:30:20 +0000578 MacrosEnabledFlag(true), CppHashInfo(), AssemblerDialect(~0U),
579 IsDarwin(false), ParsingInlineAsm(false) {
580 HadError = false;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000581 // Save the old handler.
582 SavedDiagHandler = SrcMgr.getDiagHandler();
583 SavedDiagContext = SrcMgr.getDiagContext();
584 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000585 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000586 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000587
Daniel Dunbarc5011082010-07-12 18:12:02 +0000588 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000589 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
590 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000591 PlatformParser.reset(createCOFFAsmParser());
592 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000593 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000594 PlatformParser.reset(createDarwinAsmParser());
595 IsDarwin = true;
596 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000597 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000598 PlatformParser.reset(createELFAsmParser());
599 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000600 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000601
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000602 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000603 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000604
605 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000606}
607
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000608AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000609 assert((HadError || ActiveMacros.empty()) &&
610 "Unexpected active macro instantiation!");
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000611}
612
Jim Grosbach4b905842013-09-20 23:08:21 +0000613void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000614 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000615 for (std::vector<MacroInstantiation *>::const_reverse_iterator
616 it = ActiveMacros.rbegin(),
617 ie = ActiveMacros.rend();
618 it != ie; ++it)
619 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000620 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000621}
622
Nirav Dave2364748a2016-09-16 18:30:20 +0000623void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
624 printPendingErrors();
625 printMessage(L, SourceMgr::DK_Note, Msg, Range);
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000626 printMacroInstantiations();
627}
628
Nirav Dave2364748a2016-09-16 18:30:20 +0000629bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000630 if(getTargetParser().getTargetOptions().MCNoWarn)
631 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000632 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Nirav Dave2364748a2016-09-16 18:30:20 +0000633 return Error(L, Msg, Range);
634 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000635 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000636 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000637}
638
Nirav Dave2364748a2016-09-16 18:30:20 +0000639bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000640 HadError = true;
Nirav Dave2364748a2016-09-16 18:30:20 +0000641 printMessage(L, SourceMgr::DK_Error, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000642 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000643 return true;
644}
645
Jim Grosbach4b905842013-09-20 23:08:21 +0000646bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000647 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000648 unsigned NewBuf =
649 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
650 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000651 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000652
Sean Callanan7a77eae2010-01-21 00:19:58 +0000653 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000654 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000655 return false;
656}
Daniel Dunbar43235712010-07-18 18:54:11 +0000657
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000658/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000659/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000660/// returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000661bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
662 const MCExpr *Count, SMLoc Loc) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000663 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000664 unsigned NewBuf =
665 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
666 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000667 return true;
668
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000669 // Pick up the bytes from the file and emit them.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000670 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
671 Bytes = Bytes.drop_front(Skip);
672 if (Count) {
673 int64_t Res;
674 if (!Count->evaluateAsAbsolute(Res))
675 return Error(Loc, "expected absolute expression");
676 if (Res < 0)
677 return Warning(Loc, "negative count has no effect");
678 Bytes = Bytes.take_front(Res);
679 }
680 getStreamer().EmitBytes(Bytes);
Kevin Enderby109f25c2011-12-14 21:47:48 +0000681 return false;
682}
683
Alp Tokera55b95b2014-07-06 10:33:31 +0000684void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
685 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000686 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
687 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000688}
689
Sean Callanan7a77eae2010-01-21 00:19:58 +0000690const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000691 if (Lexer.getTok().is(AsmToken::Error))
692 Error(Lexer.getErrLoc(), Lexer.getErr());
693
Nirav Dave53a72f42016-07-11 12:42:14 +0000694 // if it's a end of statement with a comment in it
695 if (getTok().is(AsmToken::EndOfStatement)) {
696 // if this is a line comment output it.
697 if (getTok().getString().front() != '\n' &&
698 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
699 Out.addExplicitComment(Twine(getTok().getString()));
700 }
701
Sean Callanan7a77eae2010-01-21 00:19:58 +0000702 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000703
704 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000705 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000706 if (MAI.preserveAsmComments())
707 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000708 tok = &Lexer.Lex();
709 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000710
Sean Callanan7a77eae2010-01-21 00:19:58 +0000711 if (tok->is(AsmToken::Eof)) {
712 // If this is the end of an included file, pop the parent file off the
713 // include stack.
714 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
715 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000716 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000717 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000718 }
719 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000720
Sean Callanan7a77eae2010-01-21 00:19:58 +0000721 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000722}
723
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000724bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000725 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000726 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000727 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000728
Chris Lattner36e02122009-06-21 20:54:55 +0000729 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000730 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000731
732 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000733 AsmCond StartingCondState = TheCondState;
734
Kevin Enderby6469fc22011-11-01 22:27:22 +0000735 // If we are generating dwarf for assembly source files save the initial text
736 // section and generate a .file directive.
737 if (getContext().getGenDwarfForAssembly()) {
Eric Christopher445c9522016-10-14 05:47:37 +0000738 MCSection *Sec = getStreamer().getCurrentSectionOnly();
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000739 if (!Sec->getBeginSymbol()) {
740 MCSymbol *SectionStartSym = getContext().createTempSymbol();
741 getStreamer().EmitLabel(SectionStartSym);
742 Sec->setBeginSymbol(SectionStartSym);
743 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000744 bool InsertResult = getContext().addGenDwarfSection(Sec);
745 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000746 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000747 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
748 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000749 }
750
Chris Lattner73f36112009-07-02 21:53:43 +0000751 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000752 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman0f4871d2012-10-22 23:58:19 +0000753 ParseStatementInfo Info;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000754 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000755 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000756
Nirav Dave2364748a2016-09-16 18:30:20 +0000757 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
758 // for printing ErrMsg via Lex() only if no (presumably better) parser error
759 // exists.
760 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
Nirav Dave1180e6892016-06-02 17:15:05 +0000761 Lex();
762 }
763
Nirav Dave2364748a2016-09-16 18:30:20 +0000764 // parseStatement returned true so may need to emit an error.
765 printPendingErrors();
766
767 // Skipping to the next line if needed.
768 if (!getLexer().isAtStartOfStatement())
769 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000770 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000771
Nirav Dave2364748a2016-09-16 18:30:20 +0000772 // All errors should have been emitted.
773 assert(!hasPendingError() && "unexpected error from parseStatement");
774
Oliver Stannard21718282016-07-26 14:19:47 +0000775 getTargetParser().flushPendingInstructions(getStreamer());
776
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000777 if (TheCondState.TheCond != StartingCondState.TheCond ||
778 TheCondState.Ignore != StartingCondState.Ignore)
Nirav Dave2364748a2016-09-16 18:30:20 +0000779 printError(getTok().getLoc(), "unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000780 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000781 const auto &LineTables = getContext().getMCDwarfLineTables();
782 if (!LineTables.empty()) {
783 unsigned Index = 0;
784 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
785 if (File.Name.empty() && Index != 0)
Nirav Dave2364748a2016-09-16 18:30:20 +0000786 printError(getTok().getLoc(), "unassigned file number: " +
787 Twine(Index) +
788 " for .file directives");
David Blaikie8bf66c42014-04-01 07:35:52 +0000789 ++Index;
790 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000791 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000792
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000793 // Check to see that all assembler local symbols were actually defined.
794 // Targets that don't do subsections via symbols may not want this, though,
795 // so conservatively exclude them. Only do this if we're finalizing, though,
796 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000797 if (!NoFinalize) {
798 if (MAI.hasSubsectionsViaSymbols()) {
799 for (const auto &TableEntry : getContext().getSymbols()) {
800 MCSymbol *Sym = TableEntry.getValue();
801 // Variable symbols may not be marked as defined, so check those
802 // explicitly. If we know it's a variable, we have a definition for
803 // the purposes of this check.
804 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
805 // FIXME: We would really like to refer back to where the symbol was
806 // first referenced for a source location. We need to add something
807 // to track that. Currently, we just point to the end of the file.
Nirav Dave2364748a2016-09-16 18:30:20 +0000808 printError(getTok().getLoc(), "assembler local symbol '" +
809 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000810 }
811 }
812
813 // Temporary symbols like the ones for directional jumps don't go in the
814 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000815 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
816 if (std::get<2>(LocSym)->isUndefined()) {
817 // Reset the state of any "# line file" directives we've seen to the
818 // context as it was at the diagnostic site.
819 CppHashInfo = std::get<1>(LocSym);
Nirav Dave2364748a2016-09-16 18:30:20 +0000820 printError(std::get<0>(LocSym), "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000821 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000822 }
823 }
824
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000825 // Finalize the output stream if there are no errors and if the client wants
826 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000827 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000828 Out.Finish();
829
Oliver Stannard07b43d32015-11-17 09:58:07 +0000830 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000831}
832
Nirav Davef43cc9f2016-10-10 15:24:54 +0000833bool AsmParser::checkForValidSection() {
Eric Christopher445c9522016-10-14 05:47:37 +0000834 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000835 Out.InitSections(false);
Nirav Davef43cc9f2016-10-10 15:24:54 +0000836 return Error(getTok().getLoc(),
837 "expected section directive before assembly directive");
Daniel Dunbare5444a82010-09-09 22:42:59 +0000838 }
Nirav Davef43cc9f2016-10-10 15:24:54 +0000839 return false;
Daniel Dunbare5444a82010-09-09 22:42:59 +0000840}
841
Jim Grosbach4b905842013-09-20 23:08:21 +0000842/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000843void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000844 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000845 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000846
Chris Lattnere5074c42009-06-22 01:29:09 +0000847 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000848 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000849 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000850}
851
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000852StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000853 const char *Start = getTok().getLoc().getPointer();
854
Jim Grosbach4b905842013-09-20 23:08:21 +0000855 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000856 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000857
858 const char *End = getTok().getLoc().getPointer();
859 return StringRef(Start, End - Start);
860}
Chris Lattner78db3622009-06-22 05:51:26 +0000861
Jim Grosbach4b905842013-09-20 23:08:21 +0000862StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000863 const char *Start = getTok().getLoc().getPointer();
864
865 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000866 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000867 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000868
869 const char *End = getTok().getLoc().getPointer();
870 return StringRef(Start, End - Start);
871}
872
Jim Grosbach4b905842013-09-20 23:08:21 +0000873/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000874/// NOTE: This assumes the leading '(' has already been consumed.
875///
876/// parenexpr ::= expr)
877///
Jim Grosbach4b905842013-09-20 23:08:21 +0000878bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
879 if (parseExpression(Res))
880 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000881 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +0000882 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000883 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000884 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +0000885 return false;
886}
Chris Lattner78db3622009-06-22 05:51:26 +0000887
Jim Grosbach4b905842013-09-20 23:08:21 +0000888/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000889/// NOTE: This assumes the leading '[' has already been consumed.
890///
891/// bracketexpr ::= expr]
892///
Jim Grosbach4b905842013-09-20 23:08:21 +0000893bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
894 if (parseExpression(Res))
895 return true;
Nirav Davea645433c2016-07-18 15:24:03 +0000896 EndLoc = getTok().getEndLoc();
897 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
898 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000899 return false;
900}
901
Jim Grosbach4b905842013-09-20 23:08:21 +0000902/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000903/// primaryexpr ::= (parenexpr
904/// primaryexpr ::= symbol
905/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +0000906/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +0000907/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +0000908bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000909 SMLoc FirstTokenLoc = getLexer().getLoc();
910 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
911 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +0000912 default:
913 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +0000914 // If we have an error assume that we've already handled it.
915 case AsmToken::Error:
916 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000917 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000918 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000919 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000920 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000921 Res = MCUnaryExpr::createLNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000922 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +0000923 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +0000924 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +0000925 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +0000926 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +0000927 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000928 if (parseIdentifier(Identifier)) {
Nirav Daved0463322016-10-12 13:58:07 +0000929 // We may have failed but $ may be a valid token.
930 if (getTok().is(AsmToken::Dollar)) {
David Majnemer0c58bc62013-09-25 10:47:21 +0000931 if (Lexer.getMAI().getDollarIsPC()) {
Nirav Daved0463322016-10-12 13:58:07 +0000932 Lex();
David Majnemer0c58bc62013-09-25 10:47:21 +0000933 // This is a '$' reference, which references the current PC. Emit a
934 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000935 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +0000936 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000937 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +0000938 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +0000939 EndLoc = FirstTokenLoc;
940 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +0000941 }
942 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +0000943 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000944 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000945 // Parse symbol variant
946 std::pair<StringRef, StringRef> Split;
947 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +0000948 if (FirstTokenKind == AsmToken::String) {
949 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +0000950 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +0000951 SMLoc AtLoc = getLexer().getLoc();
952 StringRef VName;
953 if (parseIdentifier(VName))
954 return Error(AtLoc, "expected symbol variant after '@'");
955
956 Split = std::make_pair(Identifier, VName);
957 }
958 } else {
959 Split = Identifier.split('@');
960 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000961 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +0000962 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +0000963 StringRef VName;
964 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +0000965 // eat ')'.
966 if (parseToken(AsmToken::RParen,
967 "unexpected token in variant, expected ')'"))
968 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +0000969 Split = std::make_pair(Identifier, VName);
970 }
Daniel Dunbar24764322010-08-24 19:13:42 +0000971
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000972 EndLoc = SMLoc::getFromPointer(Identifier.end());
973
Daniel Dunbard20cda02009-10-16 01:34:54 +0000974 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +0000975 StringRef SymbolName = Identifier;
976 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +0000977
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000978 // Lookup the symbol variant if used.
David Peixotto8ad70b32013-12-04 22:43:20 +0000979 if (Split.second.size()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000980 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +0000981 if (Variant != MCSymbolRefExpr::VK_Invalid) {
982 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +0000983 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +0000984 Variant = MCSymbolRefExpr::VK_None;
985 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +0000986 return Error(SMLoc::getFromPointer(Split.second.begin()),
987 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000988 }
989 }
Daniel Dunbar55992562010-03-15 23:51:06 +0000990
Jim Grosbach6f482002015-05-18 18:43:14 +0000991 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +0000992
Daniel Dunbard20cda02009-10-16 01:34:54 +0000993 // If this is an absolute variable reference, substitute it now to preserve
994 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +0000995 if (Sym->isVariable() &&
996 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +0000997 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +0000998 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +0000999
Vedant Kumar86dbd922015-08-31 17:44:53 +00001000 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +00001001 return false;
1002 }
1003
1004 // Otherwise create a symbol ref.
Jim Grosbach13760bd2015-05-30 01:25:56 +00001005 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Chris Lattner78db3622009-06-22 05:51:26 +00001006 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001007 }
David Woodhousef42a6662014-02-01 16:20:54 +00001008 case AsmToken::BigNum:
1009 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001010 case AsmToken::Integer: {
1011 SMLoc Loc = getTok().getLoc();
1012 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001013 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001014 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001015 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001016 // Look for 'b' or 'f' following an Integer as a directional label
1017 if (Lexer.getKind() == AsmToken::Identifier) {
1018 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001019 // Lookup the symbol variant if used.
1020 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1021 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1022 if (Split.first.size() != IDVal.size()) {
1023 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001024 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001025 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001026 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001027 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001028 if (IDVal == "f" || IDVal == "b") {
1029 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001030 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001031 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001032 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001033 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001034 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001035 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001036 Lex(); // Eat identifier.
1037 }
1038 }
Chris Lattner78db3622009-06-22 05:51:26 +00001039 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001040 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001041 case AsmToken::Real: {
1042 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001043 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001044 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001045 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001046 Lex(); // Eat token.
1047 return false;
1048 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001049 case AsmToken::Dot: {
1050 // This is a '.' reference, which references the current PC. Emit a
1051 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001052 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001053 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001054 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001055 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001056 Lex(); // Eat identifier.
1057 return false;
1058 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001059 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001060 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001061 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001062 case AsmToken::LBrac:
1063 if (!PlatformParser->HasBracketExpressions())
1064 return TokError("brackets expression not supported on this target");
1065 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001066 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001067 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001068 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001069 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001070 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001071 Res = MCUnaryExpr::createMinus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001072 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001073 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001074 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001075 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001076 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001077 Res = MCUnaryExpr::createPlus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001078 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001079 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001080 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001081 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001082 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001083 Res = MCUnaryExpr::createNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001084 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001085 // MIPS unary expression operators. The lexer won't generate these tokens if
1086 // MCAsmInfo::HasMipsExpressions is false for the target.
1087 case AsmToken::PercentCall16:
1088 case AsmToken::PercentCall_Hi:
1089 case AsmToken::PercentCall_Lo:
1090 case AsmToken::PercentDtprel_Hi:
1091 case AsmToken::PercentDtprel_Lo:
1092 case AsmToken::PercentGot:
1093 case AsmToken::PercentGot_Disp:
1094 case AsmToken::PercentGot_Hi:
1095 case AsmToken::PercentGot_Lo:
1096 case AsmToken::PercentGot_Ofst:
1097 case AsmToken::PercentGot_Page:
1098 case AsmToken::PercentGottprel:
1099 case AsmToken::PercentGp_Rel:
1100 case AsmToken::PercentHi:
1101 case AsmToken::PercentHigher:
1102 case AsmToken::PercentHighest:
1103 case AsmToken::PercentLo:
1104 case AsmToken::PercentNeg:
1105 case AsmToken::PercentPcrel_Hi:
1106 case AsmToken::PercentPcrel_Lo:
1107 case AsmToken::PercentTlsgd:
1108 case AsmToken::PercentTlsldm:
1109 case AsmToken::PercentTprel_Hi:
1110 case AsmToken::PercentTprel_Lo:
1111 Lex(); // Eat the operator.
1112 if (Lexer.isNot(AsmToken::LParen))
1113 return TokError("expected '(' after operator");
1114 Lex(); // Eat the operator.
1115 if (parseExpression(Res, EndLoc))
1116 return true;
1117 if (Lexer.isNot(AsmToken::RParen))
1118 return TokError("expected ')'");
1119 Lex(); // Eat the operator.
1120 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1121 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001122 }
1123}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001124
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001125bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001126 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001127 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001128}
1129
Daniel Dunbar55f16672010-09-17 02:47:07 +00001130const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001131AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001132 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001133 // Ask the target implementation about this expression first.
1134 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1135 if (NewE)
1136 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001137 // Recurse over the given expression, rebuilding it to apply the given variant
1138 // if there is exactly one symbol.
1139 switch (E->getKind()) {
1140 case MCExpr::Target:
1141 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001142 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001143
1144 case MCExpr::SymbolRef: {
1145 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1146
1147 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001148 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1149 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001150 return E;
1151 }
1152
Jim Grosbach13760bd2015-05-30 01:25:56 +00001153 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001154 }
1155
1156 case MCExpr::Unary: {
1157 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001158 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001159 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001160 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001161 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001162 }
1163
1164 case MCExpr::Binary: {
1165 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001166 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1167 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001168
1169 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001170 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001171
Jim Grosbach4b905842013-09-20 23:08:21 +00001172 if (!LHS)
1173 LHS = BE->getLHS();
1174 if (!RHS)
1175 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001176
Jim Grosbach13760bd2015-05-30 01:25:56 +00001177 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001178 }
1179 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001180
Craig Toppera2886c22012-02-07 05:05:23 +00001181 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001182}
1183
Jim Grosbach4b905842013-09-20 23:08:21 +00001184/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001185///
Jim Grosbachbd164242011-08-20 16:24:13 +00001186/// expr ::= expr &&,|| expr -> lowest.
1187/// expr ::= expr |,^,&,! expr
1188/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1189/// expr ::= expr <<,>> expr
1190/// expr ::= expr +,- expr
1191/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001192/// expr ::= primaryexpr
1193///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001194bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001195 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001196 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001197 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001198 return true;
1199
Daniel Dunbar55f16672010-09-17 02:47:07 +00001200 // As a special case, we support 'a op b @ modifier' by rewriting the
1201 // expression to include the modifier. This is inefficient, but in general we
1202 // expect users to use 'a@modifier op b'.
1203 if (Lexer.getKind() == AsmToken::At) {
1204 Lex();
1205
1206 if (Lexer.isNot(AsmToken::Identifier))
1207 return TokError("unexpected symbol modifier following '@'");
1208
1209 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001210 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001211 if (Variant == MCSymbolRefExpr::VK_Invalid)
1212 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1213
Jim Grosbach4b905842013-09-20 23:08:21 +00001214 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001215 if (!ModifiedRes) {
1216 return TokError("invalid modifier '" + getTok().getIdentifier() +
1217 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001218 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001219
Daniel Dunbar55f16672010-09-17 02:47:07 +00001220 Res = ModifiedRes;
1221 Lex();
1222 }
1223
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001224 // Try to constant fold it up front, if possible.
1225 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001226 if (Res->evaluateAsAbsolute(Value))
1227 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001228
1229 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001230}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001231
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001232bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001233 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001234 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001235}
1236
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001237bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1238 SMLoc &EndLoc) {
1239 if (parseParenExpr(Res, EndLoc))
1240 return true;
1241
1242 for (; ParenDepth > 0; --ParenDepth) {
1243 if (parseBinOpRHS(1, Res, EndLoc))
1244 return true;
1245
1246 // We don't Lex() the last RParen.
1247 // This is the same behavior as parseParenExpression().
1248 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001249 EndLoc = getTok().getEndLoc();
1250 if (parseToken(AsmToken::RParen,
1251 "expected ')' in parentheses expression"))
1252 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001253 }
1254 }
1255 return false;
1256}
1257
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001258bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001259 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001260
Daniel Dunbar75630b32009-06-30 02:10:03 +00001261 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001262 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001263 return true;
1264
Jim Grosbach13760bd2015-05-30 01:25:56 +00001265 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001266 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001267
1268 return false;
1269}
1270
David Majnemer0993e0b2015-10-26 03:15:34 +00001271static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1272 MCBinaryExpr::Opcode &Kind,
1273 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001274 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001275 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001276 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001277
Jim Grosbach4b905842013-09-20 23:08:21 +00001278 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001279 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001280 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001281 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001282 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001283 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001284 return 1;
1285
Jim Grosbach4b905842013-09-20 23:08:21 +00001286 // Low Precedence: |, &, ^
1287 //
1288 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001289 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001290 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001291 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001292 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001293 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001294 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001295 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001296 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001297 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001298
Jim Grosbach4b905842013-09-20 23:08:21 +00001299 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001300 case AsmToken::EqualEqual:
1301 Kind = MCBinaryExpr::EQ;
1302 return 3;
1303 case AsmToken::ExclaimEqual:
1304 case AsmToken::LessGreater:
1305 Kind = MCBinaryExpr::NE;
1306 return 3;
1307 case AsmToken::Less:
1308 Kind = MCBinaryExpr::LT;
1309 return 3;
1310 case AsmToken::LessEqual:
1311 Kind = MCBinaryExpr::LTE;
1312 return 3;
1313 case AsmToken::Greater:
1314 Kind = MCBinaryExpr::GT;
1315 return 3;
1316 case AsmToken::GreaterEqual:
1317 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001318 return 3;
1319
Jim Grosbach4b905842013-09-20 23:08:21 +00001320 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001321 case AsmToken::LessLess:
1322 Kind = MCBinaryExpr::Shl;
1323 return 4;
1324 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001325 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001326 return 4;
1327
Jim Grosbach4b905842013-09-20 23:08:21 +00001328 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001329 case AsmToken::Plus:
1330 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001331 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001332 case AsmToken::Minus:
1333 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001334 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001335
Jim Grosbach4b905842013-09-20 23:08:21 +00001336 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001337 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001338 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001339 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001340 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001341 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001342 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001343 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001344 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001345 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001346 }
1347}
1348
David Majnemer0993e0b2015-10-26 03:15:34 +00001349static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1350 MCBinaryExpr::Opcode &Kind,
1351 bool ShouldUseLogicalShr) {
1352 switch (K) {
1353 default:
1354 return 0; // not a binop.
1355
1356 // Lowest Precedence: &&, ||
1357 case AsmToken::AmpAmp:
1358 Kind = MCBinaryExpr::LAnd;
1359 return 2;
1360 case AsmToken::PipePipe:
1361 Kind = MCBinaryExpr::LOr;
1362 return 1;
1363
1364 // Low Precedence: ==, !=, <>, <, <=, >, >=
1365 case AsmToken::EqualEqual:
1366 Kind = MCBinaryExpr::EQ;
1367 return 3;
1368 case AsmToken::ExclaimEqual:
1369 case AsmToken::LessGreater:
1370 Kind = MCBinaryExpr::NE;
1371 return 3;
1372 case AsmToken::Less:
1373 Kind = MCBinaryExpr::LT;
1374 return 3;
1375 case AsmToken::LessEqual:
1376 Kind = MCBinaryExpr::LTE;
1377 return 3;
1378 case AsmToken::Greater:
1379 Kind = MCBinaryExpr::GT;
1380 return 3;
1381 case AsmToken::GreaterEqual:
1382 Kind = MCBinaryExpr::GTE;
1383 return 3;
1384
1385 // Low Intermediate Precedence: +, -
1386 case AsmToken::Plus:
1387 Kind = MCBinaryExpr::Add;
1388 return 4;
1389 case AsmToken::Minus:
1390 Kind = MCBinaryExpr::Sub;
1391 return 4;
1392
1393 // High Intermediate Precedence: |, &, ^
1394 //
1395 // FIXME: gas seems to support '!' as an infix operator?
1396 case AsmToken::Pipe:
1397 Kind = MCBinaryExpr::Or;
1398 return 5;
1399 case AsmToken::Caret:
1400 Kind = MCBinaryExpr::Xor;
1401 return 5;
1402 case AsmToken::Amp:
1403 Kind = MCBinaryExpr::And;
1404 return 5;
1405
1406 // Highest Precedence: *, /, %, <<, >>
1407 case AsmToken::Star:
1408 Kind = MCBinaryExpr::Mul;
1409 return 6;
1410 case AsmToken::Slash:
1411 Kind = MCBinaryExpr::Div;
1412 return 6;
1413 case AsmToken::Percent:
1414 Kind = MCBinaryExpr::Mod;
1415 return 6;
1416 case AsmToken::LessLess:
1417 Kind = MCBinaryExpr::Shl;
1418 return 6;
1419 case AsmToken::GreaterGreater:
1420 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1421 return 6;
1422 }
1423}
1424
1425unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1426 MCBinaryExpr::Opcode &Kind) {
1427 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1428 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1429 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1430}
1431
Jim Grosbach4b905842013-09-20 23:08:21 +00001432/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001433/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001434bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001435 SMLoc &EndLoc) {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001436 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001437 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001438 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001439
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001440 // If the next token is lower precedence than we are allowed to eat, return
1441 // successfully with what we ate already.
1442 if (TokPrec < Precedence)
1443 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001444
Sean Callanan686ed8d2010-01-19 20:22:31 +00001445 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001446
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001447 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001448 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001449 if (parsePrimaryExpr(RHS, EndLoc))
1450 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001451
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001452 // If BinOp binds less tightly with RHS than the operator after RHS, let
1453 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001454 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001455 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001456 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1457 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001458
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001459 // Merge LHS and RHS according to operator.
Jim Grosbach13760bd2015-05-30 01:25:56 +00001460 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001461 }
1462}
1463
Chris Lattner36e02122009-06-21 20:54:55 +00001464/// ParseStatement:
1465/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001466/// ::= Label* Directive ...Operands... EndOfStatement
1467/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001468bool AsmParser::parseStatement(ParseStatementInfo &Info,
1469 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001470 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001471 // Eat initial spaces and comments
1472 while (Lexer.is(AsmToken::Space))
1473 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001474 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001475 // if this is a line comment we can drop it safely
1476 if (getTok().getString().front() == '\r' ||
1477 getTok().getString().front() == '\n')
1478 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001479 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001480 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001481 }
Nirav Dave9263ae32016-08-02 19:17:54 +00001482 if (Lexer.is(AsmToken::Hash)) {
1483 // Seeing a hash here means that it was an end-of-line comment in
1484 // an asm syntax where hash's are not comment and the previous
1485 // statement parser did not check the end of statement. Relex as
1486 // EndOfStatement.
1487 StringRef CommentStr = parseStringToEndOfStatement();
1488 Lexer.Lex();
1489 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1490 return false;
1491 }
Nirav Davefd910412016-06-17 16:06:17 +00001492 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001493 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001494 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001495 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001496 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001497 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001498 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001499 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001500 if (Lexer.is(AsmToken::Integer)) {
1501 LocalLabelVal = getTok().getIntVal();
1502 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001503 if (!TheCondState.Ignore) {
1504 Lex(); // always eat a token
1505 return Error(IDLoc, "unexpected token at start of statement");
1506 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001507 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001508 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001509 IDVal = getTok().getString();
1510 Lex(); // Consume the integer token to be used as an identifier token.
1511 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001512 if (!TheCondState.Ignore) {
1513 Lex(); // always eat a token
1514 return Error(IDLoc, "unexpected token at start of statement");
1515 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001516 }
1517 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001518 } else if (Lexer.is(AsmToken::Dot)) {
1519 // Treat '.' as a valid identifier in this context.
1520 Lex();
1521 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001522 } else if (Lexer.is(AsmToken::LCurly)) {
1523 // Treat '{' as a valid identifier in this context.
1524 Lex();
1525 IDVal = "{";
1526
1527 } else if (Lexer.is(AsmToken::RCurly)) {
1528 // Treat '}' as a valid identifier in this context.
1529 Lex();
1530 IDVal = "}";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001531 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001532 if (!TheCondState.Ignore) {
1533 Lex(); // always eat a token
1534 return Error(IDLoc, "unexpected token at start of statement");
1535 }
Chris Lattner926885c2010-04-17 18:14:27 +00001536 IDVal = "";
1537 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001538
Chris Lattner926885c2010-04-17 18:14:27 +00001539 // Handle conditional assembly here before checking for skipping. We
1540 // have to do this so that .endif isn't skipped in a ".if 0" block for
1541 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001542 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001543 DirectiveKindMap.find(IDVal);
1544 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1545 ? DK_NO_DIRECTIVE
1546 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001547 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001548 default:
1549 break;
1550 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001551 case DK_IFEQ:
1552 case DK_IFGE:
1553 case DK_IFGT:
1554 case DK_IFLE:
1555 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001556 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001557 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001558 case DK_IFB:
1559 return parseDirectiveIfb(IDLoc, true);
1560 case DK_IFNB:
1561 return parseDirectiveIfb(IDLoc, false);
1562 case DK_IFC:
1563 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001564 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001565 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001566 case DK_IFNC:
1567 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001568 case DK_IFNES:
1569 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001570 case DK_IFDEF:
1571 return parseDirectiveIfdef(IDLoc, true);
1572 case DK_IFNDEF:
1573 case DK_IFNOTDEF:
1574 return parseDirectiveIfdef(IDLoc, false);
1575 case DK_ELSEIF:
1576 return parseDirectiveElseIf(IDLoc);
1577 case DK_ELSE:
1578 return parseDirectiveElse(IDLoc);
1579 case DK_ENDIF:
1580 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001581 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001582
Eli Bendersky88024712013-01-16 19:32:36 +00001583 // Ignore the statement if in the middle of inactive conditional
1584 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001585 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001586 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001587 return false;
1588 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001589
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001590 // FIXME: Recurse on local labels?
1591
1592 // See what kind of statement we have.
1593 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001594 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001595 if (!getTargetParser().isLabel(ID))
1596 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001597 if (checkForValidSection())
1598 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001599
Chris Lattner36e02122009-06-21 20:54:55 +00001600 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001601 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001602
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001603 // Diagnose attempt to use '.' as a label.
1604 if (IDVal == ".")
1605 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1606
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001607 // Diagnose attempt to use a variable as a label.
1608 //
1609 // FIXME: Diagnostics. Note the location of the definition as a label.
1610 // FIXME: This doesn't diagnose assignment to a symbol which has been
1611 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001612 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001613 if (LocalLabelVal == -1) {
1614 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001615 StringRef RewrittenLabel =
1616 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1617 assert(RewrittenLabel.size() &&
1618 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001619 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1620 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001621 IDVal = RewrittenLabel;
1622 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001623 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001624 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001625 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
David Majnemer58cb80c2014-12-24 10:27:50 +00001626
1627 Sym->redefineIfPossible();
1628
Daniel Dunbardeb7ba92010-05-05 19:01:00 +00001629 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001630 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencer530ce852010-10-09 11:00:50 +00001631
Nirav Dave9263ae32016-08-02 19:17:54 +00001632 // End of Labels should be treated as end of line for lexing
1633 // purposes but that information is not available to the Lexer who
1634 // does not understand Labels. This may cause us to see a Hash
1635 // here instead of a preprocessor line comment.
1636 if (getTok().is(AsmToken::Hash)) {
1637 StringRef CommentStr = parseStringToEndOfStatement();
1638 Lexer.Lex();
1639 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1640 }
1641
Nirav Dave8ea792d2016-07-13 14:03:12 +00001642 // Consume any end of statement token, if present, to avoid spurious
1643 // AddBlankLine calls().
1644 if (getTok().is(AsmToken::EndOfStatement)) {
1645 Lex();
1646 }
1647
Daniel Dunbare73b2672009-08-26 22:13:22 +00001648 // Emit the label.
Chad Rosierf3feab32013-01-07 20:34:12 +00001649 if (!ParsingInlineAsm)
1650 Out.EmitLabel(Sym);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001651
Kevin Enderbye7739d42011-12-09 18:09:40 +00001652 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001653 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001654 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001655 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1656 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001657
Tim Northover1744d0a2013-10-25 12:49:50 +00001658 getTargetParser().onLabelParsed(Sym);
1659
Eli Friedman0f4871d2012-10-22 23:58:19 +00001660 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001661 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001662
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001663 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001664 if (!getTargetParser().equalIsAsmAssignment())
1665 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001666 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001667 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001668
Jim Grosbach4b905842013-09-20 23:08:21 +00001669 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001670
1671 default: // Normal instruction or directive.
1672 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001673 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001674
1675 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001676 if (areMacrosEnabled())
1677 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1678 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001679 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001680
Michael J. Spencer530ce852010-10-09 11:00:50 +00001681 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001682
Eli Bendersky17233942013-01-15 22:59:42 +00001683 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001684 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001685 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001686 //
Eli Bendersky17233942013-01-15 22:59:42 +00001687 // 1. The target-specific assembly parser. Some directives are target
1688 // specific or may potentially behave differently on certain targets.
1689 // 2. Asm parser extensions. For example, platform-specific parsers
1690 // (like the ELF parser) register themselves as extensions.
1691 // 3. The generic directive parser implemented by this class. These are
1692 // all the directives that behave in a target and platform independent
1693 // manner, or at least have a default behavior that's shared between
1694 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001695
Oliver Stannard21718282016-07-26 14:19:47 +00001696 getTargetParser().flushPendingInstructions(getStreamer());
1697
Nirav Dave2364748a2016-09-16 18:30:20 +00001698 SMLoc StartTokLoc = getTok().getLoc();
1699 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1700
1701 if (hasPendingError())
1702 return true;
1703 // Currently the return value should be true if we are
1704 // uninterested but as this is at odds with the standard parsing
1705 // convention (return true = error) we have instances of a parsed
1706 // directive that fails returning true as an error. Catch these
1707 // cases as best as possible errors here.
1708 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1709 return true;
1710 // Return if we did some parsing or believe we succeeded.
1711 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001712 return false;
1713
Alp Tokercb402912014-01-24 17:20:08 +00001714 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001715 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001716 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1717 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001718 if (Handler.first)
1719 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1720
1721 // Finally, if no one else is interested in this directive, it must be
1722 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001723 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001724 default:
1725 break;
1726 case DK_SET:
1727 case DK_EQU:
1728 return parseDirectiveSet(IDVal, true);
1729 case DK_EQUIV:
1730 return parseDirectiveSet(IDVal, false);
1731 case DK_ASCII:
1732 return parseDirectiveAscii(IDVal, false);
1733 case DK_ASCIZ:
1734 case DK_STRING:
1735 return parseDirectiveAscii(IDVal, true);
1736 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001737 case DK_DC_B:
1738 return parseDirectiveValue(IDVal, 1);
1739 case DK_DC:
1740 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001741 case DK_SHORT:
1742 case DK_VALUE:
1743 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001744 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001745 case DK_LONG:
1746 case DK_INT:
1747 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001748 case DK_DC_L:
1749 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001750 case DK_QUAD:
1751 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001752 return parseDirectiveValue(IDVal, 8);
1753 case DK_DC_A:
1754 return parseDirectiveValue(IDVal,
1755 getContext().getAsmInfo()->getPointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001756 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001757 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001758 case DK_SINGLE:
1759 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001760 case DK_DC_S:
1761 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle);
Jim Grosbach4b905842013-09-20 23:08:21 +00001762 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001763 case DK_DC_D:
1764 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble);
Jim Grosbach4b905842013-09-20 23:08:21 +00001765 case DK_ALIGN: {
1766 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1767 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1768 }
1769 case DK_ALIGN32: {
1770 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1771 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1772 }
1773 case DK_BALIGN:
1774 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1775 case DK_BALIGNW:
1776 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1777 case DK_BALIGNL:
1778 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1779 case DK_P2ALIGN:
1780 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1781 case DK_P2ALIGNW:
1782 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1783 case DK_P2ALIGNL:
1784 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1785 case DK_ORG:
1786 return parseDirectiveOrg();
1787 case DK_FILL:
1788 return parseDirectiveFill();
1789 case DK_ZERO:
1790 return parseDirectiveZero();
1791 case DK_EXTERN:
1792 eatToEndOfStatement(); // .extern is the default, ignore it.
1793 return false;
1794 case DK_GLOBL:
1795 case DK_GLOBAL:
1796 return parseDirectiveSymbolAttribute(MCSA_Global);
1797 case DK_LAZY_REFERENCE:
1798 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1799 case DK_NO_DEAD_STRIP:
1800 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1801 case DK_SYMBOL_RESOLVER:
1802 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1803 case DK_PRIVATE_EXTERN:
1804 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1805 case DK_REFERENCE:
1806 return parseDirectiveSymbolAttribute(MCSA_Reference);
1807 case DK_WEAK_DEFINITION:
1808 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1809 case DK_WEAK_REFERENCE:
1810 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1811 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1812 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1813 case DK_COMM:
1814 case DK_COMMON:
1815 return parseDirectiveComm(/*IsLocal=*/false);
1816 case DK_LCOMM:
1817 return parseDirectiveComm(/*IsLocal=*/true);
1818 case DK_ABORT:
1819 return parseDirectiveAbort();
1820 case DK_INCLUDE:
1821 return parseDirectiveInclude();
1822 case DK_INCBIN:
1823 return parseDirectiveIncbin();
1824 case DK_CODE16:
1825 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001826 return TokError(Twine(IDVal) +
1827 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001828 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001829 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001830 case DK_IRP:
1831 return parseDirectiveIrp(IDLoc);
1832 case DK_IRPC:
1833 return parseDirectiveIrpc(IDLoc);
1834 case DK_ENDR:
1835 return parseDirectiveEndr(IDLoc);
1836 case DK_BUNDLE_ALIGN_MODE:
1837 return parseDirectiveBundleAlignMode();
1838 case DK_BUNDLE_LOCK:
1839 return parseDirectiveBundleLock();
1840 case DK_BUNDLE_UNLOCK:
1841 return parseDirectiveBundleUnlock();
1842 case DK_SLEB128:
1843 return parseDirectiveLEB128(true);
1844 case DK_ULEB128:
1845 return parseDirectiveLEB128(false);
1846 case DK_SPACE:
1847 case DK_SKIP:
1848 return parseDirectiveSpace(IDVal);
1849 case DK_FILE:
1850 return parseDirectiveFile(IDLoc);
1851 case DK_LINE:
1852 return parseDirectiveLine();
1853 case DK_LOC:
1854 return parseDirectiveLoc();
1855 case DK_STABS:
1856 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001857 case DK_CV_FILE:
1858 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001859 case DK_CV_FUNC_ID:
1860 return parseDirectiveCVFuncId();
1861 case DK_CV_INLINE_SITE_ID:
1862 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001863 case DK_CV_LOC:
1864 return parseDirectiveCVLoc();
1865 case DK_CV_LINETABLE:
1866 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00001867 case DK_CV_INLINE_LINETABLE:
1868 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00001869 case DK_CV_DEF_RANGE:
1870 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001871 case DK_CV_STRINGTABLE:
1872 return parseDirectiveCVStringTable();
1873 case DK_CV_FILECHECKSUMS:
1874 return parseDirectiveCVFileChecksums();
Jim Grosbach4b905842013-09-20 23:08:21 +00001875 case DK_CFI_SECTIONS:
1876 return parseDirectiveCFISections();
1877 case DK_CFI_STARTPROC:
1878 return parseDirectiveCFIStartProc();
1879 case DK_CFI_ENDPROC:
1880 return parseDirectiveCFIEndProc();
1881 case DK_CFI_DEF_CFA:
1882 return parseDirectiveCFIDefCfa(IDLoc);
1883 case DK_CFI_DEF_CFA_OFFSET:
1884 return parseDirectiveCFIDefCfaOffset();
1885 case DK_CFI_ADJUST_CFA_OFFSET:
1886 return parseDirectiveCFIAdjustCfaOffset();
1887 case DK_CFI_DEF_CFA_REGISTER:
1888 return parseDirectiveCFIDefCfaRegister(IDLoc);
1889 case DK_CFI_OFFSET:
1890 return parseDirectiveCFIOffset(IDLoc);
1891 case DK_CFI_REL_OFFSET:
1892 return parseDirectiveCFIRelOffset(IDLoc);
1893 case DK_CFI_PERSONALITY:
1894 return parseDirectiveCFIPersonalityOrLsda(true);
1895 case DK_CFI_LSDA:
1896 return parseDirectiveCFIPersonalityOrLsda(false);
1897 case DK_CFI_REMEMBER_STATE:
1898 return parseDirectiveCFIRememberState();
1899 case DK_CFI_RESTORE_STATE:
1900 return parseDirectiveCFIRestoreState();
1901 case DK_CFI_SAME_VALUE:
1902 return parseDirectiveCFISameValue(IDLoc);
1903 case DK_CFI_RESTORE:
1904 return parseDirectiveCFIRestore(IDLoc);
1905 case DK_CFI_ESCAPE:
1906 return parseDirectiveCFIEscape();
1907 case DK_CFI_SIGNAL_FRAME:
1908 return parseDirectiveCFISignalFrame();
1909 case DK_CFI_UNDEFINED:
1910 return parseDirectiveCFIUndefined(IDLoc);
1911 case DK_CFI_REGISTER:
1912 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00001913 case DK_CFI_WINDOW_SAVE:
1914 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00001915 case DK_MACROS_ON:
1916 case DK_MACROS_OFF:
1917 return parseDirectiveMacrosOnOff(IDVal);
1918 case DK_MACRO:
1919 return parseDirectiveMacro(IDLoc);
Nico Weber155dccd12014-07-24 17:08:39 +00001920 case DK_EXITM:
1921 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001922 case DK_ENDM:
1923 case DK_ENDMACRO:
1924 return parseDirectiveEndMacro(IDVal);
1925 case DK_PURGEM:
1926 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00001927 case DK_END:
1928 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00001929 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00001930 return parseDirectiveError(IDLoc, false);
1931 case DK_ERROR:
1932 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00001933 case DK_WARNING:
1934 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00001935 case DK_RELOC:
1936 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001937 case DK_DCB:
1938 case DK_DCB_W:
1939 return parseDirectiveDCB(IDVal, 2);
1940 case DK_DCB_B:
1941 return parseDirectiveDCB(IDVal, 1);
1942 case DK_DCB_D:
1943 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble);
1944 case DK_DCB_L:
1945 return parseDirectiveDCB(IDVal, 4);
1946 case DK_DCB_S:
1947 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle);
Petr Hosek731bb9c2016-08-23 21:34:53 +00001948 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001949 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00001950 return TokError(Twine(IDVal) +
1951 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00001952 case DK_DS:
1953 case DK_DS_W:
1954 return parseDirectiveDS(IDVal, 2);
1955 case DK_DS_B:
1956 return parseDirectiveDS(IDVal, 1);
1957 case DK_DS_D:
1958 return parseDirectiveDS(IDVal, 8);
1959 case DK_DS_L:
1960 case DK_DS_S:
1961 return parseDirectiveDS(IDVal, 4);
1962 case DK_DS_P:
1963 case DK_DS_X:
1964 return parseDirectiveDS(IDVal, 12);
Eli Friedman20b02642010-07-19 04:17:25 +00001965 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00001966
Jim Grosbach758e0cc2012-05-01 18:38:27 +00001967 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00001968 }
Chris Lattner36e02122009-06-21 20:54:55 +00001969
Chad Rosierc7f552c2013-02-12 21:33:51 +00001970 // __asm _emit or __asm __emit
1971 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1972 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001973 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00001974
1975 // __asm align
1976 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001977 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00001978
Michael Zuckerman02ecd432015-12-13 17:07:23 +00001979 if (ParsingInlineAsm && (IDVal == "even"))
1980 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00001981 if (checkForValidSection())
1982 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001983
Chris Lattner7cbfa442010-05-19 23:34:33 +00001984 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00001985 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00001986 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00001987 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
1988 Info.ParsedOperands);
1989 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00001990
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001991 // Dump the parsed representation, if requested.
1992 if (getShowParsedOperands()) {
1993 SmallString<256> Str;
1994 raw_svector_ostream OS(Str);
1995 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001996 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001997 if (i != 0)
1998 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001999 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002000 }
2001 OS << "]";
2002
Jim Grosbach4b905842013-09-20 23:08:21 +00002003 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002004 }
2005
Nirav Dave2364748a2016-09-16 18:30:20 +00002006 // Fail even if ParseInstruction erroneously returns false.
2007 if (hasPendingError() || ParseHadError)
2008 return true;
2009
Oliver Stannard8b273082014-06-19 15:52:37 +00002010 // If we are generating dwarf for the current section then generate a .loc
2011 // directive for the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002012 if (!ParseHadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002013 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002014 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002015 unsigned Line;
2016 if (ActiveMacros.empty())
2017 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2018 else
Frederic Riss16238d92015-06-25 21:57:33 +00002019 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2020 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002021
Eli Bendersky88024712013-01-16 19:32:36 +00002022 // If we previously parsed a cpp hash file line comment then make sure the
2023 // current Dwarf File is for the CppHashFilename if not then emit the
2024 // Dwarf File table for it and adjust the line number for the .loc.
Tim Northoverc0bef992016-04-13 19:46:54 +00002025 if (CppHashInfo.Filename.size()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002026 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002027 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002028 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002029
Jim Grosbach4b905842013-09-20 23:08:21 +00002030 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
2031 // cache with the different Loc from the call above we save the last
2032 // info we queried here with SrcMgr.FindLineNumber().
2033 unsigned CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002034 if (LastQueryIDLoc == CppHashInfo.Loc &&
2035 LastQueryBuffer == CppHashInfo.Buf)
Jim Grosbach4b905842013-09-20 23:08:21 +00002036 CppHashLocLineNo = LastQueryLine;
2037 else {
Tim Northoverc0bef992016-04-13 19:46:54 +00002038 CppHashLocLineNo =
2039 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002040 LastQueryLine = CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002041 LastQueryIDLoc = CppHashInfo.Loc;
2042 LastQueryBuffer = CppHashInfo.Buf;
Jim Grosbach4b905842013-09-20 23:08:21 +00002043 }
Tim Northoverc0bef992016-04-13 19:46:54 +00002044 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002045 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002046
Jim Grosbach4b905842013-09-20 23:08:21 +00002047 getStreamer().EmitDwarfLocDirective(
2048 getContext().getGenDwarfFileNumber(), Line, 0,
2049 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2050 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002051 }
2052
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002053 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002054 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002055 uint64_t ErrorInfo;
Nirav Dave2364748a2016-09-16 18:30:20 +00002056 if (getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
2057 Info.ParsedOperands, Out,
2058 ErrorInfo, ParsingInlineAsm))
2059 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002060 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002061 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002062}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002063
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002064// Parse and erase curly braces marking block start/end
2065bool
2066AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2067 // Identify curly brace marking block start/end
2068 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2069 return false;
2070
2071 SMLoc StartLoc = Lexer.getLoc();
2072 Lex(); // Eat the brace
2073 if (Lexer.is(AsmToken::EndOfStatement))
2074 Lex(); // Eat EndOfStatement following the brace
2075
2076 // Erase the block start/end brace from the output asm string
2077 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2078 StartLoc.getPointer());
2079 return true;
2080}
2081
Jim Grosbach4b905842013-09-20 23:08:21 +00002082/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002083/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002084bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002085 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002086 // Lexer only ever emits HashDirective if it fully formed if it's
2087 // done the checking already so this is an internal error.
2088 assert(getTok().is(AsmToken::Integer) &&
2089 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002090 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002091 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002092 assert(getTok().is(AsmToken::String) &&
2093 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002094 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002095 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002096
Kevin Enderby72553612011-09-13 23:45:18 +00002097 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002098 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002099
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002100 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002101 CppHashInfo.Loc = L;
2102 CppHashInfo.Filename = Filename;
2103 CppHashInfo.LineNumber = LineNumber;
2104 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002105 return false;
2106}
2107
Jim Grosbach4b905842013-09-20 23:08:21 +00002108/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002109/// for the Filename and LineNo if any in the diagnostic.
2110void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002111 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002112 raw_ostream &OS = errs();
2113
2114 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002115 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002116 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2117 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002118 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002119
Jim Grosbach4b905842013-09-20 23:08:21 +00002120 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002121 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002122 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2123 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2124 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002125 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2126 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002127 }
2128
Eric Christophera7c32732012-12-18 00:30:54 +00002129 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002130 // manager changed or buffer changed (like in a nested include) then just
2131 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002132 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002133 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002134 if (Parser->SavedDiagHandler)
2135 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2136 else
Craig Topper353eda42014-04-24 06:44:33 +00002137 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002138 return;
2139 }
2140
Eric Christophera7c32732012-12-18 00:30:54 +00002141 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002142 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2143 // for the diagnostic.
2144 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002145
2146 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2147 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002148 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002149 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002150 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002151
Jim Grosbach4b905842013-09-20 23:08:21 +00002152 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2153 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002154 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002155
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002156 if (Parser->SavedDiagHandler)
2157 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2158 else
Craig Topper353eda42014-04-24 06:44:33 +00002159 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002160}
2161
Rafael Espindola2c064482012-08-21 18:29:30 +00002162// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2163// difference being that that function accepts '@' as part of identifiers and
2164// we can't do that. AsmLexer.cpp should probably be changed to handle
2165// '@' as a special case when needed.
2166static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002167 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2168 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002169}
2170
Rafael Espindola34b9c512012-06-03 23:57:14 +00002171bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002172 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002173 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002174 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002175 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002176 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002177 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002178 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002179
Preston Gurd05500642012-09-19 20:36:12 +00002180 // A macro without parameters is handled differently on Darwin:
2181 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002182 while (!Body.empty()) {
2183 // Scan for the next substitution.
2184 std::size_t End = Body.size(), Pos = 0;
2185 for (; Pos != End; ++Pos) {
2186 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002187 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002188 // This macro has no parameters, look for $0, $1, etc.
2189 if (Body[Pos] != '$' || Pos + 1 == End)
2190 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002191
Rafael Espindola1134ab232011-06-05 02:43:45 +00002192 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002193 if (Next == '$' || Next == 'n' ||
2194 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002195 break;
2196 } else {
2197 // This macro has parameters, look for \foo, \bar, etc.
2198 if (Body[Pos] == '\\' && Pos + 1 != End)
2199 break;
2200 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002201 }
2202
2203 // Add the prefix.
2204 OS << Body.slice(0, Pos);
2205
2206 // Check if we reached the end.
2207 if (Pos == End)
2208 break;
2209
Benjamin Kramer513e7442014-02-20 13:36:32 +00002210 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002211 switch (Body[Pos + 1]) {
2212 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002213 case '$':
2214 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002215 break;
2216
Jim Grosbach4b905842013-09-20 23:08:21 +00002217 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002218 case 'n':
2219 OS << A.size();
2220 break;
2221
Jim Grosbach4b905842013-09-20 23:08:21 +00002222 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002223 default: {
2224 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002225 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002226 if (Index >= A.size())
2227 break;
2228
2229 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002230 for (const AsmToken &Token : A[Index])
2231 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002232 break;
2233 }
2234 }
2235 Pos += 2;
2236 } else {
2237 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002238
2239 // Check for the \@ pseudo-variable.
2240 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002241 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002242 else
2243 while (isIdentifierChar(Body[I]) && I + 1 != End)
2244 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002245
Jim Grosbach4b905842013-09-20 23:08:21 +00002246 const char *Begin = Body.data() + Pos + 1;
2247 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002248 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002249
Toma Tabacu217116e2015-04-27 10:50:29 +00002250 if (Argument == "@") {
2251 OS << NumOfMacroInstantiations;
2252 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002253 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002254 for (; Index < NParameters; ++Index)
2255 if (Parameters[Index].Name == Argument)
2256 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002257
Toma Tabacu217116e2015-04-27 10:50:29 +00002258 if (Index == NParameters) {
2259 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2260 Pos += 3;
2261 else {
2262 OS << '\\' << Argument;
2263 Pos = I;
2264 }
2265 } else {
2266 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002267 for (const AsmToken &Token : A[Index])
Toma Tabacu217116e2015-04-27 10:50:29 +00002268 // We expect no quotes around the string's contents when
2269 // parsing for varargs.
Craig Topper84008482015-10-10 05:38:14 +00002270 if (Token.getKind() != AsmToken::String || VarargParameter)
2271 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002272 else
Craig Topper84008482015-10-10 05:38:14 +00002273 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002274
2275 Pos += 1 + Argument.size();
2276 }
Preston Gurd05500642012-09-19 20:36:12 +00002277 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002278 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002279 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002280 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002281 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002282
Rafael Espindola1134ab232011-06-05 02:43:45 +00002283 return false;
2284}
Daniel Dunbar43235712010-07-18 18:54:11 +00002285
Nico Weber2a8f9222014-07-24 16:29:04 +00002286MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002287 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002288 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002289 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002290
Jim Grosbach4b905842013-09-20 23:08:21 +00002291static bool isOperator(AsmToken::TokenKind kind) {
2292 switch (kind) {
2293 default:
2294 return false;
2295 case AsmToken::Plus:
2296 case AsmToken::Minus:
2297 case AsmToken::Tilde:
2298 case AsmToken::Slash:
2299 case AsmToken::Star:
2300 case AsmToken::Dot:
2301 case AsmToken::Equal:
2302 case AsmToken::EqualEqual:
2303 case AsmToken::Pipe:
2304 case AsmToken::PipePipe:
2305 case AsmToken::Caret:
2306 case AsmToken::Amp:
2307 case AsmToken::AmpAmp:
2308 case AsmToken::Exclaim:
2309 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002310 case AsmToken::Less:
2311 case AsmToken::LessEqual:
2312 case AsmToken::LessLess:
2313 case AsmToken::LessGreater:
2314 case AsmToken::Greater:
2315 case AsmToken::GreaterEqual:
2316 case AsmToken::GreaterGreater:
2317 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002318 }
2319}
2320
David Majnemer16252452014-01-29 00:07:39 +00002321namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002322
David Majnemer16252452014-01-29 00:07:39 +00002323class AsmLexerSkipSpaceRAII {
2324public:
2325 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2326 Lexer.setSkipSpace(SkipSpace);
2327 }
2328
2329 ~AsmLexerSkipSpaceRAII() {
2330 Lexer.setSkipSpace(true);
2331 }
2332
2333private:
2334 AsmLexer &Lexer;
2335};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002336
2337} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002338
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002339bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2340
2341 if (Vararg) {
2342 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2343 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002344 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002345 }
2346 return false;
2347 }
2348
Rafael Espindola768b41c2012-06-15 14:02:34 +00002349 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002350
David Majnemer16252452014-01-29 00:07:39 +00002351 // Darwin doesn't use spaces to delmit arguments.
2352 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002353
Scott Egertona1fa68a2016-02-11 13:48:49 +00002354 bool SpaceEaten;
2355
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002356 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002357 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002358 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002359 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002360
Scott Egertona1fa68a2016-02-11 13:48:49 +00002361 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002362
Scott Egertona1fa68a2016-02-11 13:48:49 +00002363 if (Lexer.is(AsmToken::Comma))
2364 break;
2365
2366 if (Lexer.is(AsmToken::Space)) {
2367 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002368 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002369 }
Preston Gurd05500642012-09-19 20:36:12 +00002370
2371 // Spaces can delimit parameters, but could also be part an expression.
2372 // If the token after a space is an operator, add the token and the next
2373 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002374 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002375 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002376 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002377 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002378
Scott Egertona1fa68a2016-02-11 13:48:49 +00002379 // Whitespace after an operator can be ignored.
2380 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002381 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002382
2383 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002384 }
2385 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002386 if (SpaceEaten)
2387 break;
Preston Gurd05500642012-09-19 20:36:12 +00002388 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002389
Jim Grosbach4b905842013-09-20 23:08:21 +00002390 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002391 // to be able to fill in the remaining default parameter values
2392 if (Lexer.is(AsmToken::EndOfStatement))
2393 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002394
2395 // Adjust the current parentheses level.
2396 if (Lexer.is(AsmToken::LParen))
2397 ++ParenLevel;
2398 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2399 --ParenLevel;
2400
2401 // Append the token to the current argument list.
2402 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002403 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002404 }
Preston Gurd05500642012-09-19 20:36:12 +00002405
Rafael Espindola768b41c2012-06-15 14:02:34 +00002406 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002407 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002408 return false;
2409}
2410
2411// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002412bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002413 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002414 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002415 bool NamedParametersFound = false;
2416 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002417
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002418 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002419 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002420
Rafael Espindola768b41c2012-06-15 14:02:34 +00002421 // Parse two kinds of macro invocations:
2422 // - macros defined without any parameters accept an arbitrary number of them
2423 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002424 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002425 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2426 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002427 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002428 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002429
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002430 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002431 if (parseIdentifier(FA.Name))
2432 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002433
Nirav Dave2364748a2016-09-16 18:30:20 +00002434 if (Lexer.isNot(AsmToken::Equal))
2435 return TokError("expected '=' after formal parameter identifier");
2436
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002437 Lex();
2438
2439 NamedParametersFound = true;
2440 }
2441
Nirav Dave2364748a2016-09-16 18:30:20 +00002442 if (NamedParametersFound && FA.Name.empty())
2443 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002444
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002445 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2446 if (parseMacroArgument(FA.Value, Vararg))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002447 return true;
2448
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002449 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002450 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002451 unsigned FAI = 0;
2452 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002453 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002454 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002455
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002456 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002457 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002458 return Error(IDLoc, "parameter named '" + FA.Name +
2459 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002460 }
2461 PI = FAI;
2462 }
2463
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002464 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002465 if (A.size() <= PI)
2466 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002467 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002468
2469 if (FALocs.size() <= PI)
2470 FALocs.resize(PI + 1);
2471
2472 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002473 }
Jim Grosbach206661622012-07-30 22:44:17 +00002474
Preston Gurd242ed3152012-09-19 20:29:04 +00002475 // At the end of the statement, fill in remaining arguments that have
2476 // default values. If there aren't any, then the next argument is
2477 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002478 if (Lexer.is(AsmToken::EndOfStatement)) {
2479 bool Failure = false;
2480 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2481 if (A[FAI].empty()) {
2482 if (M->Parameters[FAI].Required) {
2483 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2484 "missing value for required parameter "
2485 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2486 Failure = true;
2487 }
2488
2489 if (!M->Parameters[FAI].Value.empty())
2490 A[FAI] = M->Parameters[FAI].Value;
2491 }
2492 }
2493 return Failure;
2494 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002495
2496 if (Lexer.is(AsmToken::Comma))
2497 Lex();
2498 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002499
2500 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002501}
2502
Jim Grosbach4b905842013-09-20 23:08:21 +00002503const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002504 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2505 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002506}
2507
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002508void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2509 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002510}
2511
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002512void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002513
Jim Grosbach4b905842013-09-20 23:08:21 +00002514bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002515 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2516 // eliminate this, although we should protect against infinite loops.
2517 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2518 if (ActiveMacros.size() == MaxNestingDepth) {
2519 std::ostringstream MaxNestingDepthError;
2520 MaxNestingDepthError << "macros cannot be nested more than "
2521 << MaxNestingDepth << " levels deep."
2522 << " Use -asm-macro-max-nesting-depth to increase "
2523 "this limit.";
2524 return TokError(MaxNestingDepthError.str());
2525 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002526
Eli Bendersky38274122013-01-14 23:22:36 +00002527 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002528 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002529 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002530
Rafael Espindola1134ab232011-06-05 02:43:45 +00002531 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2532 // to hold the macro body with substitutions.
2533 SmallString<256> Buf;
2534 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002535 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002536
Toma Tabacu217116e2015-04-27 10:50:29 +00002537 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002538 return true;
2539
Eli Bendersky38274122013-01-14 23:22:36 +00002540 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002541 // instantiation.
2542 OS << ".endmacro\n";
2543
Rafael Espindola3560ff22014-08-27 20:03:13 +00002544 std::unique_ptr<MemoryBuffer> Instantiation =
2545 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002546
Daniel Dunbar43235712010-07-18 18:54:11 +00002547 // Create the macro instantiation object and add to the current macro
2548 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002549 MacroInstantiation *MI = new MacroInstantiation(
2550 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002551 ActiveMacros.push_back(MI);
2552
Toma Tabacu217116e2015-04-27 10:50:29 +00002553 ++NumOfMacroInstantiations;
2554
Daniel Dunbar43235712010-07-18 18:54:11 +00002555 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002556 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002557 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002558 Lex();
2559
2560 return false;
2561}
2562
Jim Grosbach4b905842013-09-20 23:08:21 +00002563void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002564 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002565 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002566 Lex();
2567
2568 // Pop the instantiation entry.
2569 delete ActiveMacros.back();
2570 ActiveMacros.pop_back();
2571}
2572
Jim Grosbach4b905842013-09-20 23:08:21 +00002573bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002574 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002575 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002576 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002577 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2578 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002579 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002580
Pete Cooper80d21cb2015-06-22 19:35:57 +00002581 if (!Sym) {
2582 // In the case where we parse an expression starting with a '.', we will
2583 // not generate an error, nor will we create a symbol. In this case we
2584 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002585 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002586 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002587
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002588 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002589 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002590 if (NoDeadStrip)
2591 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2592
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002593 return false;
2594}
2595
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002596/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002597/// ::= identifier
2598/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002599bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002600 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002601 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2602 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002603 // handle this as a context dependent token, instead we detect adjacent tokens
2604 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002605 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2606 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002607
Hans Wennborgce69d772013-10-18 20:46:28 +00002608 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002609
2610 AsmToken Buf[1];
2611 Lexer.peekTokens(Buf, false);
2612
2613 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002614 return true;
2615
Hans Wennborgce69d772013-10-18 20:46:28 +00002616 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002617 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002618 return true;
2619
Nirav Daved0463322016-10-12 13:58:07 +00002620 // eat $ or @
2621 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002622 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002623 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002624 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002625 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002626 return false;
2627 }
2628
Jim Grosbach4b905842013-09-20 23:08:21 +00002629 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002630 return true;
2631
Sean Callanan936b0d32010-01-19 21:44:56 +00002632 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002633
Sean Callanan686ed8d2010-01-19 20:22:31 +00002634 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002635
2636 return false;
2637}
2638
Jim Grosbach4b905842013-09-20 23:08:21 +00002639/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002640/// ::= .equ identifier ',' expression
2641/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002642/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002643bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002644 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002645 if (check(parseIdentifier(Name), "expected identifier") ||
2646 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2647 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2648 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002649}
2650
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002651bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002652 if (check(getTok().isNot(AsmToken::String), "expected string"))
2653 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002654
2655 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002656 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002657 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2658 if (Str[i] != '\\') {
2659 Data += Str[i];
2660 continue;
2661 }
2662
2663 // Recognize escaped characters. Note that this escape semantics currently
2664 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2665 ++i;
2666 if (i == e)
2667 return TokError("unexpected backslash at end of string");
2668
2669 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002670 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002671 // Consume up to three octal characters.
2672 unsigned Value = Str[i] - '0';
2673
Jim Grosbach4b905842013-09-20 23:08:21 +00002674 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002675 ++i;
2676 Value = Value * 8 + (Str[i] - '0');
2677
Jim Grosbach4b905842013-09-20 23:08:21 +00002678 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002679 ++i;
2680 Value = Value * 8 + (Str[i] - '0');
2681 }
2682 }
2683
2684 if (Value > 255)
2685 return TokError("invalid octal escape sequence (out of range)");
2686
Jim Grosbach4b905842013-09-20 23:08:21 +00002687 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002688 continue;
2689 }
2690
2691 // Otherwise recognize individual escapes.
2692 switch (Str[i]) {
2693 default:
2694 // Just reject invalid escape sequences for now.
2695 return TokError("invalid escape sequence (unrecognized character)");
2696
2697 case 'b': Data += '\b'; break;
2698 case 'f': Data += '\f'; break;
2699 case 'n': Data += '\n'; break;
2700 case 'r': Data += '\r'; break;
2701 case 't': Data += '\t'; break;
2702 case '"': Data += '"'; break;
2703 case '\\': Data += '\\'; break;
2704 }
2705 }
2706
Nirav Davea645433c2016-07-18 15:24:03 +00002707 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002708 return false;
2709}
2710
Jim Grosbach4b905842013-09-20 23:08:21 +00002711/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002712/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002713bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002714 auto parseOp = [&]() -> bool {
2715 std::string Data;
2716 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002717 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002718 getStreamer().EmitBytes(Data);
2719 if (ZeroTerminated)
2720 getStreamer().EmitBytes(StringRef("\0", 1));
2721 return false;
2722 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002723
Nirav Dave1a9044b2016-10-24 14:35:29 +00002724 if (parseMany(parseOp))
2725 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002726 return false;
2727}
2728
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002729/// parseDirectiveReloc
2730/// ::= .reloc expression , identifier [ , expression ]
2731bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2732 const MCExpr *Offset;
2733 const MCExpr *Expr = nullptr;
2734
2735 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00002736 int64_t OffsetValue;
2737 // We can only deal with constant expressions at the moment.
2738
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002739 if (parseExpression(Offset))
2740 return true;
2741
Nirav Davea645433c2016-07-18 15:24:03 +00002742 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2743 "expression is not a constant value") ||
2744 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2745 parseToken(AsmToken::Comma, "expected comma") ||
2746 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2747 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002748
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002749 SMLoc NameLoc = Lexer.getTok().getLoc();
2750 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002751 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002752
2753 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002754 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002755 SMLoc ExprLoc = Lexer.getLoc();
2756 if (parseExpression(Expr))
2757 return true;
2758
2759 MCValue Value;
2760 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2761 return Error(ExprLoc, "expression must be relocatable");
2762 }
2763
Nirav Davea645433c2016-07-18 15:24:03 +00002764 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002765 "unexpected token in .reloc directive"))
2766 return true;
2767
2768 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2769 return Error(NameLoc, "unknown relocation name");
2770
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002771 return false;
2772}
2773
Jim Grosbach4b905842013-09-20 23:08:21 +00002774/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002775/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002776bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2777 auto parseOp = [&]() -> bool {
2778 const MCExpr *Value;
2779 SMLoc ExprLoc = getLexer().getLoc();
2780 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002781 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002782 // Special case constant expressions to match code generator.
2783 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2784 assert(Size <= 8 && "Invalid size");
2785 uint64_t IntValue = MCE->getValue();
2786 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2787 return Error(ExprLoc, "out of range literal value");
2788 getStreamer().EmitIntValue(IntValue, Size);
2789 } else
2790 getStreamer().EmitValue(Value, Size, ExprLoc);
2791 return false;
2792 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002793
Nirav Dave1a9044b2016-10-24 14:35:29 +00002794 if (parseMany(parseOp))
2795 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002796 return false;
2797}
2798
David Woodhoused6de0d92014-02-01 16:20:59 +00002799/// ParseDirectiveOctaValue
2800/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002801
2802bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
2803 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00002804 if (checkForValidSection())
2805 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002806 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
2807 return TokError("unknown token in expression");
2808 SMLoc ExprLoc = getTok().getLoc();
2809 APInt IntValue = getTok().getAPIntVal();
2810 uint64_t hi, lo;
2811 Lex();
2812 if (!IntValue.isIntN(128))
2813 return Error(ExprLoc, "out of range literal value");
2814 if (!IntValue.isIntN(64)) {
2815 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2816 lo = IntValue.getLoBits(64).getZExtValue();
2817 } else {
2818 hi = 0;
2819 lo = IntValue.getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002820 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00002821 if (MAI.isLittleEndian()) {
2822 getStreamer().EmitIntValue(lo, 8);
2823 getStreamer().EmitIntValue(hi, 8);
2824 } else {
2825 getStreamer().EmitIntValue(hi, 8);
2826 getStreamer().EmitIntValue(lo, 8);
2827 }
2828 return false;
2829 };
David Woodhoused6de0d92014-02-01 16:20:59 +00002830
Nirav Dave1a9044b2016-10-24 14:35:29 +00002831 if (parseMany(parseOp))
2832 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00002833 return false;
2834}
2835
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002836bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
2837 // We don't truly support arithmetic on floating point expressions, so we
2838 // have to manually parse unary prefixes.
2839 bool IsNeg = false;
2840 if (getLexer().is(AsmToken::Minus)) {
2841 Lexer.Lex();
2842 IsNeg = true;
2843 } else if (getLexer().is(AsmToken::Plus))
2844 Lexer.Lex();
2845
2846 if (Lexer.is(AsmToken::Error))
2847 return TokError(Lexer.getErr());
2848 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
2849 Lexer.isNot(AsmToken::Identifier))
2850 return TokError("unexpected token in directive");
2851
2852 // Convert to an APFloat.
2853 APFloat Value(Semantics);
2854 StringRef IDVal = getTok().getString();
2855 if (getLexer().is(AsmToken::Identifier)) {
2856 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2857 Value = APFloat::getInf(Semantics);
2858 else if (!IDVal.compare_lower("nan"))
2859 Value = APFloat::getNaN(Semantics, false, ~0);
2860 else
2861 return TokError("invalid floating point literal");
2862 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2863 APFloat::opInvalidOp)
2864 return TokError("invalid floating point literal");
2865 if (IsNeg)
2866 Value.changeSign();
2867
2868 // Consume the numeric token.
2869 Lex();
2870
2871 Res = Value.bitcastToAPInt();
2872
2873 return false;
2874}
2875
Jim Grosbach4b905842013-09-20 23:08:21 +00002876/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00002877/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002878bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
2879 const fltSemantics &Semantics) {
2880 auto parseOp = [&]() -> bool {
2881 APInt AsInt;
2882 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002883 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002884 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2885 AsInt.getBitWidth() / 8);
2886 return false;
2887 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00002888
Nirav Dave1a9044b2016-10-24 14:35:29 +00002889 if (parseMany(parseOp))
2890 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00002891 return false;
2892}
2893
Jim Grosbach4b905842013-09-20 23:08:21 +00002894/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00002895/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002896bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00002897 SMLoc NumBytesLoc = Lexer.getLoc();
2898 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00002899 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00002900 return true;
2901
Rafael Espindolab91bac62010-10-05 19:42:57 +00002902 int64_t Val = 0;
2903 if (getLexer().is(AsmToken::Comma)) {
2904 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002905 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00002906 return true;
2907 }
2908
Nirav Davea645433c2016-07-18 15:24:03 +00002909 if (parseToken(AsmToken::EndOfStatement,
2910 "unexpected token in '.zero' directive"))
2911 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00002912 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00002913
2914 return false;
2915}
2916
Jim Grosbach4b905842013-09-20 23:08:21 +00002917/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00002918/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002919bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00002920 SMLoc NumValuesLoc = Lexer.getLoc();
2921 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00002922 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002923 return true;
2924
Roman Divackye33098f2013-09-24 17:44:41 +00002925 int64_t FillSize = 1;
2926 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002927
David Majnemer522d3db2014-02-01 07:19:38 +00002928 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002929
Nirav Dave1a9044b2016-10-24 14:35:29 +00002930 if (parseOptionalToken(AsmToken::Comma)) {
2931 SizeLoc = getTok().getLoc();
2932 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00002933 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002934 if (parseOptionalToken(AsmToken::Comma)) {
2935 ExprLoc = getTok().getLoc();
2936 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00002937 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00002938 }
2939 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00002940 if (parseToken(AsmToken::EndOfStatement,
2941 "unexpected token in '.fill' directive"))
2942 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002943
David Majnemer522d3db2014-02-01 07:19:38 +00002944 if (FillSize < 0) {
2945 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00002946 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00002947 }
2948 if (FillSize > 8) {
2949 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2950 FillSize = 8;
2951 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002952
David Majnemer522d3db2014-02-01 07:19:38 +00002953 if (!isUInt<32>(FillExpr) && FillSize > 4)
2954 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2955
Petr Hosek67a94a72016-05-28 05:57:48 +00002956 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002957
2958 return false;
2959}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002960
Jim Grosbach4b905842013-09-20 23:08:21 +00002961/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002962/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002963bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002964 const MCExpr *Offset;
Nirav Davef43cc9f2016-10-10 15:24:54 +00002965 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002966 return true;
2967
2968 // Parse optional fill expression.
2969 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002970 if (parseOptionalToken(AsmToken::Comma))
2971 if (parseAbsoluteExpression(FillExpr))
2972 return addErrorSuffix(" in '.org' directive");
2973 if (parseToken(AsmToken::EndOfStatement))
2974 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00002975
Rafael Espindola7ae65d82015-11-04 23:59:18 +00002976 getStreamer().emitValueToOffset(Offset, FillExpr);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002977 return false;
2978}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002979
Jim Grosbach4b905842013-09-20 23:08:21 +00002980/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002981/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00002982bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002983 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002984 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002985 SMLoc MaxBytesLoc;
2986 bool HasFillExpr = false;
2987 int64_t FillExpr = 0;
2988 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002989
2990 auto parseAlign = [&]() -> bool {
2991 if (checkForValidSection() || parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00002992 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002993 if (parseOptionalToken(AsmToken::Comma)) {
2994 // The fill expression can be omitted while specifying a maximum number of
2995 // alignment bytes, e.g:
2996 // .align 3,,4
2997 if (getTok().isNot(AsmToken::Comma)) {
2998 HasFillExpr = true;
2999 if (parseAbsoluteExpression(FillExpr))
3000 return true;
3001 }
3002 if (parseOptionalToken(AsmToken::Comma))
3003 if (parseTokenLoc(MaxBytesLoc) ||
3004 parseAbsoluteExpression(MaxBytesToFill))
3005 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003006 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003007 return parseToken(AsmToken::EndOfStatement);
3008 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003009
Nirav Dave1a9044b2016-10-24 14:35:29 +00003010 if (parseAlign())
3011 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003012
Nirav Dave2364748a2016-09-16 18:30:20 +00003013 // Always emit an alignment here even if we thrown an error.
3014 bool ReturnVal = false;
3015
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003016 // Compute alignment in bytes.
3017 if (IsPow2) {
3018 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003019 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003020 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003021 Alignment = 31;
3022 }
3023
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003024 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003025 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003026 // Reject alignments that aren't either a power of two or zero,
3027 // for gas compatibility. Alignment of zero is silently rounded
3028 // up to one.
3029 if (Alignment == 0)
3030 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003031 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003032 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003033 }
3034
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003035 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003036 if (MaxBytesLoc.isValid()) {
3037 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003038 ReturnVal |= Error(MaxBytesLoc,
3039 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003040 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003041 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003042 }
3043
3044 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003045 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003046 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003047 MaxBytesToFill = 0;
3048 }
3049 }
3050
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003051 // Check whether we should use optimal code alignment for this .align
3052 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003053 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003054 assert(Section && "must have section to emit alignment");
3055 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003056 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3057 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003058 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003059 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003060 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003061 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3062 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003063 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003064
Nirav Dave2364748a2016-09-16 18:30:20 +00003065 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003066}
3067
Jim Grosbach4b905842013-09-20 23:08:21 +00003068/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00003069/// ::= .file [number] filename
3070/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00003071bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003072 // FIXME: I'm not sure what this is.
3073 int64_t FileNumber = -1;
3074 SMLoc FileNumberLoc = getLexer().getLoc();
3075 if (getLexer().is(AsmToken::Integer)) {
3076 FileNumber = getTok().getIntVal();
3077 Lex();
3078
3079 if (FileNumber < 1)
3080 return TokError("file number less than one");
3081 }
3082
Nirav Davea645433c2016-07-18 15:24:03 +00003083 std::string Path = getTok().getString();
Eli Bendersky17233942013-01-15 22:59:42 +00003084
3085 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003086 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003087 if (check(getTok().isNot(AsmToken::String),
3088 "unexpected token in '.file' directive") ||
3089 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003090 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003091
3092 StringRef Directory;
3093 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003094 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003095 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003096 if (check(FileNumber == -1,
3097 "explicit path specified, but no file number") ||
3098 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003099 return true;
3100 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003101 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003102 } else {
3103 Filename = Path;
3104 }
3105
Nirav Davea645433c2016-07-18 15:24:03 +00003106 if (parseToken(AsmToken::EndOfStatement,
3107 "unexpected token in '.file' directive"))
3108 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003109
3110 if (FileNumber == -1)
3111 getStreamer().EmitFileDirective(Filename);
3112 else {
David Blaikie22748082016-05-26 00:22:26 +00003113 // If there is -g option as well as debug info from directive file,
3114 // we turn off -g option, directly use the existing debug info instead.
David Blaikiedc3f01e2015-03-09 01:57:13 +00003115 if (getContext().getGenDwarfForAssembly())
David Blaikie22748082016-05-26 00:22:26 +00003116 getContext().setGenDwarfForAssembly(false);
3117 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
David Blaikiec714ef42014-03-17 01:52:11 +00003118 0)
Nirav Dave2364748a2016-09-16 18:30:20 +00003119 return Error(FileNumberLoc, "file number already allocated");
Eli Bendersky17233942013-01-15 22:59:42 +00003120 }
3121
3122 return false;
3123}
3124
Jim Grosbach4b905842013-09-20 23:08:21 +00003125/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003126/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003127bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003128 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003129 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003130 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3131 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003132 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003133 // FIXME: Do something with the .line.
3134 }
Nirav Davea645433c2016-07-18 15:24:03 +00003135 if (parseToken(AsmToken::EndOfStatement,
3136 "unexpected token in '.line' directive"))
3137 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003138
3139 return false;
3140}
3141
Jim Grosbach4b905842013-09-20 23:08:21 +00003142/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003143/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3144/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3145/// The first number is a file number, must have been previously assigned with
3146/// a .file directive, the second number is the line number and optionally the
3147/// third number is a column position (zero if not specified). The remaining
3148/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003149bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003150 int64_t FileNumber = 0, LineNumber = 0;
3151 SMLoc Loc = getTok().getLoc();
3152 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3153 check(FileNumber < 1, Loc,
3154 "file number less than one in '.loc' directive") ||
3155 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3156 "unassigned file number in '.loc' directive"))
3157 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003158
Nirav Davea645433c2016-07-18 15:24:03 +00003159 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003160 if (getLexer().is(AsmToken::Integer)) {
3161 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003162 if (LineNumber < 0)
3163 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003164 Lex();
3165 }
3166
3167 int64_t ColumnPos = 0;
3168 if (getLexer().is(AsmToken::Integer)) {
3169 ColumnPos = getTok().getIntVal();
3170 if (ColumnPos < 0)
3171 return TokError("column position less than zero in '.loc' directive");
3172 Lex();
3173 }
3174
3175 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3176 unsigned Isa = 0;
3177 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003178
Nirav Dave1a9044b2016-10-24 14:35:29 +00003179 auto parseLocOp = [&]() -> bool {
3180 StringRef Name;
3181 SMLoc Loc = getTok().getLoc();
3182 if (parseIdentifier(Name))
3183 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003184
Nirav Dave1a9044b2016-10-24 14:35:29 +00003185 if (Name == "basic_block")
3186 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3187 else if (Name == "prologue_end")
3188 Flags |= DWARF2_FLAG_PROLOGUE_END;
3189 else if (Name == "epilogue_begin")
3190 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3191 else if (Name == "is_stmt") {
3192 Loc = getTok().getLoc();
3193 const MCExpr *Value;
3194 if (parseExpression(Value))
3195 return true;
3196 // The expression must be the constant 0 or 1.
3197 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3198 int Value = MCE->getValue();
3199 if (Value == 0)
3200 Flags &= ~DWARF2_FLAG_IS_STMT;
3201 else if (Value == 1)
3202 Flags |= DWARF2_FLAG_IS_STMT;
3203 else
3204 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003205 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003206 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003207 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003208 } else if (Name == "isa") {
3209 Loc = getTok().getLoc();
3210 const MCExpr *Value;
3211 if (parseExpression(Value))
3212 return true;
3213 // The expression must be a constant greater or equal to 0.
3214 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3215 int Value = MCE->getValue();
3216 if (Value < 0)
3217 return Error(Loc, "isa number less than zero");
3218 Isa = Value;
3219 } else {
3220 return Error(Loc, "isa number not a constant value");
3221 }
3222 } else if (Name == "discriminator") {
3223 if (parseAbsoluteExpression(Discriminator))
3224 return true;
3225 } else {
3226 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003227 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003228 return false;
3229 };
3230
Nirav Davee2369aa2016-10-26 17:28:58 +00003231 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003232 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003233
3234 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3235 Isa, Discriminator, StringRef());
3236
3237 return false;
3238}
3239
Jim Grosbach4b905842013-09-20 23:08:21 +00003240/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003241/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003242bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003243 return TokError("unsupported directive '.stabs'");
3244}
3245
Reid Kleckner2214ed82016-01-29 00:49:42 +00003246/// parseDirectiveCVFile
3247/// ::= .cv_file number filename
3248bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003249 SMLoc FileNumberLoc = getTok().getLoc();
3250 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003251 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00003252
3253 if (parseIntToken(FileNumber,
3254 "expected file number in '.cv_file' directive") ||
3255 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3256 check(getTok().isNot(AsmToken::String),
3257 "unexpected token in '.cv_file' directive") ||
3258 // Usually directory and filename are together, otherwise just
3259 // directory. Allow the strings to have escaped octal character sequence.
3260 parseEscapedString(Filename) ||
3261 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00003262 "unexpected token in '.cv_file' directive"))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003263 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00003264
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003265 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003266 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003267
3268 return false;
3269}
3270
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003271bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3272 StringRef DirectiveName) {
3273 SMLoc Loc;
3274 return parseTokenLoc(Loc) ||
3275 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3276 "' directive") ||
3277 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3278 "expected function id within range [0, UINT_MAX)");
3279}
3280
3281bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3282 SMLoc Loc;
3283 return parseTokenLoc(Loc) ||
3284 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3285 "' directive") ||
3286 check(FileNumber < 1, Loc, "file number less than one in '" +
3287 DirectiveName + "' directive") ||
3288 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3289 "unassigned file number in '" + DirectiveName + "' directive");
3290}
3291
3292/// parseDirectiveCVFuncId
3293/// ::= .cv_func_id FunctionId
3294///
3295/// Introduces a function ID that can be used with .cv_loc.
3296bool AsmParser::parseDirectiveCVFuncId() {
3297 SMLoc FunctionIdLoc = getTok().getLoc();
3298 int64_t FunctionId;
3299
3300 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3301 parseToken(AsmToken::EndOfStatement,
3302 "unexpected token in '.cv_func_id' directive"))
3303 return true;
3304
3305 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003306 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003307
3308 return false;
3309}
3310
3311/// parseDirectiveCVInlineSiteId
3312/// ::= .cv_inline_site_id FunctionId
3313/// "within" IAFunc
3314/// "inlined_at" IAFile IALine [IACol]
3315///
3316/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3317/// at" source location information for use in the line table of the caller,
3318/// whether the caller is a real function or another inlined call site.
3319bool AsmParser::parseDirectiveCVInlineSiteId() {
3320 SMLoc FunctionIdLoc = getTok().getLoc();
3321 int64_t FunctionId;
3322 int64_t IAFunc;
3323 int64_t IAFile;
3324 int64_t IALine;
3325 int64_t IACol = 0;
3326
3327 // FunctionId
3328 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3329 return true;
3330
3331 // "within"
3332 if (check((getLexer().isNot(AsmToken::Identifier) ||
3333 getTok().getIdentifier() != "within"),
3334 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3335 return true;
3336 Lex();
3337
3338 // IAFunc
3339 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3340 return true;
3341
3342 // "inlined_at"
3343 if (check((getLexer().isNot(AsmToken::Identifier) ||
3344 getTok().getIdentifier() != "inlined_at"),
3345 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3346 "directive") )
3347 return true;
3348 Lex();
3349
3350 // IAFile IALine
3351 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3352 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3353 return true;
3354
3355 // [IACol]
3356 if (getLexer().is(AsmToken::Integer)) {
3357 IACol = getTok().getIntVal();
3358 Lex();
3359 }
3360
3361 if (parseToken(AsmToken::EndOfStatement,
3362 "unexpected token in '.cv_inline_site_id' directive"))
3363 return true;
3364
3365 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3366 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003367 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003368
3369 return false;
3370}
3371
Reid Kleckner2214ed82016-01-29 00:49:42 +00003372/// parseDirectiveCVLoc
3373/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3374/// [is_stmt VALUE]
3375/// The first number is a file number, must have been previously assigned with
3376/// a .file directive, the second number is the line number and optionally the
3377/// third number is a column position (zero if not specified). The remaining
3378/// optional items are .loc sub-directives.
3379bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003380 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003381 SMLoc Loc;
3382 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003383 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3384 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003385 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003386
3387 int64_t LineNumber = 0;
3388 if (getLexer().is(AsmToken::Integer)) {
3389 LineNumber = getTok().getIntVal();
3390 if (LineNumber < 0)
3391 return TokError("line number less than zero in '.cv_loc' directive");
3392 Lex();
3393 }
3394
3395 int64_t ColumnPos = 0;
3396 if (getLexer().is(AsmToken::Integer)) {
3397 ColumnPos = getTok().getIntVal();
3398 if (ColumnPos < 0)
3399 return TokError("column position less than zero in '.cv_loc' directive");
3400 Lex();
3401 }
3402
3403 bool PrologueEnd = false;
3404 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003405
3406 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003407 StringRef Name;
3408 SMLoc Loc = getTok().getLoc();
3409 if (parseIdentifier(Name))
3410 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003411 if (Name == "prologue_end")
3412 PrologueEnd = true;
3413 else if (Name == "is_stmt") {
3414 Loc = getTok().getLoc();
3415 const MCExpr *Value;
3416 if (parseExpression(Value))
3417 return true;
3418 // The expression must be the constant 0 or 1.
3419 IsStmt = ~0ULL;
3420 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3421 IsStmt = MCE->getValue();
3422
3423 if (IsStmt > 1)
3424 return Error(Loc, "is_stmt value not 0 or 1");
3425 } else {
3426 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3427 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003428 return false;
3429 };
3430
3431 if (parseMany(parseOp, false /*hasComma*/))
3432 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003433
3434 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003435 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3436 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003437 return false;
3438}
3439
3440/// parseDirectiveCVLinetable
3441/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3442bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003443 int64_t FunctionId;
3444 StringRef FnStartName, FnEndName;
3445 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003446 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003447 parseToken(AsmToken::Comma,
3448 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003449 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3450 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003451 parseToken(AsmToken::Comma,
3452 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003453 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3454 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003455 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003456
3457 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3458 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3459
3460 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3461 return false;
3462}
3463
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003464/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003465/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003466bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003467 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3468 StringRef FnStartName, FnEndName;
3469 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003470 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003471 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003472 parseIntToken(
3473 SourceFileId,
3474 "expected SourceField in '.cv_inline_linetable' directive") ||
3475 check(SourceFileId <= 0, Loc,
3476 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003477 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003478 parseIntToken(
3479 SourceLineNum,
3480 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3481 check(SourceLineNum < 0, Loc,
3482 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003483 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3484 "expected identifier in directive") ||
3485 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3486 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003487 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003488
Nirav Davea645433c2016-07-18 15:24:03 +00003489 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3490 return true;
3491
3492 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3493 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003494 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3495 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003496 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003497 return false;
3498}
3499
David Majnemer408b5e62016-02-05 01:55:49 +00003500/// parseDirectiveCVDefRange
3501/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3502bool AsmParser::parseDirectiveCVDefRange() {
3503 SMLoc Loc;
3504 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3505 while (getLexer().is(AsmToken::Identifier)) {
3506 Loc = getLexer().getLoc();
3507 StringRef GapStartName;
3508 if (parseIdentifier(GapStartName))
3509 return Error(Loc, "expected identifier in directive");
3510 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3511
3512 Loc = getLexer().getLoc();
3513 StringRef GapEndName;
3514 if (parseIdentifier(GapEndName))
3515 return Error(Loc, "expected identifier in directive");
3516 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3517
3518 Ranges.push_back({GapStartSym, GapEndSym});
3519 }
3520
David Majnemer408b5e62016-02-05 01:55:49 +00003521 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003522 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3523 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003524 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003525
3526 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3527 return false;
3528}
3529
Reid Kleckner2214ed82016-01-29 00:49:42 +00003530/// parseDirectiveCVStringTable
3531/// ::= .cv_stringtable
3532bool AsmParser::parseDirectiveCVStringTable() {
3533 getStreamer().EmitCVStringTableDirective();
3534 return false;
3535}
3536
3537/// parseDirectiveCVFileChecksums
3538/// ::= .cv_filechecksums
3539bool AsmParser::parseDirectiveCVFileChecksums() {
3540 getStreamer().EmitCVFileChecksumsDirective();
3541 return false;
3542}
3543
Jim Grosbach4b905842013-09-20 23:08:21 +00003544/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003545/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003546bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003547 StringRef Name;
3548 bool EH = false;
3549 bool Debug = false;
3550
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003551 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003552 return TokError("Expected an identifier");
3553
3554 if (Name == ".eh_frame")
3555 EH = true;
3556 else if (Name == ".debug_frame")
3557 Debug = true;
3558
3559 if (getLexer().is(AsmToken::Comma)) {
3560 Lex();
3561
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003562 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003563 return TokError("Expected an identifier");
3564
3565 if (Name == ".eh_frame")
3566 EH = true;
3567 else if (Name == ".debug_frame")
3568 Debug = true;
3569 }
3570
3571 getStreamer().EmitCFISections(EH, Debug);
3572 return false;
3573}
3574
Jim Grosbach4b905842013-09-20 23:08:21 +00003575/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003576/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003577bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003578 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003579 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3580 if (check(parseIdentifier(Simple) || Simple != "simple",
3581 "unexpected token") ||
3582 parseToken(AsmToken::EndOfStatement))
3583 return addErrorSuffix(" in '.cfi_startproc' directive");
3584 }
Nirav Davea645433c2016-07-18 15:24:03 +00003585
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003586 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003587 return false;
3588}
3589
Jim Grosbach4b905842013-09-20 23:08:21 +00003590/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003591/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003592bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003593 getStreamer().EmitCFIEndProc();
3594 return false;
3595}
3596
Jim Grosbach4b905842013-09-20 23:08:21 +00003597/// \brief parse register name or number.
3598bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003599 SMLoc DirectiveLoc) {
3600 unsigned RegNo;
3601
3602 if (getLexer().isNot(AsmToken::Integer)) {
3603 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3604 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003605 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003606 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003607 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003608
3609 return false;
3610}
3611
Jim Grosbach4b905842013-09-20 23:08:21 +00003612/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003613/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003614bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003615 int64_t Register = 0, Offset = 0;
3616 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3617 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3618 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003619 return true;
3620
3621 getStreamer().EmitCFIDefCfa(Register, Offset);
3622 return false;
3623}
3624
Jim Grosbach4b905842013-09-20 23:08:21 +00003625/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003626/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003627bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003628 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003629 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003630 return true;
3631
3632 getStreamer().EmitCFIDefCfaOffset(Offset);
3633 return false;
3634}
3635
Jim Grosbach4b905842013-09-20 23:08:21 +00003636/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003637/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003638bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003639 int64_t Register1 = 0, Register2 = 0;
3640 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3641 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3642 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003643 return true;
3644
3645 getStreamer().EmitCFIRegister(Register1, Register2);
3646 return false;
3647}
3648
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003649/// parseDirectiveCFIWindowSave
3650/// ::= .cfi_window_save
3651bool AsmParser::parseDirectiveCFIWindowSave() {
3652 getStreamer().EmitCFIWindowSave();
3653 return false;
3654}
3655
Jim Grosbach4b905842013-09-20 23:08:21 +00003656/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003657/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003658bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003659 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003660 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003661 return true;
3662
3663 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3664 return false;
3665}
3666
Jim Grosbach4b905842013-09-20 23:08:21 +00003667/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003668/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003669bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003670 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003671 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003672 return true;
3673
3674 getStreamer().EmitCFIDefCfaRegister(Register);
3675 return false;
3676}
3677
Jim Grosbach4b905842013-09-20 23:08:21 +00003678/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003679/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003680bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003681 int64_t Register = 0;
3682 int64_t Offset = 0;
3683
Nirav Davea645433c2016-07-18 15:24:03 +00003684 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3685 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3686 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003687 return true;
3688
3689 getStreamer().EmitCFIOffset(Register, Offset);
3690 return false;
3691}
3692
Jim Grosbach4b905842013-09-20 23:08:21 +00003693/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003694/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003695bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003696 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003697
Nirav Davea645433c2016-07-18 15:24:03 +00003698 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3699 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3700 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003701 return true;
3702
3703 getStreamer().EmitCFIRelOffset(Register, Offset);
3704 return false;
3705}
3706
3707static bool isValidEncoding(int64_t Encoding) {
3708 if (Encoding & ~0xff)
3709 return false;
3710
3711 if (Encoding == dwarf::DW_EH_PE_omit)
3712 return true;
3713
3714 const unsigned Format = Encoding & 0xf;
3715 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3716 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3717 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3718 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3719 return false;
3720
3721 const unsigned Application = Encoding & 0x70;
3722 if (Application != dwarf::DW_EH_PE_absptr &&
3723 Application != dwarf::DW_EH_PE_pcrel)
3724 return false;
3725
3726 return true;
3727}
3728
Jim Grosbach4b905842013-09-20 23:08:21 +00003729/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003730/// IsPersonality true for cfi_personality, false for cfi_lsda
3731/// ::= .cfi_personality encoding, [symbol_name]
3732/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003733bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003734 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003735 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003736 return true;
3737 if (Encoding == dwarf::DW_EH_PE_omit)
3738 return false;
3739
Eli Bendersky17233942013-01-15 22:59:42 +00003740 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00003741 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
3742 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3743 check(parseIdentifier(Name), "expected identifier in directive"))
3744 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003745
Jim Grosbach6f482002015-05-18 18:43:14 +00003746 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003747
3748 if (IsPersonality)
3749 getStreamer().EmitCFIPersonality(Sym, Encoding);
3750 else
3751 getStreamer().EmitCFILsda(Sym, Encoding);
3752 return false;
3753}
3754
Jim Grosbach4b905842013-09-20 23:08:21 +00003755/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00003756/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003757bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003758 getStreamer().EmitCFIRememberState();
3759 return false;
3760}
3761
Jim Grosbach4b905842013-09-20 23:08:21 +00003762/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00003763/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003764bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003765 getStreamer().EmitCFIRestoreState();
3766 return false;
3767}
3768
Jim Grosbach4b905842013-09-20 23:08:21 +00003769/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00003770/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00003771bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003772 int64_t Register = 0;
3773
Jim Grosbach4b905842013-09-20 23:08:21 +00003774 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003775 return true;
3776
3777 getStreamer().EmitCFISameValue(Register);
3778 return false;
3779}
3780
Jim Grosbach4b905842013-09-20 23:08:21 +00003781/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00003782/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00003783bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003784 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003785 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003786 return true;
3787
3788 getStreamer().EmitCFIRestore(Register);
3789 return false;
3790}
3791
Jim Grosbach4b905842013-09-20 23:08:21 +00003792/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00003793/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003794bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00003795 std::string Values;
3796 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003797 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003798 return true;
3799
3800 Values.push_back((uint8_t)CurrValue);
3801
3802 while (getLexer().is(AsmToken::Comma)) {
3803 Lex();
3804
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003805 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003806 return true;
3807
3808 Values.push_back((uint8_t)CurrValue);
3809 }
3810
3811 getStreamer().EmitCFIEscape(Values);
3812 return false;
3813}
3814
Jim Grosbach4b905842013-09-20 23:08:21 +00003815/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00003816/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00003817bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00003818 if (parseToken(AsmToken::EndOfStatement,
3819 "unexpected token in '.cfi_signal_frame'"))
3820 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003821
3822 getStreamer().EmitCFISignalFrame();
3823 return false;
3824}
3825
Jim Grosbach4b905842013-09-20 23:08:21 +00003826/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00003827/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00003828bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003829 int64_t Register = 0;
3830
Jim Grosbach4b905842013-09-20 23:08:21 +00003831 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003832 return true;
3833
3834 getStreamer().EmitCFIUndefined(Register);
3835 return false;
3836}
3837
Jim Grosbach4b905842013-09-20 23:08:21 +00003838/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00003839/// ::= .macros_on
3840/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00003841bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00003842 if (parseToken(AsmToken::EndOfStatement,
3843 "unexpected token in '" + Directive + "' directive"))
3844 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003845
Jim Grosbach4b905842013-09-20 23:08:21 +00003846 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00003847 return false;
3848}
3849
Jim Grosbach4b905842013-09-20 23:08:21 +00003850/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003851/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00003852bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003853 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003854 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003855 return TokError("expected identifier in '.macro' directive");
3856
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003857 if (getLexer().is(AsmToken::Comma))
3858 Lex();
3859
Eli Bendersky17233942013-01-15 22:59:42 +00003860 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00003861 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003862
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003863 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003864 return Error(Lexer.getLoc(),
3865 "Vararg parameter '" + Parameters.back().Name +
3866 "' should be last one in the list of parameters.");
3867
David Majnemer91fc4c22014-01-29 18:57:46 +00003868 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003869 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00003870 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003871
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003872 if (Lexer.is(AsmToken::Colon)) {
3873 Lex(); // consume ':'
3874
3875 SMLoc QualLoc;
3876 StringRef Qualifier;
3877
3878 QualLoc = Lexer.getLoc();
3879 if (parseIdentifier(Qualifier))
3880 return Error(QualLoc, "missing parameter qualifier for "
3881 "'" + Parameter.Name + "' in macro '" + Name + "'");
3882
3883 if (Qualifier == "req")
3884 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00003885 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003886 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003887 else
3888 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3889 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3890 }
3891
David Majnemer91fc4c22014-01-29 18:57:46 +00003892 if (getLexer().is(AsmToken::Equal)) {
3893 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003894
3895 SMLoc ParamLoc;
3896
3897 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003898 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00003899 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003900
3901 if (Parameter.Required)
3902 Warning(ParamLoc, "pointless default value for required parameter "
3903 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00003904 }
David Majnemer91fc4c22014-01-29 18:57:46 +00003905
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003906 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00003907
3908 if (getLexer().is(AsmToken::Comma))
3909 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003910 }
3911
Nirav Dave1180e6892016-06-02 17:15:05 +00003912 // Eat just the end of statement.
3913 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003914
Nirav Dave1180e6892016-06-02 17:15:05 +00003915 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00003916 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003917 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003918 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00003919 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00003920 // Ignore Lexing errors in macros.
3921 while (Lexer.is(AsmToken::Error)) {
3922 Lexer.Lex();
3923 }
3924
Eli Bendersky17233942013-01-15 22:59:42 +00003925 // Check whether we have reached the end of the file.
3926 if (getLexer().is(AsmToken::Eof))
3927 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3928
3929 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003930 if (getLexer().is(AsmToken::Identifier)) {
3931 if (getTok().getIdentifier() == ".endm" ||
3932 getTok().getIdentifier() == ".endmacro") {
3933 if (MacroDepth == 0) { // Outermost macro.
3934 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00003935 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003936 if (getLexer().isNot(AsmToken::EndOfStatement))
3937 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3938 "' directive");
3939 break;
3940 } else {
3941 // Otherwise we just found the end of an inner macro.
3942 --MacroDepth;
3943 }
3944 } else if (getTok().getIdentifier() == ".macro") {
3945 // We allow nested macros. Those aren't instantiated until the outermost
3946 // macro is expanded so just ignore them for now.
3947 ++MacroDepth;
3948 }
Eli Bendersky17233942013-01-15 22:59:42 +00003949 }
3950
3951 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003952 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00003953 }
3954
Jim Grosbach4b905842013-09-20 23:08:21 +00003955 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00003956 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3957 }
3958
3959 const char *BodyStart = StartToken.getLoc().getPointer();
3960 const char *BodyEnd = EndToken.getLoc().getPointer();
3961 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00003962 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003963 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00003964 return false;
3965}
3966
Jim Grosbach4b905842013-09-20 23:08:21 +00003967/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00003968///
3969/// With the support added for named parameters there may be code out there that
3970/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00003971/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00003972/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00003973/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00003974/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3975/// warning that the positional parameter found in body which have no effect.
3976/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00003977/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00003978/// intended or change the macro to use the named parameters. It is possible
3979/// this warning will trigger when the none of the named parameters are used
3980/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00003981void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00003982 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00003983 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00003984 // If this macro is not defined with named parameters the warning we are
3985 // checking for here doesn't apply.
3986 unsigned NParameters = Parameters.size();
3987 if (NParameters == 0)
3988 return;
3989
3990 bool NamedParametersFound = false;
3991 bool PositionalParametersFound = false;
3992
3993 // Look at the body of the macro for use of both the named parameters and what
3994 // are likely to be positional parameters. This is what expandMacro() is
3995 // doing when it finds the parameters in the body.
3996 while (!Body.empty()) {
3997 // Scan for the next possible parameter.
3998 std::size_t End = Body.size(), Pos = 0;
3999 for (; Pos != End; ++Pos) {
4000 // Check for a substitution or escape.
4001 // This macro is defined with parameters, look for \foo, \bar, etc.
4002 if (Body[Pos] == '\\' && Pos + 1 != End)
4003 break;
4004
4005 // This macro should have parameters, but look for $0, $1, ..., $n too.
4006 if (Body[Pos] != '$' || Pos + 1 == End)
4007 continue;
4008 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004009 if (Next == '$' || Next == 'n' ||
4010 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004011 break;
4012 }
4013
4014 // Check if we reached the end.
4015 if (Pos == End)
4016 break;
4017
4018 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004019 switch (Body[Pos + 1]) {
4020 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004021 case '$':
4022 break;
4023
Jim Grosbach4b905842013-09-20 23:08:21 +00004024 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004025 case 'n':
4026 PositionalParametersFound = true;
4027 break;
4028
Jim Grosbach4b905842013-09-20 23:08:21 +00004029 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004030 default: {
4031 PositionalParametersFound = true;
4032 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004033 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004034 }
4035 Pos += 2;
4036 } else {
4037 unsigned I = Pos + 1;
4038 while (isIdentifierChar(Body[I]) && I + 1 != End)
4039 ++I;
4040
Jim Grosbach4b905842013-09-20 23:08:21 +00004041 const char *Begin = Body.data() + Pos + 1;
4042 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004043 unsigned Index = 0;
4044 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004045 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004046 break;
4047
4048 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004049 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4050 Pos += 3;
4051 else {
4052 Pos = I;
4053 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004054 } else {
4055 NamedParametersFound = true;
4056 Pos += 1 + Argument.size();
4057 }
4058 }
4059 // Update the scan point.
4060 Body = Body.substr(Pos);
4061 }
4062
4063 if (!NamedParametersFound && PositionalParametersFound)
4064 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4065 "used in macro body, possible positional parameter "
4066 "found in body which will have no effect");
4067}
4068
Nico Weber155dccd12014-07-24 17:08:39 +00004069/// parseDirectiveExitMacro
4070/// ::= .exitm
4071bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004072 if (parseToken(AsmToken::EndOfStatement,
4073 "unexpected token in '" + Directive + "' directive"))
4074 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004075
4076 if (!isInsideMacroInstantiation())
4077 return TokError("unexpected '" + Directive + "' in file, "
4078 "no current macro definition");
4079
4080 // Exit all conditionals that are active in the current macro.
4081 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4082 TheCondState = TheCondStack.back();
4083 TheCondStack.pop_back();
4084 }
4085
4086 handleMacroExit();
4087 return false;
4088}
4089
Jim Grosbach4b905842013-09-20 23:08:21 +00004090/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004091/// ::= .endm
4092/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004093bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004094 if (getLexer().isNot(AsmToken::EndOfStatement))
4095 return TokError("unexpected token in '" + Directive + "' directive");
4096
4097 // If we are inside a macro instantiation, terminate the current
4098 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004099 if (isInsideMacroInstantiation()) {
4100 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004101 return false;
4102 }
4103
4104 // Otherwise, this .endmacro is a stray entry in the file; well formed
4105 // .endmacro directives are handled during the macro definition parsing.
4106 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004107 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004108}
4109
Jim Grosbach4b905842013-09-20 23:08:21 +00004110/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004111/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004112bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004113 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004114 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004115 if (parseTokenLoc(Loc) ||
4116 check(parseIdentifier(Name), Loc,
4117 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004118 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004119 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004120 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004121
Nirav Dave1ab71992016-07-18 19:35:21 +00004122 if (!lookupMacro(Name))
4123 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4124
Jim Grosbach4b905842013-09-20 23:08:21 +00004125 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004126 return false;
4127}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004128
Jim Grosbach4b905842013-09-20 23:08:21 +00004129/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004130/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004131bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004132 // Expect a single argument: an expression that evaluates to a constant
4133 // in the inclusive range 0-30.
4134 SMLoc ExprLoc = getLexer().getLoc();
4135 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004136 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004137 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4138 "in '.bundle_align_mode' "
4139 "directive") ||
4140 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4141 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004142 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004143
4144 // Because of AlignSizePow2's verified range we can safely truncate it to
4145 // unsigned.
4146 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4147 return false;
4148}
4149
Jim Grosbach4b905842013-09-20 23:08:21 +00004150/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004151/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004152bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004153 if (checkForValidSection())
4154 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004155 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004156
Nirav Dave1a9044b2016-10-24 14:35:29 +00004157 StringRef Option;
4158 SMLoc Loc = getTok().getLoc();
4159 const char *kInvalidOptionError =
4160 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004161
Nirav Dave1a9044b2016-10-24 14:35:29 +00004162 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004163 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4164 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004165 parseToken(AsmToken::EndOfStatement,
4166 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004167 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004168 AlignToEnd = true;
4169 }
4170
Eli Bendersky802b6282013-01-07 21:51:08 +00004171 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004172 return false;
4173}
4174
Jim Grosbach4b905842013-09-20 23:08:21 +00004175/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004176/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004177bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004178 if (checkForValidSection() ||
4179 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004180 "unexpected token in '.bundle_unlock' directive"))
4181 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004182
4183 getStreamer().EmitBundleUnlock();
4184 return false;
4185}
4186
Jim Grosbach4b905842013-09-20 23:08:21 +00004187/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004188/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004189bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Eli Bendersky17233942013-01-15 22:59:42 +00004190
Petr Hosek67a94a72016-05-28 05:57:48 +00004191 SMLoc NumBytesLoc = Lexer.getLoc();
4192 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004193 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004194 return true;
4195
4196 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004197 if (parseOptionalToken(AsmToken::Comma))
4198 if (parseAbsoluteExpression(FillExpr))
4199 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4200 if (parseToken(AsmToken::EndOfStatement))
4201 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004202
Eli Bendersky17233942013-01-15 22:59:42 +00004203 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004204 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004205
4206 return false;
4207}
4208
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004209/// parseDirectiveDCB
4210/// ::= .dcb.{b, l, w} expression, expression
4211bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004212 SMLoc NumValuesLoc = Lexer.getLoc();
4213 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004214 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004215 return true;
4216
4217 if (NumValues < 0) {
4218 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4219 return false;
4220 }
4221
4222 if (parseToken(AsmToken::Comma,
4223 "unexpected token in '" + Twine(IDVal) + "' directive"))
4224 return true;
4225
4226 const MCExpr *Value;
4227 SMLoc ExprLoc = getLexer().getLoc();
4228 if (parseExpression(Value))
4229 return true;
4230
4231 // Special case constant expressions to match code generator.
4232 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4233 assert(Size <= 8 && "Invalid size");
4234 uint64_t IntValue = MCE->getValue();
4235 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4236 return Error(ExprLoc, "literal value out of range for directive");
4237 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4238 getStreamer().EmitIntValue(IntValue, Size);
4239 } else {
4240 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4241 getStreamer().EmitValue(Value, Size, ExprLoc);
4242 }
4243
4244 if (parseToken(AsmToken::EndOfStatement,
4245 "unexpected token in '" + Twine(IDVal) + "' directive"))
4246 return true;
4247
4248 return false;
4249}
4250
4251/// parseDirectiveRealDCB
4252/// ::= .dcb.{d, s} expression, expression
4253bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004254 SMLoc NumValuesLoc = Lexer.getLoc();
4255 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004256 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004257 return true;
4258
4259 if (NumValues < 0) {
4260 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4261 return false;
4262 }
4263
4264 if (parseToken(AsmToken::Comma,
4265 "unexpected token in '" + Twine(IDVal) + "' directive"))
4266 return true;
4267
4268 APInt AsInt;
4269 if (parseRealValue(Semantics, AsInt))
4270 return true;
4271
4272 if (parseToken(AsmToken::EndOfStatement,
4273 "unexpected token in '" + Twine(IDVal) + "' directive"))
4274 return true;
4275
4276 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4277 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4278 AsInt.getBitWidth() / 8);
4279
4280 return false;
4281}
4282
Petr Hosek85b2f672016-09-23 21:53:36 +00004283/// parseDirectiveDS
4284/// ::= .ds.{b, d, l, p, s, w, x} expression
4285bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004286
4287 SMLoc NumValuesLoc = Lexer.getLoc();
4288 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004289 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004290 return true;
4291
4292 if (NumValues < 0) {
4293 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4294 return false;
4295 }
4296
4297 if (parseToken(AsmToken::EndOfStatement,
4298 "unexpected token in '" + Twine(IDVal) + "' directive"))
4299 return true;
4300
4301 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4302 getStreamer().emitFill(Size, 0);
4303
4304 return false;
4305}
4306
Jim Grosbach4b905842013-09-20 23:08:21 +00004307/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004308/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004309bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004310 if (checkForValidSection())
4311 return true;
4312
Nirav Dave1a9044b2016-10-24 14:35:29 +00004313 auto parseOp = [&]() -> bool {
4314 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004315 if (parseExpression(Value))
4316 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004317 if (Signed)
4318 getStreamer().EmitSLEB128Value(Value);
4319 else
4320 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004321 return false;
4322 };
Eli Bendersky17233942013-01-15 22:59:42 +00004323
Nirav Dave1a9044b2016-10-24 14:35:29 +00004324 if (parseMany(parseOp))
4325 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004326
4327 return false;
4328}
4329
Jim Grosbach4b905842013-09-20 23:08:21 +00004330/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004331/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004332bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004333 auto parseOp = [&]() -> bool {
4334 StringRef Name;
4335 SMLoc Loc = getTok().getLoc();
4336 if (parseIdentifier(Name))
4337 return Error(Loc, "expected identifier");
4338 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004339
Nirav Dave1a9044b2016-10-24 14:35:29 +00004340 // Assembler local symbols don't make any sense here. Complain loudly.
4341 if (Sym->isTemporary())
4342 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004343
Nirav Dave1a9044b2016-10-24 14:35:29 +00004344 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4345 return Error(Loc, "unable to emit symbol attribute");
4346 return false;
4347 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004348
Nirav Dave1a9044b2016-10-24 14:35:29 +00004349 if (parseMany(parseOp))
4350 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004351 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004352}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004353
Jim Grosbach4b905842013-09-20 23:08:21 +00004354/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004355/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004356bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004357 if (checkForValidSection())
4358 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004359
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004360 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004361 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004362 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004363 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004364
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004365 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004366 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004367
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004368 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004369 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004370 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004371
4372 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004373 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004374 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004375 return true;
4376
4377 int64_t Pow2Alignment = 0;
4378 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004379 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004380 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004381 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004382 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004383 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004384
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004385 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4386 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004387 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4388
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004389 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004390 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4391 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004392 if (!isPowerOf2_64(Pow2Alignment))
4393 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4394 Pow2Alignment = Log2_64(Pow2Alignment);
4395 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004396 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004397
Nirav Dave1a9044b2016-10-24 14:35:29 +00004398 if (parseToken(AsmToken::EndOfStatement,
4399 "unexpected token in '.comm' or '.lcomm' directive"))
4400 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004401
Chris Lattner28ad7542009-07-09 17:25:12 +00004402 // NOTE: a size of zero for a .comm should create a undefined symbol
4403 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004404 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004405 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004406 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004407
Eric Christopherbc818852010-05-14 01:38:54 +00004408 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004409 // may internally end up wanting an alignment in bytes.
4410 // FIXME: Diagnose overflow.
4411 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004412 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004413 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004414
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004415 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004416 return Error(IDLoc, "invalid symbol redefinition");
4417
Chris Lattner28ad7542009-07-09 17:25:12 +00004418 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004419 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004420 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004421 return false;
4422 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004423
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004424 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004425 return false;
4426}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004427
Jim Grosbach4b905842013-09-20 23:08:21 +00004428/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004429/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004430bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004431 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004432 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004433
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004434 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004435 if (parseToken(AsmToken::EndOfStatement,
4436 "unexpected token in '.abort' directive"))
4437 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004438
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004439 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004440 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004441 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004442 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004443 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004444
4445 return false;
4446}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004447
Jim Grosbach4b905842013-09-20 23:08:21 +00004448/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004449/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004450bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004451 // Allow the strings to have escaped octal character sequence.
4452 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004453 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004454
Nirav Davea645433c2016-07-18 15:24:03 +00004455 if (check(getTok().isNot(AsmToken::String),
4456 "expected string in '.include' directive") ||
4457 parseEscapedString(Filename) ||
4458 check(getTok().isNot(AsmToken::EndOfStatement),
4459 "unexpected token in '.include' directive") ||
4460 // Attempt to switch the lexer to the included file before consuming the
4461 // end of statement to avoid losing it when we switch.
4462 check(enterIncludeFile(Filename), IncludeLoc,
4463 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004464 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004465
4466 return false;
4467}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004468
Jim Grosbach4b905842013-09-20 23:08:21 +00004469/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004470/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004471bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004472 // Allow the strings to have escaped octal character sequence.
4473 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004474 SMLoc IncbinLoc = getTok().getLoc();
4475 if (check(getTok().isNot(AsmToken::String),
4476 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00004477 parseEscapedString(Filename))
4478 return true;
4479
4480 int64_t Skip = 0;
4481 const MCExpr *Count = nullptr;
4482 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004483 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00004484 // The skip expression can be omitted while specifying the count, e.g:
4485 // .incbin "filename",,4
4486 if (getTok().isNot(AsmToken::Comma)) {
4487 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4488 return true;
4489 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00004490 if (parseOptionalToken(AsmToken::Comma)) {
4491 CountLoc = getTok().getLoc();
4492 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00004493 return true;
4494 }
4495 }
4496
4497 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004498 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004499 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004500
Petr Hosek2f4ac442016-09-23 00:41:06 +00004501 if (check(Skip < 0, SkipLoc, "skip is negative"))
4502 return true;
4503
Nirav Dave1ab71992016-07-18 19:35:21 +00004504 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00004505 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00004506 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004507 return false;
4508}
4509
Jim Grosbach4b905842013-09-20 23:08:21 +00004510/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004511/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4512bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004513 TheCondStack.push_back(TheCondState);
4514 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004515 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004516 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004517 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004518 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004519 if (parseAbsoluteExpression(ExprValue) ||
4520 parseToken(AsmToken::EndOfStatement,
4521 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004522 return true;
4523
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004524 switch (DirKind) {
4525 default:
4526 llvm_unreachable("unsupported directive");
4527 case DK_IF:
4528 case DK_IFNE:
4529 break;
4530 case DK_IFEQ:
4531 ExprValue = ExprValue == 0;
4532 break;
4533 case DK_IFGE:
4534 ExprValue = ExprValue >= 0;
4535 break;
4536 case DK_IFGT:
4537 ExprValue = ExprValue > 0;
4538 break;
4539 case DK_IFLE:
4540 ExprValue = ExprValue <= 0;
4541 break;
4542 case DK_IFLT:
4543 ExprValue = ExprValue < 0;
4544 break;
4545 }
4546
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004547 TheCondState.CondMet = ExprValue;
4548 TheCondState.Ignore = !TheCondState.CondMet;
4549 }
4550
4551 return false;
4552}
4553
Jim Grosbach4b905842013-09-20 23:08:21 +00004554/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004555/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004556bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004557 TheCondStack.push_back(TheCondState);
4558 TheCondState.TheCond = AsmCond::IfCond;
4559
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004560 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004561 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004562 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004563 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004564
Nirav Davea645433c2016-07-18 15:24:03 +00004565 if (parseToken(AsmToken::EndOfStatement,
4566 "unexpected token in '.ifb' directive"))
4567 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004568
4569 TheCondState.CondMet = ExpectBlank == Str.empty();
4570 TheCondState.Ignore = !TheCondState.CondMet;
4571 }
4572
4573 return false;
4574}
4575
Jim Grosbach4b905842013-09-20 23:08:21 +00004576/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004577/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004578/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004579bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004580 TheCondStack.push_back(TheCondState);
4581 TheCondState.TheCond = AsmCond::IfCond;
4582
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004583 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004584 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004585 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004586 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004587
Nirav Davea645433c2016-07-18 15:24:03 +00004588 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4589 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004590
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004591 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004592
Nirav Davea645433c2016-07-18 15:24:03 +00004593 if (parseToken(AsmToken::EndOfStatement,
4594 "unexpected token in '.ifc' directive"))
4595 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004596
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004597 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004598 TheCondState.Ignore = !TheCondState.CondMet;
4599 }
4600
4601 return false;
4602}
4603
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004604/// parseDirectiveIfeqs
4605/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004606bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004607 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004608 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004609 return TokError("expected string parameter for '.ifeqs' directive");
4610 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004611 }
4612
4613 StringRef String1 = getTok().getStringContents();
4614 Lex();
4615
4616 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004617 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004618 return TokError(
4619 "expected comma after first string for '.ifeqs' directive");
4620 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004621 }
4622
4623 Lex();
4624
4625 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004626 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004627 return TokError("expected string parameter for '.ifeqs' directive");
4628 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004629 }
4630
4631 StringRef String2 = getTok().getStringContents();
4632 Lex();
4633
4634 TheCondStack.push_back(TheCondState);
4635 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004636 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004637 TheCondState.Ignore = !TheCondState.CondMet;
4638
4639 return false;
4640}
4641
Jim Grosbach4b905842013-09-20 23:08:21 +00004642/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004643/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004644bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004645 StringRef Name;
4646 TheCondStack.push_back(TheCondState);
4647 TheCondState.TheCond = AsmCond::IfCond;
4648
4649 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004650 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004651 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00004652 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4653 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4654 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004655
Jim Grosbach6f482002015-05-18 18:43:14 +00004656 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004657
4658 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004659 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004660 else
Craig Topper353eda42014-04-24 06:44:33 +00004661 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004662 TheCondState.Ignore = !TheCondState.CondMet;
4663 }
4664
4665 return false;
4666}
4667
Jim Grosbach4b905842013-09-20 23:08:21 +00004668/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004669/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004670bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004671 if (TheCondState.TheCond != AsmCond::IfCond &&
4672 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004673 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
4674 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004675 TheCondState.TheCond = AsmCond::ElseIfCond;
4676
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004677 bool LastIgnoreState = false;
4678 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004679 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004680 if (LastIgnoreState || TheCondState.CondMet) {
4681 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004682 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004683 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004684 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004685 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004686 return true;
4687
Nirav Dave1a9044b2016-10-24 14:35:29 +00004688 if (parseToken(AsmToken::EndOfStatement,
4689 "unexpected token in '.elseif' directive"))
4690 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004691
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004692 TheCondState.CondMet = ExprValue;
4693 TheCondState.Ignore = !TheCondState.CondMet;
4694 }
4695
4696 return false;
4697}
4698
Jim Grosbach4b905842013-09-20 23:08:21 +00004699/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004700/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004701bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004702 if (parseToken(AsmToken::EndOfStatement,
4703 "unexpected token in '.else' directive"))
4704 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004705
4706 if (TheCondState.TheCond != AsmCond::IfCond &&
4707 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004708 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
4709 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004710 TheCondState.TheCond = AsmCond::ElseCond;
4711 bool LastIgnoreState = false;
4712 if (!TheCondStack.empty())
4713 LastIgnoreState = TheCondStack.back().Ignore;
4714 if (LastIgnoreState || TheCondState.CondMet)
4715 TheCondState.Ignore = true;
4716 else
4717 TheCondState.Ignore = false;
4718
4719 return false;
4720}
4721
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004722/// parseDirectiveEnd
4723/// ::= .end
4724bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004725 if (parseToken(AsmToken::EndOfStatement,
4726 "unexpected token in '.end' directive"))
4727 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004728
4729 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00004730 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004731
4732 return false;
4733}
4734
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004735/// parseDirectiveError
4736/// ::= .err
4737/// ::= .error [string]
4738bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4739 if (!TheCondStack.empty()) {
4740 if (TheCondStack.back().Ignore) {
4741 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004742 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004743 }
4744 }
4745
4746 if (!WithMessage)
4747 return Error(L, ".err encountered");
4748
4749 StringRef Message = ".error directive invoked in source file";
4750 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004751 if (Lexer.isNot(AsmToken::String))
4752 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004753
4754 Message = getTok().getStringContents();
4755 Lex();
4756 }
4757
Nirav Dave2364748a2016-09-16 18:30:20 +00004758 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004759}
4760
Nico Weber404012b2014-07-24 16:26:06 +00004761/// parseDirectiveWarning
4762/// ::= .warning [string]
4763bool AsmParser::parseDirectiveWarning(SMLoc L) {
4764 if (!TheCondStack.empty()) {
4765 if (TheCondStack.back().Ignore) {
4766 eatToEndOfStatement();
4767 return false;
4768 }
4769 }
4770
4771 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00004772
4773 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004774 if (Lexer.isNot(AsmToken::String))
4775 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00004776
4777 Message = getTok().getStringContents();
4778 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00004779 if (parseToken(AsmToken::EndOfStatement,
4780 "expected end of statement in '.warning' directive"))
4781 return true;
Nico Weber404012b2014-07-24 16:26:06 +00004782 }
4783
Nirav Dave2364748a2016-09-16 18:30:20 +00004784 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00004785}
4786
Jim Grosbach4b905842013-09-20 23:08:21 +00004787/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004788/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00004789bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004790 if (parseToken(AsmToken::EndOfStatement,
4791 "unexpected token in '.endif' directive"))
4792 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004793
Jim Grosbach4b905842013-09-20 23:08:21 +00004794 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004795 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
4796 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004797 if (!TheCondStack.empty()) {
4798 TheCondState = TheCondStack.back();
4799 TheCondStack.pop_back();
4800 }
4801
4802 return false;
4803}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00004804
Eli Bendersky17233942013-01-15 22:59:42 +00004805void AsmParser::initializeDirectiveKindMap() {
4806 DirectiveKindMap[".set"] = DK_SET;
4807 DirectiveKindMap[".equ"] = DK_EQU;
4808 DirectiveKindMap[".equiv"] = DK_EQUIV;
4809 DirectiveKindMap[".ascii"] = DK_ASCII;
4810 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4811 DirectiveKindMap[".string"] = DK_STRING;
4812 DirectiveKindMap[".byte"] = DK_BYTE;
4813 DirectiveKindMap[".short"] = DK_SHORT;
4814 DirectiveKindMap[".value"] = DK_VALUE;
4815 DirectiveKindMap[".2byte"] = DK_2BYTE;
4816 DirectiveKindMap[".long"] = DK_LONG;
4817 DirectiveKindMap[".int"] = DK_INT;
4818 DirectiveKindMap[".4byte"] = DK_4BYTE;
4819 DirectiveKindMap[".quad"] = DK_QUAD;
4820 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00004821 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00004822 DirectiveKindMap[".single"] = DK_SINGLE;
4823 DirectiveKindMap[".float"] = DK_FLOAT;
4824 DirectiveKindMap[".double"] = DK_DOUBLE;
4825 DirectiveKindMap[".align"] = DK_ALIGN;
4826 DirectiveKindMap[".align32"] = DK_ALIGN32;
4827 DirectiveKindMap[".balign"] = DK_BALIGN;
4828 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4829 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4830 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4831 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4832 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4833 DirectiveKindMap[".org"] = DK_ORG;
4834 DirectiveKindMap[".fill"] = DK_FILL;
4835 DirectiveKindMap[".zero"] = DK_ZERO;
4836 DirectiveKindMap[".extern"] = DK_EXTERN;
4837 DirectiveKindMap[".globl"] = DK_GLOBL;
4838 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00004839 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4840 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4841 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4842 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4843 DirectiveKindMap[".reference"] = DK_REFERENCE;
4844 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4845 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4846 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4847 DirectiveKindMap[".comm"] = DK_COMM;
4848 DirectiveKindMap[".common"] = DK_COMMON;
4849 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4850 DirectiveKindMap[".abort"] = DK_ABORT;
4851 DirectiveKindMap[".include"] = DK_INCLUDE;
4852 DirectiveKindMap[".incbin"] = DK_INCBIN;
4853 DirectiveKindMap[".code16"] = DK_CODE16;
4854 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4855 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004856 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00004857 DirectiveKindMap[".irp"] = DK_IRP;
4858 DirectiveKindMap[".irpc"] = DK_IRPC;
4859 DirectiveKindMap[".endr"] = DK_ENDR;
4860 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4861 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4862 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4863 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004864 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4865 DirectiveKindMap[".ifge"] = DK_IFGE;
4866 DirectiveKindMap[".ifgt"] = DK_IFGT;
4867 DirectiveKindMap[".ifle"] = DK_IFLE;
4868 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00004869 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00004870 DirectiveKindMap[".ifb"] = DK_IFB;
4871 DirectiveKindMap[".ifnb"] = DK_IFNB;
4872 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004873 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00004874 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00004875 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00004876 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4877 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4878 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4879 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4880 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004881 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00004882 DirectiveKindMap[".endif"] = DK_ENDIF;
4883 DirectiveKindMap[".skip"] = DK_SKIP;
4884 DirectiveKindMap[".space"] = DK_SPACE;
4885 DirectiveKindMap[".file"] = DK_FILE;
4886 DirectiveKindMap[".line"] = DK_LINE;
4887 DirectiveKindMap[".loc"] = DK_LOC;
4888 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004889 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00004890 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004891 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
4892 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00004893 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00004894 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00004895 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004896 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
4897 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Eli Bendersky17233942013-01-15 22:59:42 +00004898 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4899 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4900 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4901 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4902 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4903 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4904 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4905 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4906 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4907 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4908 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4909 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4910 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4911 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4912 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4913 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4914 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4915 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4916 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4917 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4918 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00004919 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00004920 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4921 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4922 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00004923 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00004924 DirectiveKindMap[".endm"] = DK_ENDM;
4925 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4926 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004927 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004928 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00004929 DirectiveKindMap[".warning"] = DK_WARNING;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00004930 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00004931 DirectiveKindMap[".dc"] = DK_DC;
4932 DirectiveKindMap[".dc.a"] = DK_DC_A;
4933 DirectiveKindMap[".dc.b"] = DK_DC_B;
4934 DirectiveKindMap[".dc.d"] = DK_DC_D;
4935 DirectiveKindMap[".dc.l"] = DK_DC_L;
4936 DirectiveKindMap[".dc.s"] = DK_DC_S;
4937 DirectiveKindMap[".dc.w"] = DK_DC_W;
4938 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004939 DirectiveKindMap[".dcb"] = DK_DCB;
4940 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
4941 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
4942 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
4943 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
4944 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
4945 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00004946 DirectiveKindMap[".ds"] = DK_DS;
4947 DirectiveKindMap[".ds.b"] = DK_DS_B;
4948 DirectiveKindMap[".ds.d"] = DK_DS_D;
4949 DirectiveKindMap[".ds.l"] = DK_DS_L;
4950 DirectiveKindMap[".ds.p"] = DK_DS_P;
4951 DirectiveKindMap[".ds.s"] = DK_DS_S;
4952 DirectiveKindMap[".ds.w"] = DK_DS_W;
4953 DirectiveKindMap[".ds.x"] = DK_DS_X;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00004954}
4955
Jim Grosbach4b905842013-09-20 23:08:21 +00004956MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004957 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004958
Rafael Espindola34b9c512012-06-03 23:57:14 +00004959 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004960 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004961 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00004962 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004963 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00004964 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004965 }
4966
Rafael Espindola34b9c512012-06-03 23:57:14 +00004967 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00004968 (getTok().getIdentifier() == ".rept" ||
4969 getTok().getIdentifier() == ".irp" ||
4970 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004971 ++NestLevel;
4972 }
4973
4974 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00004975 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004976 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004977 EndToken = getTok();
4978 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004979 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004980 printError(getTok().getLoc(),
4981 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00004982 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004983 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004984 break;
4985 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004986 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004987 }
4988
Rafael Espindola34b9c512012-06-03 23:57:14 +00004989 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004990 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004991 }
4992
4993 const char *BodyStart = StartToken.getLoc().getPointer();
4994 const char *BodyEnd = EndToken.getLoc().getPointer();
4995 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4996
Rafael Espindola34b9c512012-06-03 23:57:14 +00004997 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004998 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00004999 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005000}
5001
Jim Grosbach4b905842013-09-20 23:08:21 +00005002void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005003 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005004 OS << ".endr\n";
5005
Rafael Espindola3560ff22014-08-27 20:03:13 +00005006 std::unique_ptr<MemoryBuffer> Instantiation =
5007 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005008
Rafael Espindola34b9c512012-06-03 23:57:14 +00005009 // Create the macro instantiation object and add to the current macro
5010 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005011 MacroInstantiation *MI = new MacroInstantiation(
5012 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005013 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005014
Rafael Espindola34b9c512012-06-03 23:57:14 +00005015 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005016 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005017 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005018 Lex();
5019}
5020
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005021/// parseDirectiveRept
5022/// ::= .rep | .rept count
5023bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005024 const MCExpr *CountExpr;
5025 SMLoc CountLoc = getTok().getLoc();
5026 if (parseExpression(CountExpr))
5027 return true;
5028
Rafael Espindola34b9c512012-06-03 23:57:14 +00005029 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00005030 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005031 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5032 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005033
Nirav Davea645433c2016-07-18 15:24:03 +00005034 if (check(Count < 0, CountLoc, "Count is negative") ||
5035 parseToken(AsmToken::EndOfStatement,
5036 "unexpected token in '" + Dir + "' directive"))
5037 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005038
5039 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005040 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005041 if (!M)
5042 return true;
5043
5044 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5045 // to hold the macro body with substitutions.
5046 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005047 raw_svector_ostream OS(Buf);
5048 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005049 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5050 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005051 return true;
5052 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005053 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005054
5055 return false;
5056}
5057
Jim Grosbach4b905842013-09-20 23:08:21 +00005058/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005059/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005060bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005061 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005062 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005063 if (check(parseIdentifier(Parameter.Name),
5064 "expected identifier in '.irp' directive") ||
5065 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5066 parseMacroArguments(nullptr, A) ||
5067 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005068 return true;
5069
Rafael Espindola768b41c2012-06-15 14:02:34 +00005070 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005071 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005072 if (!M)
5073 return true;
5074
5075 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5076 // to hold the macro body with substitutions.
5077 SmallString<256> Buf;
5078 raw_svector_ostream OS(Buf);
5079
Craig Topper84008482015-10-10 05:38:14 +00005080 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005081 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5082 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005083 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005084 return true;
5085 }
5086
Jim Grosbach4b905842013-09-20 23:08:21 +00005087 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005088
5089 return false;
5090}
5091
Jim Grosbach4b905842013-09-20 23:08:21 +00005092/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005093/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005094bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005095 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005096 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005097
5098 if (check(parseIdentifier(Parameter.Name),
5099 "expected identifier in '.irpc' directive") ||
5100 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5101 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005102 return true;
5103
5104 if (A.size() != 1 || A.front().size() != 1)
5105 return TokError("unexpected token in '.irpc' directive");
5106
5107 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005108 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5109 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005110
5111 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005112 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005113 if (!M)
5114 return true;
5115
5116 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5117 // to hold the macro body with substitutions.
5118 SmallString<256> Buf;
5119 raw_svector_ostream OS(Buf);
5120
5121 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005122 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005123 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005124 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005125
Toma Tabacu217116e2015-04-27 10:50:29 +00005126 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5127 // This is undocumented, but GAS seems to support it.
5128 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005129 return true;
5130 }
5131
Jim Grosbach4b905842013-09-20 23:08:21 +00005132 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005133
5134 return false;
5135}
5136
Jim Grosbach4b905842013-09-20 23:08:21 +00005137bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005138 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005139 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005140
5141 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005142 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005143 assert(getLexer().is(AsmToken::EndOfStatement));
5144
Jim Grosbach4b905842013-09-20 23:08:21 +00005145 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005146 return false;
5147}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005148
Jim Grosbach4b905842013-09-20 23:08:21 +00005149bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005150 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005151 const MCExpr *Value;
5152 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005153 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005154 return true;
5155 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5156 if (!MCE)
5157 return Error(ExprLoc, "unexpected expression in _emit");
5158 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005159 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005160 return Error(ExprLoc, "literal value out of range for directive");
5161
Craig Topper7d5b2312015-10-10 05:25:02 +00005162 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005163 return false;
5164}
5165
Jim Grosbach4b905842013-09-20 23:08:21 +00005166bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005167 const MCExpr *Value;
5168 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005169 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005170 return true;
5171 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5172 if (!MCE)
5173 return Error(ExprLoc, "unexpected expression in align");
5174 uint64_t IntValue = MCE->getValue();
5175 if (!isPowerOf2_64(IntValue))
5176 return Error(ExprLoc, "literal value not a power of two greater then zero");
5177
Craig Topper7d5b2312015-10-10 05:25:02 +00005178 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005179 return false;
5180}
5181
Chad Rosierf43fcf52013-02-13 21:27:17 +00005182// We are comparing pointers, but the pointers are relative to a single string.
5183// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005184static int rewritesSort(const AsmRewrite *AsmRewriteA,
5185 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005186 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5187 return -1;
5188 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5189 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005190
Chad Rosierfce4fab2013-04-08 17:43:47 +00005191 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5192 // rewrite to the same location. Make sure the SizeDirective rewrite is
5193 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5194 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005195 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5196 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005197 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005198
Jim Grosbach4b905842013-09-20 23:08:21 +00005199 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5200 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005201 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005202 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005203}
5204
Jim Grosbach4b905842013-09-20 23:08:21 +00005205bool AsmParser::parseMSInlineAsm(
5206 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
5207 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
5208 SmallVectorImpl<std::string> &Constraints,
5209 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5210 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005211 SmallVector<void *, 4> InputDecls;
5212 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005213 SmallVector<bool, 4> InputDeclsAddressOf;
5214 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005215 SmallVector<std::string, 4> InputConstraints;
5216 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005217 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005218
Benjamin Kramer1a136112013-02-15 20:37:21 +00005219 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005220
5221 // Prime the lexer.
5222 Lex();
5223
5224 // While we have input, parse each statement.
5225 unsigned InputIdx = 0;
5226 unsigned OutputIdx = 0;
5227 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005228 // Parse curly braces marking block start/end
5229 if (parseCurlyBlockScope(AsmStrRewrites))
5230 continue;
5231
Eli Friedman0f4871d2012-10-22 23:58:19 +00005232 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005233 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005234
Nirav Dave2364748a2016-09-16 18:30:20 +00005235 if (StatementErr || Info.ParseError) {
5236 // Emit pending errors if any exist.
5237 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005238 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005239 }
5240
5241 // No pending error should exist here.
5242 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005243
Benjamin Kramer1a136112013-02-15 20:37:21 +00005244 if (Info.Opcode == ~0U)
5245 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005246
Benjamin Kramer1a136112013-02-15 20:37:21 +00005247 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005248
Benjamin Kramer1a136112013-02-15 20:37:21 +00005249 // Build the list of clobbers, outputs and inputs.
5250 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005251 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005252
Benjamin Kramer1a136112013-02-15 20:37:21 +00005253 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005254 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005255 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005256
Benjamin Kramer1a136112013-02-15 20:37:21 +00005257 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005258 if (Operand.isReg() && !Operand.needAddressOf() &&
5259 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005260 unsigned NumDefs = Desc.getNumDefs();
5261 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005262 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5263 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005264 continue;
5265 }
5266
5267 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005268 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005269 if (SymName.empty())
5270 continue;
5271
David Blaikie960ea3f2014-06-08 16:18:35 +00005272 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005273 if (!OpDecl)
5274 continue;
5275
5276 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005277 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005278 if (isOutput) {
5279 ++InputIdx;
5280 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005281 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005282 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005283 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005284 } else {
5285 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005286 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5287 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005288 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005289 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005290 }
Reid Kleckneree088972013-12-10 18:27:32 +00005291
5292 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005293 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5294 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005295 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005296 }
5297
5298 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005299 NumOutputs = OutputDecls.size();
5300 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005301
5302 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005303 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5304 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5305 ClobberRegs.end());
5306 Clobbers.assign(ClobberRegs.size(), std::string());
5307 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5308 raw_string_ostream OS(Clobbers[I]);
5309 IP->printRegName(OS, ClobberRegs[I]);
5310 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005311
5312 // Merge the various outputs and inputs. Output are expected first.
5313 if (NumOutputs || NumInputs) {
5314 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005315 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005316 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005317 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005318 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005319 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005320 }
5321 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005322 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005323 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005324 }
5325 }
5326
5327 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005328 std::string AsmStringIR;
5329 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005330 StringRef ASMString =
5331 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5332 const char *AsmStart = ASMString.begin();
5333 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005334 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005335 for (const AsmRewrite &AR : AsmStrRewrites) {
5336 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005337 if (Kind == AOK_Delete)
5338 continue;
5339
David Majnemer8114c1a2014-06-23 02:17:16 +00005340 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005341 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005342
Chad Rosier120eefd2013-03-19 17:32:17 +00005343 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005344 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005345 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005346
Chad Rosier37e755c2012-10-23 17:43:43 +00005347 // Skip the original expression.
5348 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005349 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005350 continue;
5351 }
5352
Chad Rosierff10ed12013-04-12 16:26:42 +00005353 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005354 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005355 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005356 default:
5357 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005358 case AOK_Imm:
David Majnemer8114c1a2014-06-23 02:17:16 +00005359 OS << "$$" << AR.Val;
Chad Rosier11c42f22012-10-26 18:04:20 +00005360 break;
5361 case AOK_ImmPrefix:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005362 OS << "$$";
Chad Rosier8bce6642012-10-18 15:49:34 +00005363 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005364 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005365 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005366 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005367 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005368 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005369 break;
5370 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005371 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005372 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005373 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005374 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005375 default: break;
5376 case 8: OS << "byte ptr "; break;
5377 case 16: OS << "word ptr "; break;
5378 case 32: OS << "dword ptr "; break;
5379 case 64: OS << "qword ptr "; break;
5380 case 80: OS << "xword ptr "; break;
5381 case 128: OS << "xmmword ptr "; break;
5382 case 256: OS << "ymmword ptr "; break;
5383 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005384 break;
5385 case AOK_Emit:
5386 OS << ".byte";
5387 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005388 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005389 // MS alignment directives are measured in bytes. If the native assembler
5390 // measures alignment in bytes, we can pass it straight through.
5391 OS << ".align";
5392 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5393 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005394
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005395 // Alignment is in log2 form, so print that instead and skip the original
5396 // immediate.
5397 unsigned Val = AR.Val;
5398 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005399 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005400 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5401 break;
5402 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005403 case AOK_EVEN:
5404 OS << ".even";
5405 break;
Chad Rosierf0e87202012-10-25 20:41:34 +00005406 case AOK_DotOperator:
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005407 // Insert the dot if the user omitted it.
Alp Tokere69170a2014-06-26 22:52:05 +00005408 OS.flush();
5409 if (AsmStringIR.back() != '.')
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005410 OS << '.';
David Majnemer8114c1a2014-06-23 02:17:16 +00005411 OS << AR.Val;
Chad Rosierf0e87202012-10-25 20:41:34 +00005412 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005413 case AOK_EndOfStatement:
5414 OS << "\n\t";
5415 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005416 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005417
Chad Rosier8bce6642012-10-18 15:49:34 +00005418 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005419 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005420 }
5421
5422 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005423 if (AsmStart != AsmEnd)
5424 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005425
5426 AsmString = OS.str();
5427 return false;
5428}
5429
Pete Cooper80d21cb2015-06-22 19:35:57 +00005430namespace llvm {
5431namespace MCParserUtils {
5432
5433/// Returns whether the given symbol is used anywhere in the given expression,
5434/// or subexpressions.
5435static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5436 switch (Value->getKind()) {
5437 case MCExpr::Binary: {
5438 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5439 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5440 isSymbolUsedInExpression(Sym, BE->getRHS());
5441 }
5442 case MCExpr::Target:
5443 case MCExpr::Constant:
5444 return false;
5445 case MCExpr::SymbolRef: {
5446 const MCSymbol &S =
5447 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5448 if (S.isVariable())
5449 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5450 return &S == Sym;
5451 }
5452 case MCExpr::Unary:
5453 return isSymbolUsedInExpression(
5454 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5455 }
5456
5457 llvm_unreachable("Unknown expr kind!");
5458}
5459
5460bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5461 MCAsmParser &Parser, MCSymbol *&Sym,
5462 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005463
5464 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005465 SMLoc EqualLoc = Parser.getTok().getLoc();
Pete Cooper80d21cb2015-06-22 19:35:57 +00005466
5467 if (Parser.parseExpression(Value)) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00005468 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005469 }
5470
5471 // Note: we don't count b as used in "a = b". This is to allow
5472 // a = b
5473 // b = c
5474
Nirav Dave1a9044b2016-10-24 14:35:29 +00005475 if (Parser.parseToken(AsmToken::EndOfStatement))
5476 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00005477
5478 // Validate that the LHS is allowed to be a variable (either it has not been
5479 // used as a symbol, or it is an absolute symbol).
5480 Sym = Parser.getContext().lookupSymbol(Name);
5481 if (Sym) {
5482 // Diagnose assignment to a label.
5483 //
5484 // FIXME: Diagnostics. Note the location of the definition as a label.
5485 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5486 if (isSymbolUsedInExpression(Sym, Value))
5487 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005488 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5489 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005490 ; // Allow redefinitions of undefined symbols only used in directives.
5491 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5492 ; // Allow redefinitions of variables that haven't yet been used.
5493 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5494 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5495 else if (!Sym->isVariable())
5496 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5497 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5498 return Parser.Error(EqualLoc,
5499 "invalid reassignment of non-absolute variable '" +
5500 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005501 } else if (Name == ".") {
Rafael Espindola7ae65d82015-11-04 23:59:18 +00005502 Parser.getStreamer().emitValueToOffset(Value, 0);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005503 return false;
5504 } else
5505 Sym = Parser.getContext().getOrCreateSymbol(Name);
5506
5507 Sym->setRedefinable(allow_redef);
5508
5509 return false;
5510}
5511
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005512} // end namespace MCParserUtils
5513} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005514
Daniel Dunbar01e36072010-07-17 02:26:10 +00005515/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005516MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
5517 MCStreamer &Out, const MCAsmInfo &MAI) {
Jim Grosbach345768c2011-08-16 18:33:49 +00005518 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005519}