blob: 90a210f364dc98583b866d20c111b89d1772af8b [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;
Weiming Zhaocf26d562016-12-01 18:00:36 +0000976 if (SymbolName.empty())
977 return true;
978
Hans Wennborgce69d772013-10-18 20:46:28 +0000979 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +0000980
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000981 // Lookup the symbol variant if used.
David Peixotto8ad70b32013-12-04 22:43:20 +0000982 if (Split.second.size()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000983 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +0000984 if (Variant != MCSymbolRefExpr::VK_Invalid) {
985 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +0000986 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +0000987 Variant = MCSymbolRefExpr::VK_None;
988 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +0000989 return Error(SMLoc::getFromPointer(Split.second.begin()),
990 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000991 }
992 }
Daniel Dunbar55992562010-03-15 23:51:06 +0000993
Jim Grosbach6f482002015-05-18 18:43:14 +0000994 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +0000995
Daniel Dunbard20cda02009-10-16 01:34:54 +0000996 // If this is an absolute variable reference, substitute it now to preserve
997 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +0000998 if (Sym->isVariable() &&
999 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +00001000 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +00001001 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +00001002
Vedant Kumar86dbd922015-08-31 17:44:53 +00001003 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +00001004 return false;
1005 }
1006
1007 // Otherwise create a symbol ref.
Jim Grosbach13760bd2015-05-30 01:25:56 +00001008 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Chris Lattner78db3622009-06-22 05:51:26 +00001009 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001010 }
David Woodhousef42a6662014-02-01 16:20:54 +00001011 case AsmToken::BigNum:
1012 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001013 case AsmToken::Integer: {
1014 SMLoc Loc = getTok().getLoc();
1015 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001016 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001017 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001018 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001019 // Look for 'b' or 'f' following an Integer as a directional label
1020 if (Lexer.getKind() == AsmToken::Identifier) {
1021 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001022 // Lookup the symbol variant if used.
1023 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1024 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1025 if (Split.first.size() != IDVal.size()) {
1026 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001027 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001028 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001029 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001030 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001031 if (IDVal == "f" || IDVal == "b") {
1032 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001033 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001034 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001035 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001036 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001037 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001038 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001039 Lex(); // Eat identifier.
1040 }
1041 }
Chris Lattner78db3622009-06-22 05:51:26 +00001042 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001043 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001044 case AsmToken::Real: {
1045 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001046 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001047 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001048 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001049 Lex(); // Eat token.
1050 return false;
1051 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001052 case AsmToken::Dot: {
1053 // This is a '.' reference, which references the current PC. Emit a
1054 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001055 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001056 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001057 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001058 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001059 Lex(); // Eat identifier.
1060 return false;
1061 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001062 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001063 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001064 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001065 case AsmToken::LBrac:
1066 if (!PlatformParser->HasBracketExpressions())
1067 return TokError("brackets expression not supported on this target");
1068 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001069 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001070 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001071 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001072 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001073 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001074 Res = MCUnaryExpr::createMinus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001075 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001076 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001077 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001078 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001079 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001080 Res = MCUnaryExpr::createPlus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001081 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001082 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001083 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001084 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001085 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001086 Res = MCUnaryExpr::createNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001087 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001088 // MIPS unary expression operators. The lexer won't generate these tokens if
1089 // MCAsmInfo::HasMipsExpressions is false for the target.
1090 case AsmToken::PercentCall16:
1091 case AsmToken::PercentCall_Hi:
1092 case AsmToken::PercentCall_Lo:
1093 case AsmToken::PercentDtprel_Hi:
1094 case AsmToken::PercentDtprel_Lo:
1095 case AsmToken::PercentGot:
1096 case AsmToken::PercentGot_Disp:
1097 case AsmToken::PercentGot_Hi:
1098 case AsmToken::PercentGot_Lo:
1099 case AsmToken::PercentGot_Ofst:
1100 case AsmToken::PercentGot_Page:
1101 case AsmToken::PercentGottprel:
1102 case AsmToken::PercentGp_Rel:
1103 case AsmToken::PercentHi:
1104 case AsmToken::PercentHigher:
1105 case AsmToken::PercentHighest:
1106 case AsmToken::PercentLo:
1107 case AsmToken::PercentNeg:
1108 case AsmToken::PercentPcrel_Hi:
1109 case AsmToken::PercentPcrel_Lo:
1110 case AsmToken::PercentTlsgd:
1111 case AsmToken::PercentTlsldm:
1112 case AsmToken::PercentTprel_Hi:
1113 case AsmToken::PercentTprel_Lo:
1114 Lex(); // Eat the operator.
1115 if (Lexer.isNot(AsmToken::LParen))
1116 return TokError("expected '(' after operator");
1117 Lex(); // Eat the operator.
1118 if (parseExpression(Res, EndLoc))
1119 return true;
1120 if (Lexer.isNot(AsmToken::RParen))
1121 return TokError("expected ')'");
1122 Lex(); // Eat the operator.
1123 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1124 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001125 }
1126}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001127
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001128bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001129 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001130 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001131}
1132
Daniel Dunbar55f16672010-09-17 02:47:07 +00001133const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001134AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001135 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001136 // Ask the target implementation about this expression first.
1137 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1138 if (NewE)
1139 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001140 // Recurse over the given expression, rebuilding it to apply the given variant
1141 // if there is exactly one symbol.
1142 switch (E->getKind()) {
1143 case MCExpr::Target:
1144 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001145 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001146
1147 case MCExpr::SymbolRef: {
1148 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1149
1150 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001151 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1152 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001153 return E;
1154 }
1155
Jim Grosbach13760bd2015-05-30 01:25:56 +00001156 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001157 }
1158
1159 case MCExpr::Unary: {
1160 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001161 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001162 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001163 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001164 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001165 }
1166
1167 case MCExpr::Binary: {
1168 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001169 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1170 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001171
1172 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001173 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001174
Jim Grosbach4b905842013-09-20 23:08:21 +00001175 if (!LHS)
1176 LHS = BE->getLHS();
1177 if (!RHS)
1178 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001179
Jim Grosbach13760bd2015-05-30 01:25:56 +00001180 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001181 }
1182 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001183
Craig Toppera2886c22012-02-07 05:05:23 +00001184 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001185}
1186
Jim Grosbach4b905842013-09-20 23:08:21 +00001187/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001188///
Jim Grosbachbd164242011-08-20 16:24:13 +00001189/// expr ::= expr &&,|| expr -> lowest.
1190/// expr ::= expr |,^,&,! expr
1191/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1192/// expr ::= expr <<,>> expr
1193/// expr ::= expr +,- expr
1194/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001195/// expr ::= primaryexpr
1196///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001197bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001198 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001199 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001200 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001201 return true;
1202
Daniel Dunbar55f16672010-09-17 02:47:07 +00001203 // As a special case, we support 'a op b @ modifier' by rewriting the
1204 // expression to include the modifier. This is inefficient, but in general we
1205 // expect users to use 'a@modifier op b'.
1206 if (Lexer.getKind() == AsmToken::At) {
1207 Lex();
1208
1209 if (Lexer.isNot(AsmToken::Identifier))
1210 return TokError("unexpected symbol modifier following '@'");
1211
1212 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001213 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001214 if (Variant == MCSymbolRefExpr::VK_Invalid)
1215 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1216
Jim Grosbach4b905842013-09-20 23:08:21 +00001217 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001218 if (!ModifiedRes) {
1219 return TokError("invalid modifier '" + getTok().getIdentifier() +
1220 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001221 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001222
Daniel Dunbar55f16672010-09-17 02:47:07 +00001223 Res = ModifiedRes;
1224 Lex();
1225 }
1226
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001227 // Try to constant fold it up front, if possible.
1228 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001229 if (Res->evaluateAsAbsolute(Value))
1230 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001231
1232 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001233}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001234
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001235bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001236 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001237 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001238}
1239
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001240bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1241 SMLoc &EndLoc) {
1242 if (parseParenExpr(Res, EndLoc))
1243 return true;
1244
1245 for (; ParenDepth > 0; --ParenDepth) {
1246 if (parseBinOpRHS(1, Res, EndLoc))
1247 return true;
1248
1249 // We don't Lex() the last RParen.
1250 // This is the same behavior as parseParenExpression().
1251 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001252 EndLoc = getTok().getEndLoc();
1253 if (parseToken(AsmToken::RParen,
1254 "expected ')' in parentheses expression"))
1255 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001256 }
1257 }
1258 return false;
1259}
1260
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001261bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001262 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001263
Daniel Dunbar75630b32009-06-30 02:10:03 +00001264 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001265 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001266 return true;
1267
Jim Grosbach13760bd2015-05-30 01:25:56 +00001268 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001269 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001270
1271 return false;
1272}
1273
David Majnemer0993e0b2015-10-26 03:15:34 +00001274static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1275 MCBinaryExpr::Opcode &Kind,
1276 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001277 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001278 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001279 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001280
Jim Grosbach4b905842013-09-20 23:08:21 +00001281 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001282 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001283 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001284 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001285 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001286 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001287 return 1;
1288
Jim Grosbach4b905842013-09-20 23:08:21 +00001289 // Low Precedence: |, &, ^
1290 //
1291 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001292 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001293 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001294 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001295 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001296 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001297 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001298 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001299 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001300 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001301
Jim Grosbach4b905842013-09-20 23:08:21 +00001302 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001303 case AsmToken::EqualEqual:
1304 Kind = MCBinaryExpr::EQ;
1305 return 3;
1306 case AsmToken::ExclaimEqual:
1307 case AsmToken::LessGreater:
1308 Kind = MCBinaryExpr::NE;
1309 return 3;
1310 case AsmToken::Less:
1311 Kind = MCBinaryExpr::LT;
1312 return 3;
1313 case AsmToken::LessEqual:
1314 Kind = MCBinaryExpr::LTE;
1315 return 3;
1316 case AsmToken::Greater:
1317 Kind = MCBinaryExpr::GT;
1318 return 3;
1319 case AsmToken::GreaterEqual:
1320 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001321 return 3;
1322
Jim Grosbach4b905842013-09-20 23:08:21 +00001323 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001324 case AsmToken::LessLess:
1325 Kind = MCBinaryExpr::Shl;
1326 return 4;
1327 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001328 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001329 return 4;
1330
Jim Grosbach4b905842013-09-20 23:08:21 +00001331 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001332 case AsmToken::Plus:
1333 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001334 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001335 case AsmToken::Minus:
1336 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001337 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001338
Jim Grosbach4b905842013-09-20 23:08:21 +00001339 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001340 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001341 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001342 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001343 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001344 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001345 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001346 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001347 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001348 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001349 }
1350}
1351
David Majnemer0993e0b2015-10-26 03:15:34 +00001352static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1353 MCBinaryExpr::Opcode &Kind,
1354 bool ShouldUseLogicalShr) {
1355 switch (K) {
1356 default:
1357 return 0; // not a binop.
1358
1359 // Lowest Precedence: &&, ||
1360 case AsmToken::AmpAmp:
1361 Kind = MCBinaryExpr::LAnd;
1362 return 2;
1363 case AsmToken::PipePipe:
1364 Kind = MCBinaryExpr::LOr;
1365 return 1;
1366
1367 // Low Precedence: ==, !=, <>, <, <=, >, >=
1368 case AsmToken::EqualEqual:
1369 Kind = MCBinaryExpr::EQ;
1370 return 3;
1371 case AsmToken::ExclaimEqual:
1372 case AsmToken::LessGreater:
1373 Kind = MCBinaryExpr::NE;
1374 return 3;
1375 case AsmToken::Less:
1376 Kind = MCBinaryExpr::LT;
1377 return 3;
1378 case AsmToken::LessEqual:
1379 Kind = MCBinaryExpr::LTE;
1380 return 3;
1381 case AsmToken::Greater:
1382 Kind = MCBinaryExpr::GT;
1383 return 3;
1384 case AsmToken::GreaterEqual:
1385 Kind = MCBinaryExpr::GTE;
1386 return 3;
1387
1388 // Low Intermediate Precedence: +, -
1389 case AsmToken::Plus:
1390 Kind = MCBinaryExpr::Add;
1391 return 4;
1392 case AsmToken::Minus:
1393 Kind = MCBinaryExpr::Sub;
1394 return 4;
1395
1396 // High Intermediate Precedence: |, &, ^
1397 //
1398 // FIXME: gas seems to support '!' as an infix operator?
1399 case AsmToken::Pipe:
1400 Kind = MCBinaryExpr::Or;
1401 return 5;
1402 case AsmToken::Caret:
1403 Kind = MCBinaryExpr::Xor;
1404 return 5;
1405 case AsmToken::Amp:
1406 Kind = MCBinaryExpr::And;
1407 return 5;
1408
1409 // Highest Precedence: *, /, %, <<, >>
1410 case AsmToken::Star:
1411 Kind = MCBinaryExpr::Mul;
1412 return 6;
1413 case AsmToken::Slash:
1414 Kind = MCBinaryExpr::Div;
1415 return 6;
1416 case AsmToken::Percent:
1417 Kind = MCBinaryExpr::Mod;
1418 return 6;
1419 case AsmToken::LessLess:
1420 Kind = MCBinaryExpr::Shl;
1421 return 6;
1422 case AsmToken::GreaterGreater:
1423 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1424 return 6;
1425 }
1426}
1427
1428unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1429 MCBinaryExpr::Opcode &Kind) {
1430 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1431 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1432 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1433}
1434
Jim Grosbach4b905842013-09-20 23:08:21 +00001435/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001436/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001437bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001438 SMLoc &EndLoc) {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001439 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001440 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001441 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001442
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001443 // If the next token is lower precedence than we are allowed to eat, return
1444 // successfully with what we ate already.
1445 if (TokPrec < Precedence)
1446 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001447
Sean Callanan686ed8d2010-01-19 20:22:31 +00001448 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001449
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001450 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001451 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001452 if (parsePrimaryExpr(RHS, EndLoc))
1453 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001454
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001455 // If BinOp binds less tightly with RHS than the operator after RHS, let
1456 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001457 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001458 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001459 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1460 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001461
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001462 // Merge LHS and RHS according to operator.
Jim Grosbach13760bd2015-05-30 01:25:56 +00001463 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001464 }
1465}
1466
Chris Lattner36e02122009-06-21 20:54:55 +00001467/// ParseStatement:
1468/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001469/// ::= Label* Directive ...Operands... EndOfStatement
1470/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001471bool AsmParser::parseStatement(ParseStatementInfo &Info,
1472 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001473 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001474 // Eat initial spaces and comments
1475 while (Lexer.is(AsmToken::Space))
1476 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001477 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001478 // if this is a line comment we can drop it safely
1479 if (getTok().getString().front() == '\r' ||
1480 getTok().getString().front() == '\n')
1481 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001482 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001483 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001484 }
Nirav Dave9263ae32016-08-02 19:17:54 +00001485 if (Lexer.is(AsmToken::Hash)) {
1486 // Seeing a hash here means that it was an end-of-line comment in
1487 // an asm syntax where hash's are not comment and the previous
1488 // statement parser did not check the end of statement. Relex as
1489 // EndOfStatement.
1490 StringRef CommentStr = parseStringToEndOfStatement();
1491 Lexer.Lex();
1492 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1493 return false;
1494 }
Nirav Davefd910412016-06-17 16:06:17 +00001495 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001496 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001497 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001498 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001499 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001500 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001501 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001502 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001503 if (Lexer.is(AsmToken::Integer)) {
1504 LocalLabelVal = getTok().getIntVal();
1505 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001506 if (!TheCondState.Ignore) {
1507 Lex(); // always eat a token
1508 return Error(IDLoc, "unexpected token at start of statement");
1509 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001510 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001511 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001512 IDVal = getTok().getString();
1513 Lex(); // Consume the integer token to be used as an identifier token.
1514 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001515 if (!TheCondState.Ignore) {
1516 Lex(); // always eat a token
1517 return Error(IDLoc, "unexpected token at start of statement");
1518 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001519 }
1520 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001521 } else if (Lexer.is(AsmToken::Dot)) {
1522 // Treat '.' as a valid identifier in this context.
1523 Lex();
1524 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001525 } else if (Lexer.is(AsmToken::LCurly)) {
1526 // Treat '{' as a valid identifier in this context.
1527 Lex();
1528 IDVal = "{";
1529
1530 } else if (Lexer.is(AsmToken::RCurly)) {
1531 // Treat '}' as a valid identifier in this context.
1532 Lex();
1533 IDVal = "}";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001534 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001535 if (!TheCondState.Ignore) {
1536 Lex(); // always eat a token
1537 return Error(IDLoc, "unexpected token at start of statement");
1538 }
Chris Lattner926885c2010-04-17 18:14:27 +00001539 IDVal = "";
1540 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001541
Chris Lattner926885c2010-04-17 18:14:27 +00001542 // Handle conditional assembly here before checking for skipping. We
1543 // have to do this so that .endif isn't skipped in a ".if 0" block for
1544 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001545 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001546 DirectiveKindMap.find(IDVal);
1547 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1548 ? DK_NO_DIRECTIVE
1549 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001550 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001551 default:
1552 break;
1553 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001554 case DK_IFEQ:
1555 case DK_IFGE:
1556 case DK_IFGT:
1557 case DK_IFLE:
1558 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001559 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001560 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001561 case DK_IFB:
1562 return parseDirectiveIfb(IDLoc, true);
1563 case DK_IFNB:
1564 return parseDirectiveIfb(IDLoc, false);
1565 case DK_IFC:
1566 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001567 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001568 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001569 case DK_IFNC:
1570 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001571 case DK_IFNES:
1572 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001573 case DK_IFDEF:
1574 return parseDirectiveIfdef(IDLoc, true);
1575 case DK_IFNDEF:
1576 case DK_IFNOTDEF:
1577 return parseDirectiveIfdef(IDLoc, false);
1578 case DK_ELSEIF:
1579 return parseDirectiveElseIf(IDLoc);
1580 case DK_ELSE:
1581 return parseDirectiveElse(IDLoc);
1582 case DK_ENDIF:
1583 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001584 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001585
Eli Bendersky88024712013-01-16 19:32:36 +00001586 // Ignore the statement if in the middle of inactive conditional
1587 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001588 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001589 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001590 return false;
1591 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001592
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001593 // FIXME: Recurse on local labels?
1594
1595 // See what kind of statement we have.
1596 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001597 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001598 if (!getTargetParser().isLabel(ID))
1599 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001600 if (checkForValidSection())
1601 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001602
Chris Lattner36e02122009-06-21 20:54:55 +00001603 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001604 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001605
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001606 // Diagnose attempt to use '.' as a label.
1607 if (IDVal == ".")
1608 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1609
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001610 // Diagnose attempt to use a variable as a label.
1611 //
1612 // FIXME: Diagnostics. Note the location of the definition as a label.
1613 // FIXME: This doesn't diagnose assignment to a symbol which has been
1614 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001615 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001616 if (LocalLabelVal == -1) {
1617 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001618 StringRef RewrittenLabel =
1619 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1620 assert(RewrittenLabel.size() &&
1621 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001622 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1623 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001624 IDVal = RewrittenLabel;
1625 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001626 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001627 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001628 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
David Majnemer58cb80c2014-12-24 10:27:50 +00001629
1630 Sym->redefineIfPossible();
1631
Daniel Dunbardeb7ba92010-05-05 19:01:00 +00001632 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001633 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencer530ce852010-10-09 11:00:50 +00001634
Nirav Dave9263ae32016-08-02 19:17:54 +00001635 // End of Labels should be treated as end of line for lexing
1636 // purposes but that information is not available to the Lexer who
1637 // does not understand Labels. This may cause us to see a Hash
1638 // here instead of a preprocessor line comment.
1639 if (getTok().is(AsmToken::Hash)) {
1640 StringRef CommentStr = parseStringToEndOfStatement();
1641 Lexer.Lex();
1642 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1643 }
1644
Nirav Dave8ea792d2016-07-13 14:03:12 +00001645 // Consume any end of statement token, if present, to avoid spurious
1646 // AddBlankLine calls().
1647 if (getTok().is(AsmToken::EndOfStatement)) {
1648 Lex();
1649 }
1650
Daniel Dunbare73b2672009-08-26 22:13:22 +00001651 // Emit the label.
Chad Rosierf3feab32013-01-07 20:34:12 +00001652 if (!ParsingInlineAsm)
1653 Out.EmitLabel(Sym);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001654
Kevin Enderbye7739d42011-12-09 18:09:40 +00001655 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001656 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001657 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001658 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1659 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001660
Tim Northover1744d0a2013-10-25 12:49:50 +00001661 getTargetParser().onLabelParsed(Sym);
1662
Eli Friedman0f4871d2012-10-22 23:58:19 +00001663 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001664 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001665
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001666 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001667 if (!getTargetParser().equalIsAsmAssignment())
1668 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001669 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001670 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001671
Jim Grosbach4b905842013-09-20 23:08:21 +00001672 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001673
1674 default: // Normal instruction or directive.
1675 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001676 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001677
1678 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001679 if (areMacrosEnabled())
1680 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1681 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001682 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001683
Michael J. Spencer530ce852010-10-09 11:00:50 +00001684 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001685
Eli Bendersky17233942013-01-15 22:59:42 +00001686 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001687 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001688 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001689 //
Eli Bendersky17233942013-01-15 22:59:42 +00001690 // 1. The target-specific assembly parser. Some directives are target
1691 // specific or may potentially behave differently on certain targets.
1692 // 2. Asm parser extensions. For example, platform-specific parsers
1693 // (like the ELF parser) register themselves as extensions.
1694 // 3. The generic directive parser implemented by this class. These are
1695 // all the directives that behave in a target and platform independent
1696 // manner, or at least have a default behavior that's shared between
1697 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001698
Oliver Stannard21718282016-07-26 14:19:47 +00001699 getTargetParser().flushPendingInstructions(getStreamer());
1700
Nirav Dave2364748a2016-09-16 18:30:20 +00001701 SMLoc StartTokLoc = getTok().getLoc();
1702 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1703
1704 if (hasPendingError())
1705 return true;
1706 // Currently the return value should be true if we are
1707 // uninterested but as this is at odds with the standard parsing
1708 // convention (return true = error) we have instances of a parsed
1709 // directive that fails returning true as an error. Catch these
1710 // cases as best as possible errors here.
1711 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1712 return true;
1713 // Return if we did some parsing or believe we succeeded.
1714 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001715 return false;
1716
Alp Tokercb402912014-01-24 17:20:08 +00001717 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001718 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001719 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1720 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001721 if (Handler.first)
1722 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1723
1724 // Finally, if no one else is interested in this directive, it must be
1725 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001726 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001727 default:
1728 break;
1729 case DK_SET:
1730 case DK_EQU:
1731 return parseDirectiveSet(IDVal, true);
1732 case DK_EQUIV:
1733 return parseDirectiveSet(IDVal, false);
1734 case DK_ASCII:
1735 return parseDirectiveAscii(IDVal, false);
1736 case DK_ASCIZ:
1737 case DK_STRING:
1738 return parseDirectiveAscii(IDVal, true);
1739 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001740 case DK_DC_B:
1741 return parseDirectiveValue(IDVal, 1);
1742 case DK_DC:
1743 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001744 case DK_SHORT:
1745 case DK_VALUE:
1746 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001747 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001748 case DK_LONG:
1749 case DK_INT:
1750 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001751 case DK_DC_L:
1752 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001753 case DK_QUAD:
1754 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001755 return parseDirectiveValue(IDVal, 8);
1756 case DK_DC_A:
1757 return parseDirectiveValue(IDVal,
1758 getContext().getAsmInfo()->getPointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001759 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001760 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001761 case DK_SINGLE:
1762 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001763 case DK_DC_S:
1764 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle);
Jim Grosbach4b905842013-09-20 23:08:21 +00001765 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001766 case DK_DC_D:
1767 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble);
Jim Grosbach4b905842013-09-20 23:08:21 +00001768 case DK_ALIGN: {
1769 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1770 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1771 }
1772 case DK_ALIGN32: {
1773 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1774 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1775 }
1776 case DK_BALIGN:
1777 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1778 case DK_BALIGNW:
1779 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1780 case DK_BALIGNL:
1781 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1782 case DK_P2ALIGN:
1783 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1784 case DK_P2ALIGNW:
1785 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1786 case DK_P2ALIGNL:
1787 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1788 case DK_ORG:
1789 return parseDirectiveOrg();
1790 case DK_FILL:
1791 return parseDirectiveFill();
1792 case DK_ZERO:
1793 return parseDirectiveZero();
1794 case DK_EXTERN:
1795 eatToEndOfStatement(); // .extern is the default, ignore it.
1796 return false;
1797 case DK_GLOBL:
1798 case DK_GLOBAL:
1799 return parseDirectiveSymbolAttribute(MCSA_Global);
1800 case DK_LAZY_REFERENCE:
1801 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1802 case DK_NO_DEAD_STRIP:
1803 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1804 case DK_SYMBOL_RESOLVER:
1805 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1806 case DK_PRIVATE_EXTERN:
1807 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1808 case DK_REFERENCE:
1809 return parseDirectiveSymbolAttribute(MCSA_Reference);
1810 case DK_WEAK_DEFINITION:
1811 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1812 case DK_WEAK_REFERENCE:
1813 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1814 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1815 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1816 case DK_COMM:
1817 case DK_COMMON:
1818 return parseDirectiveComm(/*IsLocal=*/false);
1819 case DK_LCOMM:
1820 return parseDirectiveComm(/*IsLocal=*/true);
1821 case DK_ABORT:
1822 return parseDirectiveAbort();
1823 case DK_INCLUDE:
1824 return parseDirectiveInclude();
1825 case DK_INCBIN:
1826 return parseDirectiveIncbin();
1827 case DK_CODE16:
1828 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001829 return TokError(Twine(IDVal) +
1830 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001831 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001832 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001833 case DK_IRP:
1834 return parseDirectiveIrp(IDLoc);
1835 case DK_IRPC:
1836 return parseDirectiveIrpc(IDLoc);
1837 case DK_ENDR:
1838 return parseDirectiveEndr(IDLoc);
1839 case DK_BUNDLE_ALIGN_MODE:
1840 return parseDirectiveBundleAlignMode();
1841 case DK_BUNDLE_LOCK:
1842 return parseDirectiveBundleLock();
1843 case DK_BUNDLE_UNLOCK:
1844 return parseDirectiveBundleUnlock();
1845 case DK_SLEB128:
1846 return parseDirectiveLEB128(true);
1847 case DK_ULEB128:
1848 return parseDirectiveLEB128(false);
1849 case DK_SPACE:
1850 case DK_SKIP:
1851 return parseDirectiveSpace(IDVal);
1852 case DK_FILE:
1853 return parseDirectiveFile(IDLoc);
1854 case DK_LINE:
1855 return parseDirectiveLine();
1856 case DK_LOC:
1857 return parseDirectiveLoc();
1858 case DK_STABS:
1859 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001860 case DK_CV_FILE:
1861 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001862 case DK_CV_FUNC_ID:
1863 return parseDirectiveCVFuncId();
1864 case DK_CV_INLINE_SITE_ID:
1865 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001866 case DK_CV_LOC:
1867 return parseDirectiveCVLoc();
1868 case DK_CV_LINETABLE:
1869 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00001870 case DK_CV_INLINE_LINETABLE:
1871 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00001872 case DK_CV_DEF_RANGE:
1873 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001874 case DK_CV_STRINGTABLE:
1875 return parseDirectiveCVStringTable();
1876 case DK_CV_FILECHECKSUMS:
1877 return parseDirectiveCVFileChecksums();
Jim Grosbach4b905842013-09-20 23:08:21 +00001878 case DK_CFI_SECTIONS:
1879 return parseDirectiveCFISections();
1880 case DK_CFI_STARTPROC:
1881 return parseDirectiveCFIStartProc();
1882 case DK_CFI_ENDPROC:
1883 return parseDirectiveCFIEndProc();
1884 case DK_CFI_DEF_CFA:
1885 return parseDirectiveCFIDefCfa(IDLoc);
1886 case DK_CFI_DEF_CFA_OFFSET:
1887 return parseDirectiveCFIDefCfaOffset();
1888 case DK_CFI_ADJUST_CFA_OFFSET:
1889 return parseDirectiveCFIAdjustCfaOffset();
1890 case DK_CFI_DEF_CFA_REGISTER:
1891 return parseDirectiveCFIDefCfaRegister(IDLoc);
1892 case DK_CFI_OFFSET:
1893 return parseDirectiveCFIOffset(IDLoc);
1894 case DK_CFI_REL_OFFSET:
1895 return parseDirectiveCFIRelOffset(IDLoc);
1896 case DK_CFI_PERSONALITY:
1897 return parseDirectiveCFIPersonalityOrLsda(true);
1898 case DK_CFI_LSDA:
1899 return parseDirectiveCFIPersonalityOrLsda(false);
1900 case DK_CFI_REMEMBER_STATE:
1901 return parseDirectiveCFIRememberState();
1902 case DK_CFI_RESTORE_STATE:
1903 return parseDirectiveCFIRestoreState();
1904 case DK_CFI_SAME_VALUE:
1905 return parseDirectiveCFISameValue(IDLoc);
1906 case DK_CFI_RESTORE:
1907 return parseDirectiveCFIRestore(IDLoc);
1908 case DK_CFI_ESCAPE:
1909 return parseDirectiveCFIEscape();
1910 case DK_CFI_SIGNAL_FRAME:
1911 return parseDirectiveCFISignalFrame();
1912 case DK_CFI_UNDEFINED:
1913 return parseDirectiveCFIUndefined(IDLoc);
1914 case DK_CFI_REGISTER:
1915 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00001916 case DK_CFI_WINDOW_SAVE:
1917 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00001918 case DK_MACROS_ON:
1919 case DK_MACROS_OFF:
1920 return parseDirectiveMacrosOnOff(IDVal);
1921 case DK_MACRO:
1922 return parseDirectiveMacro(IDLoc);
Nico Weber155dccd12014-07-24 17:08:39 +00001923 case DK_EXITM:
1924 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001925 case DK_ENDM:
1926 case DK_ENDMACRO:
1927 return parseDirectiveEndMacro(IDVal);
1928 case DK_PURGEM:
1929 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00001930 case DK_END:
1931 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00001932 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00001933 return parseDirectiveError(IDLoc, false);
1934 case DK_ERROR:
1935 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00001936 case DK_WARNING:
1937 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00001938 case DK_RELOC:
1939 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001940 case DK_DCB:
1941 case DK_DCB_W:
1942 return parseDirectiveDCB(IDVal, 2);
1943 case DK_DCB_B:
1944 return parseDirectiveDCB(IDVal, 1);
1945 case DK_DCB_D:
1946 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble);
1947 case DK_DCB_L:
1948 return parseDirectiveDCB(IDVal, 4);
1949 case DK_DCB_S:
1950 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle);
Petr Hosek731bb9c2016-08-23 21:34:53 +00001951 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001952 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00001953 return TokError(Twine(IDVal) +
1954 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00001955 case DK_DS:
1956 case DK_DS_W:
1957 return parseDirectiveDS(IDVal, 2);
1958 case DK_DS_B:
1959 return parseDirectiveDS(IDVal, 1);
1960 case DK_DS_D:
1961 return parseDirectiveDS(IDVal, 8);
1962 case DK_DS_L:
1963 case DK_DS_S:
1964 return parseDirectiveDS(IDVal, 4);
1965 case DK_DS_P:
1966 case DK_DS_X:
1967 return parseDirectiveDS(IDVal, 12);
Eli Friedman20b02642010-07-19 04:17:25 +00001968 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00001969
Jim Grosbach758e0cc2012-05-01 18:38:27 +00001970 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00001971 }
Chris Lattner36e02122009-06-21 20:54:55 +00001972
Chad Rosierc7f552c2013-02-12 21:33:51 +00001973 // __asm _emit or __asm __emit
1974 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1975 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001976 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00001977
1978 // __asm align
1979 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001980 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00001981
Michael Zuckerman02ecd432015-12-13 17:07:23 +00001982 if (ParsingInlineAsm && (IDVal == "even"))
1983 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00001984 if (checkForValidSection())
1985 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001986
Chris Lattner7cbfa442010-05-19 23:34:33 +00001987 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00001988 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00001989 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00001990 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
1991 Info.ParsedOperands);
1992 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00001993
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001994 // Dump the parsed representation, if requested.
1995 if (getShowParsedOperands()) {
1996 SmallString<256> Str;
1997 raw_svector_ostream OS(Str);
1998 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001999 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002000 if (i != 0)
2001 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002002 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002003 }
2004 OS << "]";
2005
Jim Grosbach4b905842013-09-20 23:08:21 +00002006 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002007 }
2008
Nirav Dave2364748a2016-09-16 18:30:20 +00002009 // Fail even if ParseInstruction erroneously returns false.
2010 if (hasPendingError() || ParseHadError)
2011 return true;
2012
Oliver Stannard8b273082014-06-19 15:52:37 +00002013 // If we are generating dwarf for the current section then generate a .loc
2014 // directive for the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002015 if (!ParseHadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002016 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002017 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002018 unsigned Line;
2019 if (ActiveMacros.empty())
2020 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2021 else
Frederic Riss16238d92015-06-25 21:57:33 +00002022 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2023 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002024
Eli Bendersky88024712013-01-16 19:32:36 +00002025 // If we previously parsed a cpp hash file line comment then make sure the
2026 // current Dwarf File is for the CppHashFilename if not then emit the
2027 // Dwarf File table for it and adjust the line number for the .loc.
Tim Northoverc0bef992016-04-13 19:46:54 +00002028 if (CppHashInfo.Filename.size()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002029 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002030 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002031 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002032
Jim Grosbach4b905842013-09-20 23:08:21 +00002033 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
2034 // cache with the different Loc from the call above we save the last
2035 // info we queried here with SrcMgr.FindLineNumber().
2036 unsigned CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002037 if (LastQueryIDLoc == CppHashInfo.Loc &&
2038 LastQueryBuffer == CppHashInfo.Buf)
Jim Grosbach4b905842013-09-20 23:08:21 +00002039 CppHashLocLineNo = LastQueryLine;
2040 else {
Tim Northoverc0bef992016-04-13 19:46:54 +00002041 CppHashLocLineNo =
2042 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002043 LastQueryLine = CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002044 LastQueryIDLoc = CppHashInfo.Loc;
2045 LastQueryBuffer = CppHashInfo.Buf;
Jim Grosbach4b905842013-09-20 23:08:21 +00002046 }
Tim Northoverc0bef992016-04-13 19:46:54 +00002047 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002048 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002049
Jim Grosbach4b905842013-09-20 23:08:21 +00002050 getStreamer().EmitDwarfLocDirective(
2051 getContext().getGenDwarfFileNumber(), Line, 0,
2052 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2053 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002054 }
2055
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002056 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002057 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002058 uint64_t ErrorInfo;
Nirav Dave2364748a2016-09-16 18:30:20 +00002059 if (getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
2060 Info.ParsedOperands, Out,
2061 ErrorInfo, ParsingInlineAsm))
2062 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002063 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002064 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002065}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002066
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002067// Parse and erase curly braces marking block start/end
2068bool
2069AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2070 // Identify curly brace marking block start/end
2071 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2072 return false;
2073
2074 SMLoc StartLoc = Lexer.getLoc();
2075 Lex(); // Eat the brace
2076 if (Lexer.is(AsmToken::EndOfStatement))
2077 Lex(); // Eat EndOfStatement following the brace
2078
2079 // Erase the block start/end brace from the output asm string
2080 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2081 StartLoc.getPointer());
2082 return true;
2083}
2084
Jim Grosbach4b905842013-09-20 23:08:21 +00002085/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002086/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002087bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002088 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002089 // Lexer only ever emits HashDirective if it fully formed if it's
2090 // done the checking already so this is an internal error.
2091 assert(getTok().is(AsmToken::Integer) &&
2092 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002093 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002094 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002095 assert(getTok().is(AsmToken::String) &&
2096 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002097 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002098 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002099
Kevin Enderby72553612011-09-13 23:45:18 +00002100 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002101 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002102
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002103 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002104 CppHashInfo.Loc = L;
2105 CppHashInfo.Filename = Filename;
2106 CppHashInfo.LineNumber = LineNumber;
2107 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002108 return false;
2109}
2110
Jim Grosbach4b905842013-09-20 23:08:21 +00002111/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002112/// for the Filename and LineNo if any in the diagnostic.
2113void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002114 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002115 raw_ostream &OS = errs();
2116
2117 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002118 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002119 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2120 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002121 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002122
Jim Grosbach4b905842013-09-20 23:08:21 +00002123 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002124 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002125 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2126 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2127 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002128 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2129 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002130 }
2131
Eric Christophera7c32732012-12-18 00:30:54 +00002132 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002133 // manager changed or buffer changed (like in a nested include) then just
2134 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002135 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002136 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002137 if (Parser->SavedDiagHandler)
2138 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2139 else
Craig Topper353eda42014-04-24 06:44:33 +00002140 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002141 return;
2142 }
2143
Eric Christophera7c32732012-12-18 00:30:54 +00002144 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002145 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2146 // for the diagnostic.
2147 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002148
2149 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2150 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002151 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002152 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002153 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002154
Jim Grosbach4b905842013-09-20 23:08:21 +00002155 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2156 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002157 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002158
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002159 if (Parser->SavedDiagHandler)
2160 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2161 else
Craig Topper353eda42014-04-24 06:44:33 +00002162 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002163}
2164
Rafael Espindola2c064482012-08-21 18:29:30 +00002165// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2166// difference being that that function accepts '@' as part of identifiers and
2167// we can't do that. AsmLexer.cpp should probably be changed to handle
2168// '@' as a special case when needed.
2169static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002170 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2171 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002172}
2173
Rafael Espindola34b9c512012-06-03 23:57:14 +00002174bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002175 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002176 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002177 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002178 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002179 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002180 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002181 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002182
Preston Gurd05500642012-09-19 20:36:12 +00002183 // A macro without parameters is handled differently on Darwin:
2184 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002185 while (!Body.empty()) {
2186 // Scan for the next substitution.
2187 std::size_t End = Body.size(), Pos = 0;
2188 for (; Pos != End; ++Pos) {
2189 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002190 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002191 // This macro has no parameters, look for $0, $1, etc.
2192 if (Body[Pos] != '$' || Pos + 1 == End)
2193 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002194
Rafael Espindola1134ab232011-06-05 02:43:45 +00002195 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002196 if (Next == '$' || Next == 'n' ||
2197 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002198 break;
2199 } else {
2200 // This macro has parameters, look for \foo, \bar, etc.
2201 if (Body[Pos] == '\\' && Pos + 1 != End)
2202 break;
2203 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002204 }
2205
2206 // Add the prefix.
2207 OS << Body.slice(0, Pos);
2208
2209 // Check if we reached the end.
2210 if (Pos == End)
2211 break;
2212
Benjamin Kramer513e7442014-02-20 13:36:32 +00002213 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002214 switch (Body[Pos + 1]) {
2215 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002216 case '$':
2217 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002218 break;
2219
Jim Grosbach4b905842013-09-20 23:08:21 +00002220 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002221 case 'n':
2222 OS << A.size();
2223 break;
2224
Jim Grosbach4b905842013-09-20 23:08:21 +00002225 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002226 default: {
2227 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002228 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002229 if (Index >= A.size())
2230 break;
2231
2232 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002233 for (const AsmToken &Token : A[Index])
2234 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002235 break;
2236 }
2237 }
2238 Pos += 2;
2239 } else {
2240 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002241
2242 // Check for the \@ pseudo-variable.
2243 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002244 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002245 else
2246 while (isIdentifierChar(Body[I]) && I + 1 != End)
2247 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002248
Jim Grosbach4b905842013-09-20 23:08:21 +00002249 const char *Begin = Body.data() + Pos + 1;
2250 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002251 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002252
Toma Tabacu217116e2015-04-27 10:50:29 +00002253 if (Argument == "@") {
2254 OS << NumOfMacroInstantiations;
2255 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002256 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002257 for (; Index < NParameters; ++Index)
2258 if (Parameters[Index].Name == Argument)
2259 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002260
Toma Tabacu217116e2015-04-27 10:50:29 +00002261 if (Index == NParameters) {
2262 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2263 Pos += 3;
2264 else {
2265 OS << '\\' << Argument;
2266 Pos = I;
2267 }
2268 } else {
2269 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002270 for (const AsmToken &Token : A[Index])
Toma Tabacu217116e2015-04-27 10:50:29 +00002271 // We expect no quotes around the string's contents when
2272 // parsing for varargs.
Craig Topper84008482015-10-10 05:38:14 +00002273 if (Token.getKind() != AsmToken::String || VarargParameter)
2274 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002275 else
Craig Topper84008482015-10-10 05:38:14 +00002276 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002277
2278 Pos += 1 + Argument.size();
2279 }
Preston Gurd05500642012-09-19 20:36:12 +00002280 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002281 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002282 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002283 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002284 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002285
Rafael Espindola1134ab232011-06-05 02:43:45 +00002286 return false;
2287}
Daniel Dunbar43235712010-07-18 18:54:11 +00002288
Nico Weber2a8f9222014-07-24 16:29:04 +00002289MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002290 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002291 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002292 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002293
Jim Grosbach4b905842013-09-20 23:08:21 +00002294static bool isOperator(AsmToken::TokenKind kind) {
2295 switch (kind) {
2296 default:
2297 return false;
2298 case AsmToken::Plus:
2299 case AsmToken::Minus:
2300 case AsmToken::Tilde:
2301 case AsmToken::Slash:
2302 case AsmToken::Star:
2303 case AsmToken::Dot:
2304 case AsmToken::Equal:
2305 case AsmToken::EqualEqual:
2306 case AsmToken::Pipe:
2307 case AsmToken::PipePipe:
2308 case AsmToken::Caret:
2309 case AsmToken::Amp:
2310 case AsmToken::AmpAmp:
2311 case AsmToken::Exclaim:
2312 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002313 case AsmToken::Less:
2314 case AsmToken::LessEqual:
2315 case AsmToken::LessLess:
2316 case AsmToken::LessGreater:
2317 case AsmToken::Greater:
2318 case AsmToken::GreaterEqual:
2319 case AsmToken::GreaterGreater:
2320 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002321 }
2322}
2323
David Majnemer16252452014-01-29 00:07:39 +00002324namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002325
David Majnemer16252452014-01-29 00:07:39 +00002326class AsmLexerSkipSpaceRAII {
2327public:
2328 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2329 Lexer.setSkipSpace(SkipSpace);
2330 }
2331
2332 ~AsmLexerSkipSpaceRAII() {
2333 Lexer.setSkipSpace(true);
2334 }
2335
2336private:
2337 AsmLexer &Lexer;
2338};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002339
2340} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002341
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002342bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2343
2344 if (Vararg) {
2345 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2346 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002347 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002348 }
2349 return false;
2350 }
2351
Rafael Espindola768b41c2012-06-15 14:02:34 +00002352 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002353
David Majnemer16252452014-01-29 00:07:39 +00002354 // Darwin doesn't use spaces to delmit arguments.
2355 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002356
Scott Egertona1fa68a2016-02-11 13:48:49 +00002357 bool SpaceEaten;
2358
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002359 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002360 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002361 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002362 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002363
Scott Egertona1fa68a2016-02-11 13:48:49 +00002364 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002365
Scott Egertona1fa68a2016-02-11 13:48:49 +00002366 if (Lexer.is(AsmToken::Comma))
2367 break;
2368
2369 if (Lexer.is(AsmToken::Space)) {
2370 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002371 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002372 }
Preston Gurd05500642012-09-19 20:36:12 +00002373
2374 // Spaces can delimit parameters, but could also be part an expression.
2375 // If the token after a space is an operator, add the token and the next
2376 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002377 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002378 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002379 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002380 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002381
Scott Egertona1fa68a2016-02-11 13:48:49 +00002382 // Whitespace after an operator can be ignored.
2383 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002384 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002385
2386 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002387 }
2388 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002389 if (SpaceEaten)
2390 break;
Preston Gurd05500642012-09-19 20:36:12 +00002391 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002392
Jim Grosbach4b905842013-09-20 23:08:21 +00002393 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002394 // to be able to fill in the remaining default parameter values
2395 if (Lexer.is(AsmToken::EndOfStatement))
2396 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002397
2398 // Adjust the current parentheses level.
2399 if (Lexer.is(AsmToken::LParen))
2400 ++ParenLevel;
2401 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2402 --ParenLevel;
2403
2404 // Append the token to the current argument list.
2405 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002406 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002407 }
Preston Gurd05500642012-09-19 20:36:12 +00002408
Rafael Espindola768b41c2012-06-15 14:02:34 +00002409 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002410 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002411 return false;
2412}
2413
2414// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002415bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002416 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002417 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002418 bool NamedParametersFound = false;
2419 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002420
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002421 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002422 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002423
Rafael Espindola768b41c2012-06-15 14:02:34 +00002424 // Parse two kinds of macro invocations:
2425 // - macros defined without any parameters accept an arbitrary number of them
2426 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002427 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002428 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2429 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002430 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002431 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002432
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002433 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002434 if (parseIdentifier(FA.Name))
2435 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002436
Nirav Dave2364748a2016-09-16 18:30:20 +00002437 if (Lexer.isNot(AsmToken::Equal))
2438 return TokError("expected '=' after formal parameter identifier");
2439
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002440 Lex();
2441
2442 NamedParametersFound = true;
2443 }
2444
Nirav Dave2364748a2016-09-16 18:30:20 +00002445 if (NamedParametersFound && FA.Name.empty())
2446 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002447
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002448 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2449 if (parseMacroArgument(FA.Value, Vararg))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002450 return true;
2451
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002452 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002453 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002454 unsigned FAI = 0;
2455 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002456 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002457 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002458
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002459 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002460 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002461 return Error(IDLoc, "parameter named '" + FA.Name +
2462 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002463 }
2464 PI = FAI;
2465 }
2466
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002467 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002468 if (A.size() <= PI)
2469 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002470 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002471
2472 if (FALocs.size() <= PI)
2473 FALocs.resize(PI + 1);
2474
2475 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002476 }
Jim Grosbach206661622012-07-30 22:44:17 +00002477
Preston Gurd242ed3152012-09-19 20:29:04 +00002478 // At the end of the statement, fill in remaining arguments that have
2479 // default values. If there aren't any, then the next argument is
2480 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002481 if (Lexer.is(AsmToken::EndOfStatement)) {
2482 bool Failure = false;
2483 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2484 if (A[FAI].empty()) {
2485 if (M->Parameters[FAI].Required) {
2486 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2487 "missing value for required parameter "
2488 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2489 Failure = true;
2490 }
2491
2492 if (!M->Parameters[FAI].Value.empty())
2493 A[FAI] = M->Parameters[FAI].Value;
2494 }
2495 }
2496 return Failure;
2497 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002498
2499 if (Lexer.is(AsmToken::Comma))
2500 Lex();
2501 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002502
2503 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002504}
2505
Jim Grosbach4b905842013-09-20 23:08:21 +00002506const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002507 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2508 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002509}
2510
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002511void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2512 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002513}
2514
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002515void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002516
Jim Grosbach4b905842013-09-20 23:08:21 +00002517bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002518 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2519 // eliminate this, although we should protect against infinite loops.
2520 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2521 if (ActiveMacros.size() == MaxNestingDepth) {
2522 std::ostringstream MaxNestingDepthError;
2523 MaxNestingDepthError << "macros cannot be nested more than "
2524 << MaxNestingDepth << " levels deep."
2525 << " Use -asm-macro-max-nesting-depth to increase "
2526 "this limit.";
2527 return TokError(MaxNestingDepthError.str());
2528 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002529
Eli Bendersky38274122013-01-14 23:22:36 +00002530 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002531 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002532 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002533
Rafael Espindola1134ab232011-06-05 02:43:45 +00002534 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2535 // to hold the macro body with substitutions.
2536 SmallString<256> Buf;
2537 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002538 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002539
Toma Tabacu217116e2015-04-27 10:50:29 +00002540 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002541 return true;
2542
Eli Bendersky38274122013-01-14 23:22:36 +00002543 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002544 // instantiation.
2545 OS << ".endmacro\n";
2546
Rafael Espindola3560ff22014-08-27 20:03:13 +00002547 std::unique_ptr<MemoryBuffer> Instantiation =
2548 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002549
Daniel Dunbar43235712010-07-18 18:54:11 +00002550 // Create the macro instantiation object and add to the current macro
2551 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002552 MacroInstantiation *MI = new MacroInstantiation(
2553 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002554 ActiveMacros.push_back(MI);
2555
Toma Tabacu217116e2015-04-27 10:50:29 +00002556 ++NumOfMacroInstantiations;
2557
Daniel Dunbar43235712010-07-18 18:54:11 +00002558 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002559 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002560 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002561 Lex();
2562
2563 return false;
2564}
2565
Jim Grosbach4b905842013-09-20 23:08:21 +00002566void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002567 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002568 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002569 Lex();
2570
2571 // Pop the instantiation entry.
2572 delete ActiveMacros.back();
2573 ActiveMacros.pop_back();
2574}
2575
Jim Grosbach4b905842013-09-20 23:08:21 +00002576bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002577 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002578 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002579 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002580 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2581 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002582 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002583
Pete Cooper80d21cb2015-06-22 19:35:57 +00002584 if (!Sym) {
2585 // In the case where we parse an expression starting with a '.', we will
2586 // not generate an error, nor will we create a symbol. In this case we
2587 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002588 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002589 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002590
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002591 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002592 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002593 if (NoDeadStrip)
2594 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2595
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002596 return false;
2597}
2598
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002599/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002600/// ::= identifier
2601/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002602bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002603 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002604 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2605 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002606 // handle this as a context dependent token, instead we detect adjacent tokens
2607 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002608 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2609 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002610
Hans Wennborgce69d772013-10-18 20:46:28 +00002611 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002612
2613 AsmToken Buf[1];
2614 Lexer.peekTokens(Buf, false);
2615
2616 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002617 return true;
2618
Hans Wennborgce69d772013-10-18 20:46:28 +00002619 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002620 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002621 return true;
2622
Nirav Daved0463322016-10-12 13:58:07 +00002623 // eat $ or @
2624 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002625 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002626 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002627 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002628 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002629 return false;
2630 }
2631
Jim Grosbach4b905842013-09-20 23:08:21 +00002632 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002633 return true;
2634
Sean Callanan936b0d32010-01-19 21:44:56 +00002635 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002636
Sean Callanan686ed8d2010-01-19 20:22:31 +00002637 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002638
2639 return false;
2640}
2641
Jim Grosbach4b905842013-09-20 23:08:21 +00002642/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002643/// ::= .equ identifier ',' expression
2644/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002645/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002646bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002647 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002648 if (check(parseIdentifier(Name), "expected identifier") ||
2649 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2650 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2651 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002652}
2653
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002654bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002655 if (check(getTok().isNot(AsmToken::String), "expected string"))
2656 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002657
2658 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002659 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002660 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2661 if (Str[i] != '\\') {
2662 Data += Str[i];
2663 continue;
2664 }
2665
2666 // Recognize escaped characters. Note that this escape semantics currently
2667 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2668 ++i;
2669 if (i == e)
2670 return TokError("unexpected backslash at end of string");
2671
2672 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002673 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002674 // Consume up to three octal characters.
2675 unsigned Value = Str[i] - '0';
2676
Jim Grosbach4b905842013-09-20 23:08:21 +00002677 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002678 ++i;
2679 Value = Value * 8 + (Str[i] - '0');
2680
Jim Grosbach4b905842013-09-20 23:08:21 +00002681 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002682 ++i;
2683 Value = Value * 8 + (Str[i] - '0');
2684 }
2685 }
2686
2687 if (Value > 255)
2688 return TokError("invalid octal escape sequence (out of range)");
2689
Jim Grosbach4b905842013-09-20 23:08:21 +00002690 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002691 continue;
2692 }
2693
2694 // Otherwise recognize individual escapes.
2695 switch (Str[i]) {
2696 default:
2697 // Just reject invalid escape sequences for now.
2698 return TokError("invalid escape sequence (unrecognized character)");
2699
2700 case 'b': Data += '\b'; break;
2701 case 'f': Data += '\f'; break;
2702 case 'n': Data += '\n'; break;
2703 case 'r': Data += '\r'; break;
2704 case 't': Data += '\t'; break;
2705 case '"': Data += '"'; break;
2706 case '\\': Data += '\\'; break;
2707 }
2708 }
2709
Nirav Davea645433c2016-07-18 15:24:03 +00002710 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002711 return false;
2712}
2713
Jim Grosbach4b905842013-09-20 23:08:21 +00002714/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002715/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002716bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002717 auto parseOp = [&]() -> bool {
2718 std::string Data;
2719 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002720 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002721 getStreamer().EmitBytes(Data);
2722 if (ZeroTerminated)
2723 getStreamer().EmitBytes(StringRef("\0", 1));
2724 return false;
2725 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002726
Nirav Dave1a9044b2016-10-24 14:35:29 +00002727 if (parseMany(parseOp))
2728 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002729 return false;
2730}
2731
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002732/// parseDirectiveReloc
2733/// ::= .reloc expression , identifier [ , expression ]
2734bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2735 const MCExpr *Offset;
2736 const MCExpr *Expr = nullptr;
2737
2738 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00002739 int64_t OffsetValue;
2740 // We can only deal with constant expressions at the moment.
2741
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002742 if (parseExpression(Offset))
2743 return true;
2744
Nirav Davea645433c2016-07-18 15:24:03 +00002745 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2746 "expression is not a constant value") ||
2747 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2748 parseToken(AsmToken::Comma, "expected comma") ||
2749 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2750 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002751
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002752 SMLoc NameLoc = Lexer.getTok().getLoc();
2753 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002754 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002755
2756 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002757 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002758 SMLoc ExprLoc = Lexer.getLoc();
2759 if (parseExpression(Expr))
2760 return true;
2761
2762 MCValue Value;
2763 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2764 return Error(ExprLoc, "expression must be relocatable");
2765 }
2766
Nirav Davea645433c2016-07-18 15:24:03 +00002767 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002768 "unexpected token in .reloc directive"))
2769 return true;
2770
2771 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2772 return Error(NameLoc, "unknown relocation name");
2773
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002774 return false;
2775}
2776
Jim Grosbach4b905842013-09-20 23:08:21 +00002777/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002778/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002779bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2780 auto parseOp = [&]() -> bool {
2781 const MCExpr *Value;
2782 SMLoc ExprLoc = getLexer().getLoc();
2783 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002784 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002785 // Special case constant expressions to match code generator.
2786 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2787 assert(Size <= 8 && "Invalid size");
2788 uint64_t IntValue = MCE->getValue();
2789 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2790 return Error(ExprLoc, "out of range literal value");
2791 getStreamer().EmitIntValue(IntValue, Size);
2792 } else
2793 getStreamer().EmitValue(Value, Size, ExprLoc);
2794 return false;
2795 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002796
Nirav Dave1a9044b2016-10-24 14:35:29 +00002797 if (parseMany(parseOp))
2798 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002799 return false;
2800}
2801
David Woodhoused6de0d92014-02-01 16:20:59 +00002802/// ParseDirectiveOctaValue
2803/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002804
2805bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
2806 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00002807 if (checkForValidSection())
2808 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002809 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
2810 return TokError("unknown token in expression");
2811 SMLoc ExprLoc = getTok().getLoc();
2812 APInt IntValue = getTok().getAPIntVal();
2813 uint64_t hi, lo;
2814 Lex();
2815 if (!IntValue.isIntN(128))
2816 return Error(ExprLoc, "out of range literal value");
2817 if (!IntValue.isIntN(64)) {
2818 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2819 lo = IntValue.getLoBits(64).getZExtValue();
2820 } else {
2821 hi = 0;
2822 lo = IntValue.getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002823 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00002824 if (MAI.isLittleEndian()) {
2825 getStreamer().EmitIntValue(lo, 8);
2826 getStreamer().EmitIntValue(hi, 8);
2827 } else {
2828 getStreamer().EmitIntValue(hi, 8);
2829 getStreamer().EmitIntValue(lo, 8);
2830 }
2831 return false;
2832 };
David Woodhoused6de0d92014-02-01 16:20:59 +00002833
Nirav Dave1a9044b2016-10-24 14:35:29 +00002834 if (parseMany(parseOp))
2835 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00002836 return false;
2837}
2838
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002839bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
2840 // We don't truly support arithmetic on floating point expressions, so we
2841 // have to manually parse unary prefixes.
2842 bool IsNeg = false;
2843 if (getLexer().is(AsmToken::Minus)) {
2844 Lexer.Lex();
2845 IsNeg = true;
2846 } else if (getLexer().is(AsmToken::Plus))
2847 Lexer.Lex();
2848
2849 if (Lexer.is(AsmToken::Error))
2850 return TokError(Lexer.getErr());
2851 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
2852 Lexer.isNot(AsmToken::Identifier))
2853 return TokError("unexpected token in directive");
2854
2855 // Convert to an APFloat.
2856 APFloat Value(Semantics);
2857 StringRef IDVal = getTok().getString();
2858 if (getLexer().is(AsmToken::Identifier)) {
2859 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2860 Value = APFloat::getInf(Semantics);
2861 else if (!IDVal.compare_lower("nan"))
2862 Value = APFloat::getNaN(Semantics, false, ~0);
2863 else
2864 return TokError("invalid floating point literal");
2865 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2866 APFloat::opInvalidOp)
2867 return TokError("invalid floating point literal");
2868 if (IsNeg)
2869 Value.changeSign();
2870
2871 // Consume the numeric token.
2872 Lex();
2873
2874 Res = Value.bitcastToAPInt();
2875
2876 return false;
2877}
2878
Jim Grosbach4b905842013-09-20 23:08:21 +00002879/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00002880/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002881bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
2882 const fltSemantics &Semantics) {
2883 auto parseOp = [&]() -> bool {
2884 APInt AsInt;
2885 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002886 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002887 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2888 AsInt.getBitWidth() / 8);
2889 return false;
2890 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00002891
Nirav Dave1a9044b2016-10-24 14:35:29 +00002892 if (parseMany(parseOp))
2893 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00002894 return false;
2895}
2896
Jim Grosbach4b905842013-09-20 23:08:21 +00002897/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00002898/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002899bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00002900 SMLoc NumBytesLoc = Lexer.getLoc();
2901 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00002902 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00002903 return true;
2904
Rafael Espindolab91bac62010-10-05 19:42:57 +00002905 int64_t Val = 0;
2906 if (getLexer().is(AsmToken::Comma)) {
2907 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002908 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00002909 return true;
2910 }
2911
Nirav Davea645433c2016-07-18 15:24:03 +00002912 if (parseToken(AsmToken::EndOfStatement,
2913 "unexpected token in '.zero' directive"))
2914 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00002915 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00002916
2917 return false;
2918}
2919
Jim Grosbach4b905842013-09-20 23:08:21 +00002920/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00002921/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002922bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00002923 SMLoc NumValuesLoc = Lexer.getLoc();
2924 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00002925 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002926 return true;
2927
Roman Divackye33098f2013-09-24 17:44:41 +00002928 int64_t FillSize = 1;
2929 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002930
David Majnemer522d3db2014-02-01 07:19:38 +00002931 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002932
Nirav Dave1a9044b2016-10-24 14:35:29 +00002933 if (parseOptionalToken(AsmToken::Comma)) {
2934 SizeLoc = getTok().getLoc();
2935 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00002936 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002937 if (parseOptionalToken(AsmToken::Comma)) {
2938 ExprLoc = getTok().getLoc();
2939 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00002940 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00002941 }
2942 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00002943 if (parseToken(AsmToken::EndOfStatement,
2944 "unexpected token in '.fill' directive"))
2945 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002946
David Majnemer522d3db2014-02-01 07:19:38 +00002947 if (FillSize < 0) {
2948 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00002949 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00002950 }
2951 if (FillSize > 8) {
2952 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2953 FillSize = 8;
2954 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002955
David Majnemer522d3db2014-02-01 07:19:38 +00002956 if (!isUInt<32>(FillExpr) && FillSize > 4)
2957 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2958
Petr Hosek67a94a72016-05-28 05:57:48 +00002959 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002960
2961 return false;
2962}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002963
Jim Grosbach4b905842013-09-20 23:08:21 +00002964/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002965/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002966bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002967 const MCExpr *Offset;
Oliver Stannard268f42f2016-12-14 10:43:58 +00002968 SMLoc OffsetLoc = Lexer.getLoc();
Nirav Davef43cc9f2016-10-10 15:24:54 +00002969 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002970 return true;
2971
2972 // Parse optional fill expression.
2973 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002974 if (parseOptionalToken(AsmToken::Comma))
2975 if (parseAbsoluteExpression(FillExpr))
2976 return addErrorSuffix(" in '.org' directive");
2977 if (parseToken(AsmToken::EndOfStatement))
2978 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00002979
Oliver Stannard268f42f2016-12-14 10:43:58 +00002980 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002981 return false;
2982}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002983
Jim Grosbach4b905842013-09-20 23:08:21 +00002984/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002985/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00002986bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002987 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002988 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002989 SMLoc MaxBytesLoc;
2990 bool HasFillExpr = false;
2991 int64_t FillExpr = 0;
2992 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002993
2994 auto parseAlign = [&]() -> bool {
2995 if (checkForValidSection() || parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00002996 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002997 if (parseOptionalToken(AsmToken::Comma)) {
2998 // The fill expression can be omitted while specifying a maximum number of
2999 // alignment bytes, e.g:
3000 // .align 3,,4
3001 if (getTok().isNot(AsmToken::Comma)) {
3002 HasFillExpr = true;
3003 if (parseAbsoluteExpression(FillExpr))
3004 return true;
3005 }
3006 if (parseOptionalToken(AsmToken::Comma))
3007 if (parseTokenLoc(MaxBytesLoc) ||
3008 parseAbsoluteExpression(MaxBytesToFill))
3009 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003010 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003011 return parseToken(AsmToken::EndOfStatement);
3012 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003013
Nirav Dave1a9044b2016-10-24 14:35:29 +00003014 if (parseAlign())
3015 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003016
Nirav Dave2364748a2016-09-16 18:30:20 +00003017 // Always emit an alignment here even if we thrown an error.
3018 bool ReturnVal = false;
3019
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003020 // Compute alignment in bytes.
3021 if (IsPow2) {
3022 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003023 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003024 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003025 Alignment = 31;
3026 }
3027
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003028 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003029 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003030 // Reject alignments that aren't either a power of two or zero,
3031 // for gas compatibility. Alignment of zero is silently rounded
3032 // up to one.
3033 if (Alignment == 0)
3034 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003035 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003036 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003037 }
3038
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003039 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003040 if (MaxBytesLoc.isValid()) {
3041 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003042 ReturnVal |= Error(MaxBytesLoc,
3043 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003044 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003045 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003046 }
3047
3048 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003049 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003050 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003051 MaxBytesToFill = 0;
3052 }
3053 }
3054
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003055 // Check whether we should use optimal code alignment for this .align
3056 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003057 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003058 assert(Section && "must have section to emit alignment");
3059 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003060 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3061 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003062 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003063 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003064 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003065 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3066 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003067 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003068
Nirav Dave2364748a2016-09-16 18:30:20 +00003069 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003070}
3071
Jim Grosbach4b905842013-09-20 23:08:21 +00003072/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00003073/// ::= .file [number] filename
3074/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00003075bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003076 // FIXME: I'm not sure what this is.
3077 int64_t FileNumber = -1;
3078 SMLoc FileNumberLoc = getLexer().getLoc();
3079 if (getLexer().is(AsmToken::Integer)) {
3080 FileNumber = getTok().getIntVal();
3081 Lex();
3082
3083 if (FileNumber < 1)
3084 return TokError("file number less than one");
3085 }
3086
Nirav Davea645433c2016-07-18 15:24:03 +00003087 std::string Path = getTok().getString();
Eli Bendersky17233942013-01-15 22:59:42 +00003088
3089 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003090 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003091 if (check(getTok().isNot(AsmToken::String),
3092 "unexpected token in '.file' directive") ||
3093 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003094 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003095
3096 StringRef Directory;
3097 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003098 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003099 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003100 if (check(FileNumber == -1,
3101 "explicit path specified, but no file number") ||
3102 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003103 return true;
3104 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003105 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003106 } else {
3107 Filename = Path;
3108 }
3109
Nirav Davea645433c2016-07-18 15:24:03 +00003110 if (parseToken(AsmToken::EndOfStatement,
3111 "unexpected token in '.file' directive"))
3112 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003113
3114 if (FileNumber == -1)
3115 getStreamer().EmitFileDirective(Filename);
3116 else {
David Blaikie22748082016-05-26 00:22:26 +00003117 // If there is -g option as well as debug info from directive file,
3118 // we turn off -g option, directly use the existing debug info instead.
David Blaikiedc3f01e2015-03-09 01:57:13 +00003119 if (getContext().getGenDwarfForAssembly())
David Blaikie22748082016-05-26 00:22:26 +00003120 getContext().setGenDwarfForAssembly(false);
3121 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
David Blaikiec714ef42014-03-17 01:52:11 +00003122 0)
Nirav Dave2364748a2016-09-16 18:30:20 +00003123 return Error(FileNumberLoc, "file number already allocated");
Eli Bendersky17233942013-01-15 22:59:42 +00003124 }
3125
3126 return false;
3127}
3128
Jim Grosbach4b905842013-09-20 23:08:21 +00003129/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003130/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003131bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003132 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003133 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003134 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3135 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003136 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003137 // FIXME: Do something with the .line.
3138 }
Nirav Davea645433c2016-07-18 15:24:03 +00003139 if (parseToken(AsmToken::EndOfStatement,
3140 "unexpected token in '.line' directive"))
3141 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003142
3143 return false;
3144}
3145
Jim Grosbach4b905842013-09-20 23:08:21 +00003146/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003147/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3148/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3149/// The first number is a file number, must have been previously assigned with
3150/// a .file directive, the second number is the line number and optionally the
3151/// third number is a column position (zero if not specified). The remaining
3152/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003153bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003154 int64_t FileNumber = 0, LineNumber = 0;
3155 SMLoc Loc = getTok().getLoc();
3156 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3157 check(FileNumber < 1, Loc,
3158 "file number less than one in '.loc' directive") ||
3159 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3160 "unassigned file number in '.loc' directive"))
3161 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003162
Nirav Davea645433c2016-07-18 15:24:03 +00003163 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003164 if (getLexer().is(AsmToken::Integer)) {
3165 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003166 if (LineNumber < 0)
3167 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003168 Lex();
3169 }
3170
3171 int64_t ColumnPos = 0;
3172 if (getLexer().is(AsmToken::Integer)) {
3173 ColumnPos = getTok().getIntVal();
3174 if (ColumnPos < 0)
3175 return TokError("column position less than zero in '.loc' directive");
3176 Lex();
3177 }
3178
3179 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3180 unsigned Isa = 0;
3181 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003182
Nirav Dave1a9044b2016-10-24 14:35:29 +00003183 auto parseLocOp = [&]() -> bool {
3184 StringRef Name;
3185 SMLoc Loc = getTok().getLoc();
3186 if (parseIdentifier(Name))
3187 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003188
Nirav Dave1a9044b2016-10-24 14:35:29 +00003189 if (Name == "basic_block")
3190 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3191 else if (Name == "prologue_end")
3192 Flags |= DWARF2_FLAG_PROLOGUE_END;
3193 else if (Name == "epilogue_begin")
3194 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3195 else if (Name == "is_stmt") {
3196 Loc = getTok().getLoc();
3197 const MCExpr *Value;
3198 if (parseExpression(Value))
3199 return true;
3200 // The expression must be the constant 0 or 1.
3201 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3202 int Value = MCE->getValue();
3203 if (Value == 0)
3204 Flags &= ~DWARF2_FLAG_IS_STMT;
3205 else if (Value == 1)
3206 Flags |= DWARF2_FLAG_IS_STMT;
3207 else
3208 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003209 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003210 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003211 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003212 } else if (Name == "isa") {
3213 Loc = getTok().getLoc();
3214 const MCExpr *Value;
3215 if (parseExpression(Value))
3216 return true;
3217 // The expression must be a constant greater or equal to 0.
3218 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3219 int Value = MCE->getValue();
3220 if (Value < 0)
3221 return Error(Loc, "isa number less than zero");
3222 Isa = Value;
3223 } else {
3224 return Error(Loc, "isa number not a constant value");
3225 }
3226 } else if (Name == "discriminator") {
3227 if (parseAbsoluteExpression(Discriminator))
3228 return true;
3229 } else {
3230 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003231 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003232 return false;
3233 };
3234
Nirav Davee2369aa2016-10-26 17:28:58 +00003235 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003236 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003237
3238 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3239 Isa, Discriminator, StringRef());
3240
3241 return false;
3242}
3243
Jim Grosbach4b905842013-09-20 23:08:21 +00003244/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003245/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003246bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003247 return TokError("unsupported directive '.stabs'");
3248}
3249
Reid Kleckner2214ed82016-01-29 00:49:42 +00003250/// parseDirectiveCVFile
3251/// ::= .cv_file number filename
3252bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003253 SMLoc FileNumberLoc = getTok().getLoc();
3254 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003255 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00003256
3257 if (parseIntToken(FileNumber,
3258 "expected file number in '.cv_file' directive") ||
3259 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3260 check(getTok().isNot(AsmToken::String),
3261 "unexpected token in '.cv_file' directive") ||
3262 // Usually directory and filename are together, otherwise just
3263 // directory. Allow the strings to have escaped octal character sequence.
3264 parseEscapedString(Filename) ||
3265 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00003266 "unexpected token in '.cv_file' directive"))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003267 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00003268
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003269 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003270 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003271
3272 return false;
3273}
3274
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003275bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3276 StringRef DirectiveName) {
3277 SMLoc Loc;
3278 return parseTokenLoc(Loc) ||
3279 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3280 "' directive") ||
3281 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3282 "expected function id within range [0, UINT_MAX)");
3283}
3284
3285bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3286 SMLoc Loc;
3287 return parseTokenLoc(Loc) ||
3288 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3289 "' directive") ||
3290 check(FileNumber < 1, Loc, "file number less than one in '" +
3291 DirectiveName + "' directive") ||
3292 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3293 "unassigned file number in '" + DirectiveName + "' directive");
3294}
3295
3296/// parseDirectiveCVFuncId
3297/// ::= .cv_func_id FunctionId
3298///
3299/// Introduces a function ID that can be used with .cv_loc.
3300bool AsmParser::parseDirectiveCVFuncId() {
3301 SMLoc FunctionIdLoc = getTok().getLoc();
3302 int64_t FunctionId;
3303
3304 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3305 parseToken(AsmToken::EndOfStatement,
3306 "unexpected token in '.cv_func_id' directive"))
3307 return true;
3308
3309 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003310 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003311
3312 return false;
3313}
3314
3315/// parseDirectiveCVInlineSiteId
3316/// ::= .cv_inline_site_id FunctionId
3317/// "within" IAFunc
3318/// "inlined_at" IAFile IALine [IACol]
3319///
3320/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3321/// at" source location information for use in the line table of the caller,
3322/// whether the caller is a real function or another inlined call site.
3323bool AsmParser::parseDirectiveCVInlineSiteId() {
3324 SMLoc FunctionIdLoc = getTok().getLoc();
3325 int64_t FunctionId;
3326 int64_t IAFunc;
3327 int64_t IAFile;
3328 int64_t IALine;
3329 int64_t IACol = 0;
3330
3331 // FunctionId
3332 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3333 return true;
3334
3335 // "within"
3336 if (check((getLexer().isNot(AsmToken::Identifier) ||
3337 getTok().getIdentifier() != "within"),
3338 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3339 return true;
3340 Lex();
3341
3342 // IAFunc
3343 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3344 return true;
3345
3346 // "inlined_at"
3347 if (check((getLexer().isNot(AsmToken::Identifier) ||
3348 getTok().getIdentifier() != "inlined_at"),
3349 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3350 "directive") )
3351 return true;
3352 Lex();
3353
3354 // IAFile IALine
3355 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3356 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3357 return true;
3358
3359 // [IACol]
3360 if (getLexer().is(AsmToken::Integer)) {
3361 IACol = getTok().getIntVal();
3362 Lex();
3363 }
3364
3365 if (parseToken(AsmToken::EndOfStatement,
3366 "unexpected token in '.cv_inline_site_id' directive"))
3367 return true;
3368
3369 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3370 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003371 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003372
3373 return false;
3374}
3375
Reid Kleckner2214ed82016-01-29 00:49:42 +00003376/// parseDirectiveCVLoc
3377/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3378/// [is_stmt VALUE]
3379/// The first number is a file number, must have been previously assigned with
3380/// a .file directive, the second number is the line number and optionally the
3381/// third number is a column position (zero if not specified). The remaining
3382/// optional items are .loc sub-directives.
3383bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003384 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003385 SMLoc Loc;
3386 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003387 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3388 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003389 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003390
3391 int64_t LineNumber = 0;
3392 if (getLexer().is(AsmToken::Integer)) {
3393 LineNumber = getTok().getIntVal();
3394 if (LineNumber < 0)
3395 return TokError("line number less than zero in '.cv_loc' directive");
3396 Lex();
3397 }
3398
3399 int64_t ColumnPos = 0;
3400 if (getLexer().is(AsmToken::Integer)) {
3401 ColumnPos = getTok().getIntVal();
3402 if (ColumnPos < 0)
3403 return TokError("column position less than zero in '.cv_loc' directive");
3404 Lex();
3405 }
3406
3407 bool PrologueEnd = false;
3408 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003409
3410 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003411 StringRef Name;
3412 SMLoc Loc = getTok().getLoc();
3413 if (parseIdentifier(Name))
3414 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003415 if (Name == "prologue_end")
3416 PrologueEnd = true;
3417 else if (Name == "is_stmt") {
3418 Loc = getTok().getLoc();
3419 const MCExpr *Value;
3420 if (parseExpression(Value))
3421 return true;
3422 // The expression must be the constant 0 or 1.
3423 IsStmt = ~0ULL;
3424 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3425 IsStmt = MCE->getValue();
3426
3427 if (IsStmt > 1)
3428 return Error(Loc, "is_stmt value not 0 or 1");
3429 } else {
3430 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3431 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003432 return false;
3433 };
3434
3435 if (parseMany(parseOp, false /*hasComma*/))
3436 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003437
3438 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003439 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3440 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003441 return false;
3442}
3443
3444/// parseDirectiveCVLinetable
3445/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3446bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003447 int64_t FunctionId;
3448 StringRef FnStartName, FnEndName;
3449 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003450 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
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(FnStartName), Loc,
3454 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003455 parseToken(AsmToken::Comma,
3456 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003457 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3458 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003459 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003460
3461 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3462 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3463
3464 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3465 return false;
3466}
3467
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003468/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003469/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003470bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003471 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3472 StringRef FnStartName, FnEndName;
3473 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003474 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003475 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003476 parseIntToken(
3477 SourceFileId,
3478 "expected SourceField in '.cv_inline_linetable' directive") ||
3479 check(SourceFileId <= 0, Loc,
3480 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003481 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003482 parseIntToken(
3483 SourceLineNum,
3484 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3485 check(SourceLineNum < 0, Loc,
3486 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003487 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3488 "expected identifier in directive") ||
3489 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3490 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003491 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003492
Nirav Davea645433c2016-07-18 15:24:03 +00003493 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3494 return true;
3495
3496 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3497 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003498 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3499 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003500 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003501 return false;
3502}
3503
David Majnemer408b5e62016-02-05 01:55:49 +00003504/// parseDirectiveCVDefRange
3505/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3506bool AsmParser::parseDirectiveCVDefRange() {
3507 SMLoc Loc;
3508 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3509 while (getLexer().is(AsmToken::Identifier)) {
3510 Loc = getLexer().getLoc();
3511 StringRef GapStartName;
3512 if (parseIdentifier(GapStartName))
3513 return Error(Loc, "expected identifier in directive");
3514 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3515
3516 Loc = getLexer().getLoc();
3517 StringRef GapEndName;
3518 if (parseIdentifier(GapEndName))
3519 return Error(Loc, "expected identifier in directive");
3520 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3521
3522 Ranges.push_back({GapStartSym, GapEndSym});
3523 }
3524
David Majnemer408b5e62016-02-05 01:55:49 +00003525 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003526 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3527 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003528 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003529
3530 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3531 return false;
3532}
3533
Reid Kleckner2214ed82016-01-29 00:49:42 +00003534/// parseDirectiveCVStringTable
3535/// ::= .cv_stringtable
3536bool AsmParser::parseDirectiveCVStringTable() {
3537 getStreamer().EmitCVStringTableDirective();
3538 return false;
3539}
3540
3541/// parseDirectiveCVFileChecksums
3542/// ::= .cv_filechecksums
3543bool AsmParser::parseDirectiveCVFileChecksums() {
3544 getStreamer().EmitCVFileChecksumsDirective();
3545 return false;
3546}
3547
Jim Grosbach4b905842013-09-20 23:08:21 +00003548/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003549/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003550bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003551 StringRef Name;
3552 bool EH = false;
3553 bool Debug = false;
3554
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003555 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003556 return TokError("Expected an identifier");
3557
3558 if (Name == ".eh_frame")
3559 EH = true;
3560 else if (Name == ".debug_frame")
3561 Debug = true;
3562
3563 if (getLexer().is(AsmToken::Comma)) {
3564 Lex();
3565
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003566 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003567 return TokError("Expected an identifier");
3568
3569 if (Name == ".eh_frame")
3570 EH = true;
3571 else if (Name == ".debug_frame")
3572 Debug = true;
3573 }
3574
3575 getStreamer().EmitCFISections(EH, Debug);
3576 return false;
3577}
3578
Jim Grosbach4b905842013-09-20 23:08:21 +00003579/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003580/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003581bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003582 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003583 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3584 if (check(parseIdentifier(Simple) || Simple != "simple",
3585 "unexpected token") ||
3586 parseToken(AsmToken::EndOfStatement))
3587 return addErrorSuffix(" in '.cfi_startproc' directive");
3588 }
Nirav Davea645433c2016-07-18 15:24:03 +00003589
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003590 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003591 return false;
3592}
3593
Jim Grosbach4b905842013-09-20 23:08:21 +00003594/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003595/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003596bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003597 getStreamer().EmitCFIEndProc();
3598 return false;
3599}
3600
Jim Grosbach4b905842013-09-20 23:08:21 +00003601/// \brief parse register name or number.
3602bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003603 SMLoc DirectiveLoc) {
3604 unsigned RegNo;
3605
3606 if (getLexer().isNot(AsmToken::Integer)) {
3607 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3608 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003609 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003610 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003611 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003612
3613 return false;
3614}
3615
Jim Grosbach4b905842013-09-20 23:08:21 +00003616/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003617/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003618bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003619 int64_t Register = 0, Offset = 0;
3620 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3621 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3622 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003623 return true;
3624
3625 getStreamer().EmitCFIDefCfa(Register, Offset);
3626 return false;
3627}
3628
Jim Grosbach4b905842013-09-20 23:08:21 +00003629/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003630/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003631bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003632 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003633 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003634 return true;
3635
3636 getStreamer().EmitCFIDefCfaOffset(Offset);
3637 return false;
3638}
3639
Jim Grosbach4b905842013-09-20 23:08:21 +00003640/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003641/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003642bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003643 int64_t Register1 = 0, Register2 = 0;
3644 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3645 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3646 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003647 return true;
3648
3649 getStreamer().EmitCFIRegister(Register1, Register2);
3650 return false;
3651}
3652
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003653/// parseDirectiveCFIWindowSave
3654/// ::= .cfi_window_save
3655bool AsmParser::parseDirectiveCFIWindowSave() {
3656 getStreamer().EmitCFIWindowSave();
3657 return false;
3658}
3659
Jim Grosbach4b905842013-09-20 23:08:21 +00003660/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003661/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003662bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003663 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003664 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003665 return true;
3666
3667 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3668 return false;
3669}
3670
Jim Grosbach4b905842013-09-20 23:08:21 +00003671/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003672/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003673bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003674 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003675 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003676 return true;
3677
3678 getStreamer().EmitCFIDefCfaRegister(Register);
3679 return false;
3680}
3681
Jim Grosbach4b905842013-09-20 23:08:21 +00003682/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003683/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003684bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003685 int64_t Register = 0;
3686 int64_t Offset = 0;
3687
Nirav Davea645433c2016-07-18 15:24:03 +00003688 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3689 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3690 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003691 return true;
3692
3693 getStreamer().EmitCFIOffset(Register, Offset);
3694 return false;
3695}
3696
Jim Grosbach4b905842013-09-20 23:08:21 +00003697/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003698/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003699bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003700 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003701
Nirav Davea645433c2016-07-18 15:24:03 +00003702 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3703 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3704 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003705 return true;
3706
3707 getStreamer().EmitCFIRelOffset(Register, Offset);
3708 return false;
3709}
3710
3711static bool isValidEncoding(int64_t Encoding) {
3712 if (Encoding & ~0xff)
3713 return false;
3714
3715 if (Encoding == dwarf::DW_EH_PE_omit)
3716 return true;
3717
3718 const unsigned Format = Encoding & 0xf;
3719 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3720 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3721 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3722 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3723 return false;
3724
3725 const unsigned Application = Encoding & 0x70;
3726 if (Application != dwarf::DW_EH_PE_absptr &&
3727 Application != dwarf::DW_EH_PE_pcrel)
3728 return false;
3729
3730 return true;
3731}
3732
Jim Grosbach4b905842013-09-20 23:08:21 +00003733/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003734/// IsPersonality true for cfi_personality, false for cfi_lsda
3735/// ::= .cfi_personality encoding, [symbol_name]
3736/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003737bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003738 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003739 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003740 return true;
3741 if (Encoding == dwarf::DW_EH_PE_omit)
3742 return false;
3743
Eli Bendersky17233942013-01-15 22:59:42 +00003744 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00003745 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
3746 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3747 check(parseIdentifier(Name), "expected identifier in directive"))
3748 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003749
Jim Grosbach6f482002015-05-18 18:43:14 +00003750 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003751
3752 if (IsPersonality)
3753 getStreamer().EmitCFIPersonality(Sym, Encoding);
3754 else
3755 getStreamer().EmitCFILsda(Sym, Encoding);
3756 return false;
3757}
3758
Jim Grosbach4b905842013-09-20 23:08:21 +00003759/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00003760/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003761bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003762 getStreamer().EmitCFIRememberState();
3763 return false;
3764}
3765
Jim Grosbach4b905842013-09-20 23:08:21 +00003766/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00003767/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003768bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003769 getStreamer().EmitCFIRestoreState();
3770 return false;
3771}
3772
Jim Grosbach4b905842013-09-20 23:08:21 +00003773/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00003774/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00003775bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003776 int64_t Register = 0;
3777
Jim Grosbach4b905842013-09-20 23:08:21 +00003778 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003779 return true;
3780
3781 getStreamer().EmitCFISameValue(Register);
3782 return false;
3783}
3784
Jim Grosbach4b905842013-09-20 23:08:21 +00003785/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00003786/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00003787bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003788 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003789 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003790 return true;
3791
3792 getStreamer().EmitCFIRestore(Register);
3793 return false;
3794}
3795
Jim Grosbach4b905842013-09-20 23:08:21 +00003796/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00003797/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003798bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00003799 std::string Values;
3800 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003801 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003802 return true;
3803
3804 Values.push_back((uint8_t)CurrValue);
3805
3806 while (getLexer().is(AsmToken::Comma)) {
3807 Lex();
3808
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003809 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003810 return true;
3811
3812 Values.push_back((uint8_t)CurrValue);
3813 }
3814
3815 getStreamer().EmitCFIEscape(Values);
3816 return false;
3817}
3818
Jim Grosbach4b905842013-09-20 23:08:21 +00003819/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00003820/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00003821bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00003822 if (parseToken(AsmToken::EndOfStatement,
3823 "unexpected token in '.cfi_signal_frame'"))
3824 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003825
3826 getStreamer().EmitCFISignalFrame();
3827 return false;
3828}
3829
Jim Grosbach4b905842013-09-20 23:08:21 +00003830/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00003831/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00003832bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003833 int64_t Register = 0;
3834
Jim Grosbach4b905842013-09-20 23:08:21 +00003835 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003836 return true;
3837
3838 getStreamer().EmitCFIUndefined(Register);
3839 return false;
3840}
3841
Jim Grosbach4b905842013-09-20 23:08:21 +00003842/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00003843/// ::= .macros_on
3844/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00003845bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00003846 if (parseToken(AsmToken::EndOfStatement,
3847 "unexpected token in '" + Directive + "' directive"))
3848 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003849
Jim Grosbach4b905842013-09-20 23:08:21 +00003850 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00003851 return false;
3852}
3853
Jim Grosbach4b905842013-09-20 23:08:21 +00003854/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003855/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00003856bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003857 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003858 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003859 return TokError("expected identifier in '.macro' directive");
3860
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003861 if (getLexer().is(AsmToken::Comma))
3862 Lex();
3863
Eli Bendersky17233942013-01-15 22:59:42 +00003864 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00003865 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003866
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003867 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003868 return Error(Lexer.getLoc(),
3869 "Vararg parameter '" + Parameters.back().Name +
3870 "' should be last one in the list of parameters.");
3871
David Majnemer91fc4c22014-01-29 18:57:46 +00003872 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003873 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00003874 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003875
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003876 if (Lexer.is(AsmToken::Colon)) {
3877 Lex(); // consume ':'
3878
3879 SMLoc QualLoc;
3880 StringRef Qualifier;
3881
3882 QualLoc = Lexer.getLoc();
3883 if (parseIdentifier(Qualifier))
3884 return Error(QualLoc, "missing parameter qualifier for "
3885 "'" + Parameter.Name + "' in macro '" + Name + "'");
3886
3887 if (Qualifier == "req")
3888 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00003889 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003890 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003891 else
3892 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3893 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3894 }
3895
David Majnemer91fc4c22014-01-29 18:57:46 +00003896 if (getLexer().is(AsmToken::Equal)) {
3897 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003898
3899 SMLoc ParamLoc;
3900
3901 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003902 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00003903 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003904
3905 if (Parameter.Required)
3906 Warning(ParamLoc, "pointless default value for required parameter "
3907 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00003908 }
David Majnemer91fc4c22014-01-29 18:57:46 +00003909
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003910 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00003911
3912 if (getLexer().is(AsmToken::Comma))
3913 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003914 }
3915
Nirav Dave1180e6892016-06-02 17:15:05 +00003916 // Eat just the end of statement.
3917 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003918
Nirav Dave1180e6892016-06-02 17:15:05 +00003919 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00003920 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003921 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003922 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00003923 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00003924 // Ignore Lexing errors in macros.
3925 while (Lexer.is(AsmToken::Error)) {
3926 Lexer.Lex();
3927 }
3928
Eli Bendersky17233942013-01-15 22:59:42 +00003929 // Check whether we have reached the end of the file.
3930 if (getLexer().is(AsmToken::Eof))
3931 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3932
3933 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003934 if (getLexer().is(AsmToken::Identifier)) {
3935 if (getTok().getIdentifier() == ".endm" ||
3936 getTok().getIdentifier() == ".endmacro") {
3937 if (MacroDepth == 0) { // Outermost macro.
3938 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00003939 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003940 if (getLexer().isNot(AsmToken::EndOfStatement))
3941 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3942 "' directive");
3943 break;
3944 } else {
3945 // Otherwise we just found the end of an inner macro.
3946 --MacroDepth;
3947 }
3948 } else if (getTok().getIdentifier() == ".macro") {
3949 // We allow nested macros. Those aren't instantiated until the outermost
3950 // macro is expanded so just ignore them for now.
3951 ++MacroDepth;
3952 }
Eli Bendersky17233942013-01-15 22:59:42 +00003953 }
3954
3955 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003956 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00003957 }
3958
Jim Grosbach4b905842013-09-20 23:08:21 +00003959 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00003960 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3961 }
3962
3963 const char *BodyStart = StartToken.getLoc().getPointer();
3964 const char *BodyEnd = EndToken.getLoc().getPointer();
3965 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00003966 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003967 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00003968 return false;
3969}
3970
Jim Grosbach4b905842013-09-20 23:08:21 +00003971/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00003972///
3973/// With the support added for named parameters there may be code out there that
3974/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00003975/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00003976/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00003977/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00003978/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3979/// warning that the positional parameter found in body which have no effect.
3980/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00003981/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00003982/// intended or change the macro to use the named parameters. It is possible
3983/// this warning will trigger when the none of the named parameters are used
3984/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00003985void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00003986 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00003987 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00003988 // If this macro is not defined with named parameters the warning we are
3989 // checking for here doesn't apply.
3990 unsigned NParameters = Parameters.size();
3991 if (NParameters == 0)
3992 return;
3993
3994 bool NamedParametersFound = false;
3995 bool PositionalParametersFound = false;
3996
3997 // Look at the body of the macro for use of both the named parameters and what
3998 // are likely to be positional parameters. This is what expandMacro() is
3999 // doing when it finds the parameters in the body.
4000 while (!Body.empty()) {
4001 // Scan for the next possible parameter.
4002 std::size_t End = Body.size(), Pos = 0;
4003 for (; Pos != End; ++Pos) {
4004 // Check for a substitution or escape.
4005 // This macro is defined with parameters, look for \foo, \bar, etc.
4006 if (Body[Pos] == '\\' && Pos + 1 != End)
4007 break;
4008
4009 // This macro should have parameters, but look for $0, $1, ..., $n too.
4010 if (Body[Pos] != '$' || Pos + 1 == End)
4011 continue;
4012 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004013 if (Next == '$' || Next == 'n' ||
4014 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004015 break;
4016 }
4017
4018 // Check if we reached the end.
4019 if (Pos == End)
4020 break;
4021
4022 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004023 switch (Body[Pos + 1]) {
4024 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004025 case '$':
4026 break;
4027
Jim Grosbach4b905842013-09-20 23:08:21 +00004028 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004029 case 'n':
4030 PositionalParametersFound = true;
4031 break;
4032
Jim Grosbach4b905842013-09-20 23:08:21 +00004033 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004034 default: {
4035 PositionalParametersFound = true;
4036 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004037 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004038 }
4039 Pos += 2;
4040 } else {
4041 unsigned I = Pos + 1;
4042 while (isIdentifierChar(Body[I]) && I + 1 != End)
4043 ++I;
4044
Jim Grosbach4b905842013-09-20 23:08:21 +00004045 const char *Begin = Body.data() + Pos + 1;
4046 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004047 unsigned Index = 0;
4048 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004049 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004050 break;
4051
4052 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004053 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4054 Pos += 3;
4055 else {
4056 Pos = I;
4057 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004058 } else {
4059 NamedParametersFound = true;
4060 Pos += 1 + Argument.size();
4061 }
4062 }
4063 // Update the scan point.
4064 Body = Body.substr(Pos);
4065 }
4066
4067 if (!NamedParametersFound && PositionalParametersFound)
4068 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4069 "used in macro body, possible positional parameter "
4070 "found in body which will have no effect");
4071}
4072
Nico Weber155dccd12014-07-24 17:08:39 +00004073/// parseDirectiveExitMacro
4074/// ::= .exitm
4075bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004076 if (parseToken(AsmToken::EndOfStatement,
4077 "unexpected token in '" + Directive + "' directive"))
4078 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004079
4080 if (!isInsideMacroInstantiation())
4081 return TokError("unexpected '" + Directive + "' in file, "
4082 "no current macro definition");
4083
4084 // Exit all conditionals that are active in the current macro.
4085 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4086 TheCondState = TheCondStack.back();
4087 TheCondStack.pop_back();
4088 }
4089
4090 handleMacroExit();
4091 return false;
4092}
4093
Jim Grosbach4b905842013-09-20 23:08:21 +00004094/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004095/// ::= .endm
4096/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004097bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004098 if (getLexer().isNot(AsmToken::EndOfStatement))
4099 return TokError("unexpected token in '" + Directive + "' directive");
4100
4101 // If we are inside a macro instantiation, terminate the current
4102 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004103 if (isInsideMacroInstantiation()) {
4104 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004105 return false;
4106 }
4107
4108 // Otherwise, this .endmacro is a stray entry in the file; well formed
4109 // .endmacro directives are handled during the macro definition parsing.
4110 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004111 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004112}
4113
Jim Grosbach4b905842013-09-20 23:08:21 +00004114/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004115/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004116bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004117 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004118 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004119 if (parseTokenLoc(Loc) ||
4120 check(parseIdentifier(Name), Loc,
4121 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004122 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004123 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004124 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004125
Nirav Dave1ab71992016-07-18 19:35:21 +00004126 if (!lookupMacro(Name))
4127 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4128
Jim Grosbach4b905842013-09-20 23:08:21 +00004129 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004130 return false;
4131}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004132
Jim Grosbach4b905842013-09-20 23:08:21 +00004133/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004134/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004135bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004136 // Expect a single argument: an expression that evaluates to a constant
4137 // in the inclusive range 0-30.
4138 SMLoc ExprLoc = getLexer().getLoc();
4139 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004140 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004141 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4142 "in '.bundle_align_mode' "
4143 "directive") ||
4144 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4145 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004146 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004147
4148 // Because of AlignSizePow2's verified range we can safely truncate it to
4149 // unsigned.
4150 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4151 return false;
4152}
4153
Jim Grosbach4b905842013-09-20 23:08:21 +00004154/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004155/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004156bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004157 if (checkForValidSection())
4158 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004159 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004160
Nirav Dave1a9044b2016-10-24 14:35:29 +00004161 StringRef Option;
4162 SMLoc Loc = getTok().getLoc();
4163 const char *kInvalidOptionError =
4164 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004165
Nirav Dave1a9044b2016-10-24 14:35:29 +00004166 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004167 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4168 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004169 parseToken(AsmToken::EndOfStatement,
4170 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004171 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004172 AlignToEnd = true;
4173 }
4174
Eli Bendersky802b6282013-01-07 21:51:08 +00004175 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004176 return false;
4177}
4178
Jim Grosbach4b905842013-09-20 23:08:21 +00004179/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004180/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004181bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004182 if (checkForValidSection() ||
4183 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004184 "unexpected token in '.bundle_unlock' directive"))
4185 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004186
4187 getStreamer().EmitBundleUnlock();
4188 return false;
4189}
4190
Jim Grosbach4b905842013-09-20 23:08:21 +00004191/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004192/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004193bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Eli Bendersky17233942013-01-15 22:59:42 +00004194
Petr Hosek67a94a72016-05-28 05:57:48 +00004195 SMLoc NumBytesLoc = Lexer.getLoc();
4196 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004197 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004198 return true;
4199
4200 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004201 if (parseOptionalToken(AsmToken::Comma))
4202 if (parseAbsoluteExpression(FillExpr))
4203 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4204 if (parseToken(AsmToken::EndOfStatement))
4205 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004206
Eli Bendersky17233942013-01-15 22:59:42 +00004207 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004208 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004209
4210 return false;
4211}
4212
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004213/// parseDirectiveDCB
4214/// ::= .dcb.{b, l, w} expression, expression
4215bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004216 SMLoc NumValuesLoc = Lexer.getLoc();
4217 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004218 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004219 return true;
4220
4221 if (NumValues < 0) {
4222 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4223 return false;
4224 }
4225
4226 if (parseToken(AsmToken::Comma,
4227 "unexpected token in '" + Twine(IDVal) + "' directive"))
4228 return true;
4229
4230 const MCExpr *Value;
4231 SMLoc ExprLoc = getLexer().getLoc();
4232 if (parseExpression(Value))
4233 return true;
4234
4235 // Special case constant expressions to match code generator.
4236 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4237 assert(Size <= 8 && "Invalid size");
4238 uint64_t IntValue = MCE->getValue();
4239 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4240 return Error(ExprLoc, "literal value out of range for directive");
4241 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4242 getStreamer().EmitIntValue(IntValue, Size);
4243 } else {
4244 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4245 getStreamer().EmitValue(Value, Size, ExprLoc);
4246 }
4247
4248 if (parseToken(AsmToken::EndOfStatement,
4249 "unexpected token in '" + Twine(IDVal) + "' directive"))
4250 return true;
4251
4252 return false;
4253}
4254
4255/// parseDirectiveRealDCB
4256/// ::= .dcb.{d, s} expression, expression
4257bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004258 SMLoc NumValuesLoc = Lexer.getLoc();
4259 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004260 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004261 return true;
4262
4263 if (NumValues < 0) {
4264 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4265 return false;
4266 }
4267
4268 if (parseToken(AsmToken::Comma,
4269 "unexpected token in '" + Twine(IDVal) + "' directive"))
4270 return true;
4271
4272 APInt AsInt;
4273 if (parseRealValue(Semantics, AsInt))
4274 return true;
4275
4276 if (parseToken(AsmToken::EndOfStatement,
4277 "unexpected token in '" + Twine(IDVal) + "' directive"))
4278 return true;
4279
4280 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4281 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4282 AsInt.getBitWidth() / 8);
4283
4284 return false;
4285}
4286
Petr Hosek85b2f672016-09-23 21:53:36 +00004287/// parseDirectiveDS
4288/// ::= .ds.{b, d, l, p, s, w, x} expression
4289bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004290
4291 SMLoc NumValuesLoc = Lexer.getLoc();
4292 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004293 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004294 return true;
4295
4296 if (NumValues < 0) {
4297 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4298 return false;
4299 }
4300
4301 if (parseToken(AsmToken::EndOfStatement,
4302 "unexpected token in '" + Twine(IDVal) + "' directive"))
4303 return true;
4304
4305 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4306 getStreamer().emitFill(Size, 0);
4307
4308 return false;
4309}
4310
Jim Grosbach4b905842013-09-20 23:08:21 +00004311/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004312/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004313bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004314 if (checkForValidSection())
4315 return true;
4316
Nirav Dave1a9044b2016-10-24 14:35:29 +00004317 auto parseOp = [&]() -> bool {
4318 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004319 if (parseExpression(Value))
4320 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004321 if (Signed)
4322 getStreamer().EmitSLEB128Value(Value);
4323 else
4324 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004325 return false;
4326 };
Eli Bendersky17233942013-01-15 22:59:42 +00004327
Nirav Dave1a9044b2016-10-24 14:35:29 +00004328 if (parseMany(parseOp))
4329 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004330
4331 return false;
4332}
4333
Jim Grosbach4b905842013-09-20 23:08:21 +00004334/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004335/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004336bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004337 auto parseOp = [&]() -> bool {
4338 StringRef Name;
4339 SMLoc Loc = getTok().getLoc();
4340 if (parseIdentifier(Name))
4341 return Error(Loc, "expected identifier");
4342 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004343
Nirav Dave1a9044b2016-10-24 14:35:29 +00004344 // Assembler local symbols don't make any sense here. Complain loudly.
4345 if (Sym->isTemporary())
4346 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004347
Nirav Dave1a9044b2016-10-24 14:35:29 +00004348 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4349 return Error(Loc, "unable to emit symbol attribute");
4350 return false;
4351 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004352
Nirav Dave1a9044b2016-10-24 14:35:29 +00004353 if (parseMany(parseOp))
4354 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004355 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004356}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004357
Jim Grosbach4b905842013-09-20 23:08:21 +00004358/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004359/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004360bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004361 if (checkForValidSection())
4362 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004363
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004364 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004365 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004366 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004367 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004368
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004369 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004370 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004371
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004372 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004373 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004374 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004375
4376 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004377 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004378 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004379 return true;
4380
4381 int64_t Pow2Alignment = 0;
4382 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004383 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004384 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004385 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004386 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004387 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004388
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004389 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4390 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004391 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4392
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004393 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004394 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4395 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004396 if (!isPowerOf2_64(Pow2Alignment))
4397 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4398 Pow2Alignment = Log2_64(Pow2Alignment);
4399 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004400 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004401
Nirav Dave1a9044b2016-10-24 14:35:29 +00004402 if (parseToken(AsmToken::EndOfStatement,
4403 "unexpected token in '.comm' or '.lcomm' directive"))
4404 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004405
Chris Lattner28ad7542009-07-09 17:25:12 +00004406 // NOTE: a size of zero for a .comm should create a undefined symbol
4407 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004408 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004409 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004410 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004411
Eric Christopherbc818852010-05-14 01:38:54 +00004412 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004413 // may internally end up wanting an alignment in bytes.
4414 // FIXME: Diagnose overflow.
4415 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004416 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004417 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004418
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004419 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004420 return Error(IDLoc, "invalid symbol redefinition");
4421
Chris Lattner28ad7542009-07-09 17:25:12 +00004422 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004423 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004424 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004425 return false;
4426 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004427
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004428 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004429 return false;
4430}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004431
Jim Grosbach4b905842013-09-20 23:08:21 +00004432/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004433/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004434bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004435 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004436 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004437
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004438 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004439 if (parseToken(AsmToken::EndOfStatement,
4440 "unexpected token in '.abort' directive"))
4441 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004442
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004443 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004444 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004445 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004446 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004447 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004448
4449 return false;
4450}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004451
Jim Grosbach4b905842013-09-20 23:08:21 +00004452/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004453/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004454bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004455 // Allow the strings to have escaped octal character sequence.
4456 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004457 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004458
Nirav Davea645433c2016-07-18 15:24:03 +00004459 if (check(getTok().isNot(AsmToken::String),
4460 "expected string in '.include' directive") ||
4461 parseEscapedString(Filename) ||
4462 check(getTok().isNot(AsmToken::EndOfStatement),
4463 "unexpected token in '.include' directive") ||
4464 // Attempt to switch the lexer to the included file before consuming the
4465 // end of statement to avoid losing it when we switch.
4466 check(enterIncludeFile(Filename), IncludeLoc,
4467 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004468 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004469
4470 return false;
4471}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004472
Jim Grosbach4b905842013-09-20 23:08:21 +00004473/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004474/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004475bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004476 // Allow the strings to have escaped octal character sequence.
4477 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004478 SMLoc IncbinLoc = getTok().getLoc();
4479 if (check(getTok().isNot(AsmToken::String),
4480 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00004481 parseEscapedString(Filename))
4482 return true;
4483
4484 int64_t Skip = 0;
4485 const MCExpr *Count = nullptr;
4486 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004487 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00004488 // The skip expression can be omitted while specifying the count, e.g:
4489 // .incbin "filename",,4
4490 if (getTok().isNot(AsmToken::Comma)) {
4491 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4492 return true;
4493 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00004494 if (parseOptionalToken(AsmToken::Comma)) {
4495 CountLoc = getTok().getLoc();
4496 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00004497 return true;
4498 }
4499 }
4500
4501 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004502 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004503 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004504
Petr Hosek2f4ac442016-09-23 00:41:06 +00004505 if (check(Skip < 0, SkipLoc, "skip is negative"))
4506 return true;
4507
Nirav Dave1ab71992016-07-18 19:35:21 +00004508 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00004509 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00004510 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004511 return false;
4512}
4513
Jim Grosbach4b905842013-09-20 23:08:21 +00004514/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004515/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4516bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004517 TheCondStack.push_back(TheCondState);
4518 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004519 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004520 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004521 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004522 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004523 if (parseAbsoluteExpression(ExprValue) ||
4524 parseToken(AsmToken::EndOfStatement,
4525 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004526 return true;
4527
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004528 switch (DirKind) {
4529 default:
4530 llvm_unreachable("unsupported directive");
4531 case DK_IF:
4532 case DK_IFNE:
4533 break;
4534 case DK_IFEQ:
4535 ExprValue = ExprValue == 0;
4536 break;
4537 case DK_IFGE:
4538 ExprValue = ExprValue >= 0;
4539 break;
4540 case DK_IFGT:
4541 ExprValue = ExprValue > 0;
4542 break;
4543 case DK_IFLE:
4544 ExprValue = ExprValue <= 0;
4545 break;
4546 case DK_IFLT:
4547 ExprValue = ExprValue < 0;
4548 break;
4549 }
4550
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004551 TheCondState.CondMet = ExprValue;
4552 TheCondState.Ignore = !TheCondState.CondMet;
4553 }
4554
4555 return false;
4556}
4557
Jim Grosbach4b905842013-09-20 23:08:21 +00004558/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004559/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004560bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004561 TheCondStack.push_back(TheCondState);
4562 TheCondState.TheCond = AsmCond::IfCond;
4563
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004564 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004565 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004566 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004567 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004568
Nirav Davea645433c2016-07-18 15:24:03 +00004569 if (parseToken(AsmToken::EndOfStatement,
4570 "unexpected token in '.ifb' directive"))
4571 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004572
4573 TheCondState.CondMet = ExpectBlank == Str.empty();
4574 TheCondState.Ignore = !TheCondState.CondMet;
4575 }
4576
4577 return false;
4578}
4579
Jim Grosbach4b905842013-09-20 23:08:21 +00004580/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004581/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004582/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004583bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004584 TheCondStack.push_back(TheCondState);
4585 TheCondState.TheCond = AsmCond::IfCond;
4586
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004587 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004588 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004589 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004590 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004591
Nirav Davea645433c2016-07-18 15:24:03 +00004592 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4593 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004594
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004595 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004596
Nirav Davea645433c2016-07-18 15:24:03 +00004597 if (parseToken(AsmToken::EndOfStatement,
4598 "unexpected token in '.ifc' directive"))
4599 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004600
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004601 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004602 TheCondState.Ignore = !TheCondState.CondMet;
4603 }
4604
4605 return false;
4606}
4607
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004608/// parseDirectiveIfeqs
4609/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004610bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004611 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004612 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004613 return TokError("expected string parameter for '.ifeqs' directive");
4614 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004615 }
4616
4617 StringRef String1 = getTok().getStringContents();
4618 Lex();
4619
4620 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004621 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004622 return TokError(
4623 "expected comma after first string for '.ifeqs' directive");
4624 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004625 }
4626
4627 Lex();
4628
4629 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004630 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004631 return TokError("expected string parameter for '.ifeqs' directive");
4632 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004633 }
4634
4635 StringRef String2 = getTok().getStringContents();
4636 Lex();
4637
4638 TheCondStack.push_back(TheCondState);
4639 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004640 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004641 TheCondState.Ignore = !TheCondState.CondMet;
4642
4643 return false;
4644}
4645
Jim Grosbach4b905842013-09-20 23:08:21 +00004646/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004647/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004648bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004649 StringRef Name;
4650 TheCondStack.push_back(TheCondState);
4651 TheCondState.TheCond = AsmCond::IfCond;
4652
4653 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004654 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004655 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00004656 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4657 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4658 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004659
Jim Grosbach6f482002015-05-18 18:43:14 +00004660 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004661
4662 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004663 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004664 else
Craig Topper353eda42014-04-24 06:44:33 +00004665 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004666 TheCondState.Ignore = !TheCondState.CondMet;
4667 }
4668
4669 return false;
4670}
4671
Jim Grosbach4b905842013-09-20 23:08:21 +00004672/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004673/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004674bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004675 if (TheCondState.TheCond != AsmCond::IfCond &&
4676 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004677 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
4678 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004679 TheCondState.TheCond = AsmCond::ElseIfCond;
4680
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004681 bool LastIgnoreState = false;
4682 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004683 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004684 if (LastIgnoreState || TheCondState.CondMet) {
4685 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004686 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004687 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004688 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004689 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004690 return true;
4691
Nirav Dave1a9044b2016-10-24 14:35:29 +00004692 if (parseToken(AsmToken::EndOfStatement,
4693 "unexpected token in '.elseif' directive"))
4694 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004695
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004696 TheCondState.CondMet = ExprValue;
4697 TheCondState.Ignore = !TheCondState.CondMet;
4698 }
4699
4700 return false;
4701}
4702
Jim Grosbach4b905842013-09-20 23:08:21 +00004703/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004704/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004705bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004706 if (parseToken(AsmToken::EndOfStatement,
4707 "unexpected token in '.else' directive"))
4708 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004709
4710 if (TheCondState.TheCond != AsmCond::IfCond &&
4711 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004712 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
4713 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004714 TheCondState.TheCond = AsmCond::ElseCond;
4715 bool LastIgnoreState = false;
4716 if (!TheCondStack.empty())
4717 LastIgnoreState = TheCondStack.back().Ignore;
4718 if (LastIgnoreState || TheCondState.CondMet)
4719 TheCondState.Ignore = true;
4720 else
4721 TheCondState.Ignore = false;
4722
4723 return false;
4724}
4725
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004726/// parseDirectiveEnd
4727/// ::= .end
4728bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004729 if (parseToken(AsmToken::EndOfStatement,
4730 "unexpected token in '.end' directive"))
4731 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004732
4733 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00004734 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004735
4736 return false;
4737}
4738
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004739/// parseDirectiveError
4740/// ::= .err
4741/// ::= .error [string]
4742bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4743 if (!TheCondStack.empty()) {
4744 if (TheCondStack.back().Ignore) {
4745 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004746 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004747 }
4748 }
4749
4750 if (!WithMessage)
4751 return Error(L, ".err encountered");
4752
4753 StringRef Message = ".error directive invoked in source file";
4754 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004755 if (Lexer.isNot(AsmToken::String))
4756 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004757
4758 Message = getTok().getStringContents();
4759 Lex();
4760 }
4761
Nirav Dave2364748a2016-09-16 18:30:20 +00004762 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004763}
4764
Nico Weber404012b2014-07-24 16:26:06 +00004765/// parseDirectiveWarning
4766/// ::= .warning [string]
4767bool AsmParser::parseDirectiveWarning(SMLoc L) {
4768 if (!TheCondStack.empty()) {
4769 if (TheCondStack.back().Ignore) {
4770 eatToEndOfStatement();
4771 return false;
4772 }
4773 }
4774
4775 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00004776
4777 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004778 if (Lexer.isNot(AsmToken::String))
4779 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00004780
4781 Message = getTok().getStringContents();
4782 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00004783 if (parseToken(AsmToken::EndOfStatement,
4784 "expected end of statement in '.warning' directive"))
4785 return true;
Nico Weber404012b2014-07-24 16:26:06 +00004786 }
4787
Nirav Dave2364748a2016-09-16 18:30:20 +00004788 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00004789}
4790
Jim Grosbach4b905842013-09-20 23:08:21 +00004791/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004792/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00004793bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004794 if (parseToken(AsmToken::EndOfStatement,
4795 "unexpected token in '.endif' directive"))
4796 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004797
Jim Grosbach4b905842013-09-20 23:08:21 +00004798 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004799 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
4800 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004801 if (!TheCondStack.empty()) {
4802 TheCondState = TheCondStack.back();
4803 TheCondStack.pop_back();
4804 }
4805
4806 return false;
4807}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00004808
Eli Bendersky17233942013-01-15 22:59:42 +00004809void AsmParser::initializeDirectiveKindMap() {
4810 DirectiveKindMap[".set"] = DK_SET;
4811 DirectiveKindMap[".equ"] = DK_EQU;
4812 DirectiveKindMap[".equiv"] = DK_EQUIV;
4813 DirectiveKindMap[".ascii"] = DK_ASCII;
4814 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4815 DirectiveKindMap[".string"] = DK_STRING;
4816 DirectiveKindMap[".byte"] = DK_BYTE;
4817 DirectiveKindMap[".short"] = DK_SHORT;
4818 DirectiveKindMap[".value"] = DK_VALUE;
4819 DirectiveKindMap[".2byte"] = DK_2BYTE;
4820 DirectiveKindMap[".long"] = DK_LONG;
4821 DirectiveKindMap[".int"] = DK_INT;
4822 DirectiveKindMap[".4byte"] = DK_4BYTE;
4823 DirectiveKindMap[".quad"] = DK_QUAD;
4824 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00004825 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00004826 DirectiveKindMap[".single"] = DK_SINGLE;
4827 DirectiveKindMap[".float"] = DK_FLOAT;
4828 DirectiveKindMap[".double"] = DK_DOUBLE;
4829 DirectiveKindMap[".align"] = DK_ALIGN;
4830 DirectiveKindMap[".align32"] = DK_ALIGN32;
4831 DirectiveKindMap[".balign"] = DK_BALIGN;
4832 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4833 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4834 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4835 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4836 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4837 DirectiveKindMap[".org"] = DK_ORG;
4838 DirectiveKindMap[".fill"] = DK_FILL;
4839 DirectiveKindMap[".zero"] = DK_ZERO;
4840 DirectiveKindMap[".extern"] = DK_EXTERN;
4841 DirectiveKindMap[".globl"] = DK_GLOBL;
4842 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00004843 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4844 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4845 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4846 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4847 DirectiveKindMap[".reference"] = DK_REFERENCE;
4848 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4849 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4850 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4851 DirectiveKindMap[".comm"] = DK_COMM;
4852 DirectiveKindMap[".common"] = DK_COMMON;
4853 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4854 DirectiveKindMap[".abort"] = DK_ABORT;
4855 DirectiveKindMap[".include"] = DK_INCLUDE;
4856 DirectiveKindMap[".incbin"] = DK_INCBIN;
4857 DirectiveKindMap[".code16"] = DK_CODE16;
4858 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4859 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004860 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00004861 DirectiveKindMap[".irp"] = DK_IRP;
4862 DirectiveKindMap[".irpc"] = DK_IRPC;
4863 DirectiveKindMap[".endr"] = DK_ENDR;
4864 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4865 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4866 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4867 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004868 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4869 DirectiveKindMap[".ifge"] = DK_IFGE;
4870 DirectiveKindMap[".ifgt"] = DK_IFGT;
4871 DirectiveKindMap[".ifle"] = DK_IFLE;
4872 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00004873 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00004874 DirectiveKindMap[".ifb"] = DK_IFB;
4875 DirectiveKindMap[".ifnb"] = DK_IFNB;
4876 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004877 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00004878 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00004879 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00004880 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4881 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4882 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4883 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4884 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004885 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00004886 DirectiveKindMap[".endif"] = DK_ENDIF;
4887 DirectiveKindMap[".skip"] = DK_SKIP;
4888 DirectiveKindMap[".space"] = DK_SPACE;
4889 DirectiveKindMap[".file"] = DK_FILE;
4890 DirectiveKindMap[".line"] = DK_LINE;
4891 DirectiveKindMap[".loc"] = DK_LOC;
4892 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004893 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00004894 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004895 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
4896 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00004897 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00004898 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00004899 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004900 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
4901 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Eli Bendersky17233942013-01-15 22:59:42 +00004902 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4903 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4904 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4905 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4906 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4907 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4908 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4909 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4910 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4911 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4912 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4913 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4914 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4915 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4916 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4917 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4918 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4919 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4920 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4921 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4922 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00004923 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00004924 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4925 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4926 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00004927 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00004928 DirectiveKindMap[".endm"] = DK_ENDM;
4929 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4930 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004931 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004932 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00004933 DirectiveKindMap[".warning"] = DK_WARNING;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00004934 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00004935 DirectiveKindMap[".dc"] = DK_DC;
4936 DirectiveKindMap[".dc.a"] = DK_DC_A;
4937 DirectiveKindMap[".dc.b"] = DK_DC_B;
4938 DirectiveKindMap[".dc.d"] = DK_DC_D;
4939 DirectiveKindMap[".dc.l"] = DK_DC_L;
4940 DirectiveKindMap[".dc.s"] = DK_DC_S;
4941 DirectiveKindMap[".dc.w"] = DK_DC_W;
4942 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004943 DirectiveKindMap[".dcb"] = DK_DCB;
4944 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
4945 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
4946 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
4947 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
4948 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
4949 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00004950 DirectiveKindMap[".ds"] = DK_DS;
4951 DirectiveKindMap[".ds.b"] = DK_DS_B;
4952 DirectiveKindMap[".ds.d"] = DK_DS_D;
4953 DirectiveKindMap[".ds.l"] = DK_DS_L;
4954 DirectiveKindMap[".ds.p"] = DK_DS_P;
4955 DirectiveKindMap[".ds.s"] = DK_DS_S;
4956 DirectiveKindMap[".ds.w"] = DK_DS_W;
4957 DirectiveKindMap[".ds.x"] = DK_DS_X;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00004958}
4959
Jim Grosbach4b905842013-09-20 23:08:21 +00004960MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004961 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004962
Rafael Espindola34b9c512012-06-03 23:57:14 +00004963 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004964 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004965 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00004966 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004967 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00004968 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004969 }
4970
Rafael Espindola34b9c512012-06-03 23:57:14 +00004971 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00004972 (getTok().getIdentifier() == ".rept" ||
4973 getTok().getIdentifier() == ".irp" ||
4974 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004975 ++NestLevel;
4976 }
4977
4978 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00004979 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004980 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004981 EndToken = getTok();
4982 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004983 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004984 printError(getTok().getLoc(),
4985 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00004986 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004987 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004988 break;
4989 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004990 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004991 }
4992
Rafael Espindola34b9c512012-06-03 23:57:14 +00004993 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004994 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004995 }
4996
4997 const char *BodyStart = StartToken.getLoc().getPointer();
4998 const char *BodyEnd = EndToken.getLoc().getPointer();
4999 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5000
Rafael Espindola34b9c512012-06-03 23:57:14 +00005001 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005002 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00005003 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005004}
5005
Jim Grosbach4b905842013-09-20 23:08:21 +00005006void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005007 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005008 OS << ".endr\n";
5009
Rafael Espindola3560ff22014-08-27 20:03:13 +00005010 std::unique_ptr<MemoryBuffer> Instantiation =
5011 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005012
Rafael Espindola34b9c512012-06-03 23:57:14 +00005013 // Create the macro instantiation object and add to the current macro
5014 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005015 MacroInstantiation *MI = new MacroInstantiation(
5016 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005017 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005018
Rafael Espindola34b9c512012-06-03 23:57:14 +00005019 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005020 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005021 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005022 Lex();
5023}
5024
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005025/// parseDirectiveRept
5026/// ::= .rep | .rept count
5027bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005028 const MCExpr *CountExpr;
5029 SMLoc CountLoc = getTok().getLoc();
5030 if (parseExpression(CountExpr))
5031 return true;
5032
Rafael Espindola34b9c512012-06-03 23:57:14 +00005033 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00005034 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005035 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5036 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005037
Nirav Davea645433c2016-07-18 15:24:03 +00005038 if (check(Count < 0, CountLoc, "Count is negative") ||
5039 parseToken(AsmToken::EndOfStatement,
5040 "unexpected token in '" + Dir + "' directive"))
5041 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005042
5043 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005044 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005045 if (!M)
5046 return true;
5047
5048 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5049 // to hold the macro body with substitutions.
5050 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005051 raw_svector_ostream OS(Buf);
5052 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005053 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5054 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005055 return true;
5056 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005057 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005058
5059 return false;
5060}
5061
Jim Grosbach4b905842013-09-20 23:08:21 +00005062/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005063/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005064bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005065 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005066 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005067 if (check(parseIdentifier(Parameter.Name),
5068 "expected identifier in '.irp' directive") ||
5069 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5070 parseMacroArguments(nullptr, A) ||
5071 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005072 return true;
5073
Rafael Espindola768b41c2012-06-15 14:02:34 +00005074 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005075 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005076 if (!M)
5077 return true;
5078
5079 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5080 // to hold the macro body with substitutions.
5081 SmallString<256> Buf;
5082 raw_svector_ostream OS(Buf);
5083
Craig Topper84008482015-10-10 05:38:14 +00005084 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005085 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5086 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005087 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005088 return true;
5089 }
5090
Jim Grosbach4b905842013-09-20 23:08:21 +00005091 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005092
5093 return false;
5094}
5095
Jim Grosbach4b905842013-09-20 23:08:21 +00005096/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005097/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005098bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005099 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005100 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005101
5102 if (check(parseIdentifier(Parameter.Name),
5103 "expected identifier in '.irpc' directive") ||
5104 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5105 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005106 return true;
5107
5108 if (A.size() != 1 || A.front().size() != 1)
5109 return TokError("unexpected token in '.irpc' directive");
5110
5111 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005112 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5113 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005114
5115 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005116 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005117 if (!M)
5118 return true;
5119
5120 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5121 // to hold the macro body with substitutions.
5122 SmallString<256> Buf;
5123 raw_svector_ostream OS(Buf);
5124
5125 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005126 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005127 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005128 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005129
Toma Tabacu217116e2015-04-27 10:50:29 +00005130 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5131 // This is undocumented, but GAS seems to support it.
5132 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005133 return true;
5134 }
5135
Jim Grosbach4b905842013-09-20 23:08:21 +00005136 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005137
5138 return false;
5139}
5140
Jim Grosbach4b905842013-09-20 23:08:21 +00005141bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005142 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005143 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005144
5145 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005146 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005147 assert(getLexer().is(AsmToken::EndOfStatement));
5148
Jim Grosbach4b905842013-09-20 23:08:21 +00005149 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005150 return false;
5151}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005152
Jim Grosbach4b905842013-09-20 23:08:21 +00005153bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005154 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005155 const MCExpr *Value;
5156 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005157 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005158 return true;
5159 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5160 if (!MCE)
5161 return Error(ExprLoc, "unexpected expression in _emit");
5162 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005163 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005164 return Error(ExprLoc, "literal value out of range for directive");
5165
Craig Topper7d5b2312015-10-10 05:25:02 +00005166 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005167 return false;
5168}
5169
Jim Grosbach4b905842013-09-20 23:08:21 +00005170bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005171 const MCExpr *Value;
5172 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005173 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005174 return true;
5175 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5176 if (!MCE)
5177 return Error(ExprLoc, "unexpected expression in align");
5178 uint64_t IntValue = MCE->getValue();
5179 if (!isPowerOf2_64(IntValue))
5180 return Error(ExprLoc, "literal value not a power of two greater then zero");
5181
Craig Topper7d5b2312015-10-10 05:25:02 +00005182 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005183 return false;
5184}
5185
Chad Rosierf43fcf52013-02-13 21:27:17 +00005186// We are comparing pointers, but the pointers are relative to a single string.
5187// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005188static int rewritesSort(const AsmRewrite *AsmRewriteA,
5189 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005190 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5191 return -1;
5192 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5193 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005194
Chad Rosierfce4fab2013-04-08 17:43:47 +00005195 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5196 // rewrite to the same location. Make sure the SizeDirective rewrite is
5197 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5198 // ensures the sort algorithm is stable.
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;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005202
Jim Grosbach4b905842013-09-20 23:08:21 +00005203 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5204 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005205 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005206 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005207}
5208
Jim Grosbach4b905842013-09-20 23:08:21 +00005209bool AsmParser::parseMSInlineAsm(
5210 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
5211 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
5212 SmallVectorImpl<std::string> &Constraints,
5213 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5214 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005215 SmallVector<void *, 4> InputDecls;
5216 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005217 SmallVector<bool, 4> InputDeclsAddressOf;
5218 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005219 SmallVector<std::string, 4> InputConstraints;
5220 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005221 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005222
Benjamin Kramer1a136112013-02-15 20:37:21 +00005223 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005224
5225 // Prime the lexer.
5226 Lex();
5227
5228 // While we have input, parse each statement.
5229 unsigned InputIdx = 0;
5230 unsigned OutputIdx = 0;
5231 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005232 // Parse curly braces marking block start/end
5233 if (parseCurlyBlockScope(AsmStrRewrites))
5234 continue;
5235
Eli Friedman0f4871d2012-10-22 23:58:19 +00005236 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005237 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005238
Nirav Dave2364748a2016-09-16 18:30:20 +00005239 if (StatementErr || Info.ParseError) {
5240 // Emit pending errors if any exist.
5241 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005242 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005243 }
5244
5245 // No pending error should exist here.
5246 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005247
Benjamin Kramer1a136112013-02-15 20:37:21 +00005248 if (Info.Opcode == ~0U)
5249 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005250
Benjamin Kramer1a136112013-02-15 20:37:21 +00005251 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005252
Benjamin Kramer1a136112013-02-15 20:37:21 +00005253 // Build the list of clobbers, outputs and inputs.
5254 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005255 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005256
Benjamin Kramer1a136112013-02-15 20:37:21 +00005257 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005258 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005259 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005260
Benjamin Kramer1a136112013-02-15 20:37:21 +00005261 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005262 if (Operand.isReg() && !Operand.needAddressOf() &&
5263 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005264 unsigned NumDefs = Desc.getNumDefs();
5265 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005266 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5267 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005268 continue;
5269 }
5270
5271 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005272 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005273 if (SymName.empty())
5274 continue;
5275
David Blaikie960ea3f2014-06-08 16:18:35 +00005276 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005277 if (!OpDecl)
5278 continue;
5279
5280 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005281 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005282 if (isOutput) {
5283 ++InputIdx;
5284 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005285 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005286 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005287 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005288 } else {
5289 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005290 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5291 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005292 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005293 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005294 }
Reid Kleckneree088972013-12-10 18:27:32 +00005295
5296 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005297 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5298 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005299 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005300 }
5301
5302 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005303 NumOutputs = OutputDecls.size();
5304 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005305
5306 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005307 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5308 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5309 ClobberRegs.end());
5310 Clobbers.assign(ClobberRegs.size(), std::string());
5311 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5312 raw_string_ostream OS(Clobbers[I]);
5313 IP->printRegName(OS, ClobberRegs[I]);
5314 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005315
5316 // Merge the various outputs and inputs. Output are expected first.
5317 if (NumOutputs || NumInputs) {
5318 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005319 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005320 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005321 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005322 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005323 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005324 }
5325 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005326 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005327 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005328 }
5329 }
5330
5331 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005332 std::string AsmStringIR;
5333 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005334 StringRef ASMString =
5335 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5336 const char *AsmStart = ASMString.begin();
5337 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005338 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005339 for (const AsmRewrite &AR : AsmStrRewrites) {
5340 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005341 if (Kind == AOK_Delete)
5342 continue;
5343
David Majnemer8114c1a2014-06-23 02:17:16 +00005344 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005345 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005346
Chad Rosier120eefd2013-03-19 17:32:17 +00005347 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005348 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005349 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005350
Chad Rosier37e755c2012-10-23 17:43:43 +00005351 // Skip the original expression.
5352 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005353 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005354 continue;
5355 }
5356
Chad Rosierff10ed12013-04-12 16:26:42 +00005357 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005358 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005359 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005360 default:
5361 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005362 case AOK_Imm:
David Majnemer8114c1a2014-06-23 02:17:16 +00005363 OS << "$$" << AR.Val;
Chad Rosier11c42f22012-10-26 18:04:20 +00005364 break;
5365 case AOK_ImmPrefix:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005366 OS << "$$";
Chad Rosier8bce6642012-10-18 15:49:34 +00005367 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005368 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005369 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005370 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005371 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005372 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005373 break;
5374 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005375 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005376 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005377 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005378 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005379 default: break;
5380 case 8: OS << "byte ptr "; break;
5381 case 16: OS << "word ptr "; break;
5382 case 32: OS << "dword ptr "; break;
5383 case 64: OS << "qword ptr "; break;
5384 case 80: OS << "xword ptr "; break;
5385 case 128: OS << "xmmword ptr "; break;
5386 case 256: OS << "ymmword ptr "; break;
5387 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005388 break;
5389 case AOK_Emit:
5390 OS << ".byte";
5391 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005392 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005393 // MS alignment directives are measured in bytes. If the native assembler
5394 // measures alignment in bytes, we can pass it straight through.
5395 OS << ".align";
5396 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5397 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005398
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005399 // Alignment is in log2 form, so print that instead and skip the original
5400 // immediate.
5401 unsigned Val = AR.Val;
5402 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005403 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005404 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5405 break;
5406 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005407 case AOK_EVEN:
5408 OS << ".even";
5409 break;
Chad Rosierf0e87202012-10-25 20:41:34 +00005410 case AOK_DotOperator:
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005411 // Insert the dot if the user omitted it.
Alp Tokere69170a2014-06-26 22:52:05 +00005412 OS.flush();
5413 if (AsmStringIR.back() != '.')
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005414 OS << '.';
David Majnemer8114c1a2014-06-23 02:17:16 +00005415 OS << AR.Val;
Chad Rosierf0e87202012-10-25 20:41:34 +00005416 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005417 case AOK_EndOfStatement:
5418 OS << "\n\t";
5419 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005420 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005421
Chad Rosier8bce6642012-10-18 15:49:34 +00005422 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005423 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005424 }
5425
5426 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005427 if (AsmStart != AsmEnd)
5428 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005429
5430 AsmString = OS.str();
5431 return false;
5432}
5433
Pete Cooper80d21cb2015-06-22 19:35:57 +00005434namespace llvm {
5435namespace MCParserUtils {
5436
5437/// Returns whether the given symbol is used anywhere in the given expression,
5438/// or subexpressions.
5439static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5440 switch (Value->getKind()) {
5441 case MCExpr::Binary: {
5442 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5443 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5444 isSymbolUsedInExpression(Sym, BE->getRHS());
5445 }
5446 case MCExpr::Target:
5447 case MCExpr::Constant:
5448 return false;
5449 case MCExpr::SymbolRef: {
5450 const MCSymbol &S =
5451 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5452 if (S.isVariable())
5453 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5454 return &S == Sym;
5455 }
5456 case MCExpr::Unary:
5457 return isSymbolUsedInExpression(
5458 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5459 }
5460
5461 llvm_unreachable("Unknown expr kind!");
5462}
5463
5464bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5465 MCAsmParser &Parser, MCSymbol *&Sym,
5466 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005467
5468 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005469 SMLoc EqualLoc = Parser.getTok().getLoc();
Pete Cooper80d21cb2015-06-22 19:35:57 +00005470
5471 if (Parser.parseExpression(Value)) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00005472 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005473 }
5474
5475 // Note: we don't count b as used in "a = b". This is to allow
5476 // a = b
5477 // b = c
5478
Nirav Dave1a9044b2016-10-24 14:35:29 +00005479 if (Parser.parseToken(AsmToken::EndOfStatement))
5480 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00005481
5482 // Validate that the LHS is allowed to be a variable (either it has not been
5483 // used as a symbol, or it is an absolute symbol).
5484 Sym = Parser.getContext().lookupSymbol(Name);
5485 if (Sym) {
5486 // Diagnose assignment to a label.
5487 //
5488 // FIXME: Diagnostics. Note the location of the definition as a label.
5489 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5490 if (isSymbolUsedInExpression(Sym, Value))
5491 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005492 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5493 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005494 ; // Allow redefinitions of undefined symbols only used in directives.
5495 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5496 ; // Allow redefinitions of variables that haven't yet been used.
5497 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5498 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5499 else if (!Sym->isVariable())
5500 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5501 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5502 return Parser.Error(EqualLoc,
5503 "invalid reassignment of non-absolute variable '" +
5504 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005505 } else if (Name == ".") {
Oliver Stannard268f42f2016-12-14 10:43:58 +00005506 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005507 return false;
5508 } else
5509 Sym = Parser.getContext().getOrCreateSymbol(Name);
5510
5511 Sym->setRedefinable(allow_redef);
5512
5513 return false;
5514}
5515
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005516} // end namespace MCParserUtils
5517} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005518
Daniel Dunbar01e36072010-07-17 02:26:10 +00005519/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005520MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
5521 MCStreamer &Out, const MCAsmInfo &MAI) {
Jim Grosbach345768c2011-08-16 18:33:49 +00005522 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005523}