blob: 5262558df1a6d7c6d76b438b8672a380134afffd [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"
Chad Rosiereb5c1682013-02-13 18:38:58 +000015#include "llvm/ADT/STLExtras.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000016#include "llvm/ADT/SmallString.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000017#include "llvm/ADT/StringMap.h"
Daniel Dunbareb6bb322009-07-27 23:20:52 +000018#include "llvm/ADT/Twine.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000019#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000020#include "llvm/MC/MCContext.h"
Evan Cheng11424442011-07-26 00:24:13 +000021#include "llvm/MC/MCDwarf.h"
Daniel Dunbar115e4d62009-08-31 08:06:59 +000022#include "llvm/MC/MCExpr.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000023#include "llvm/MC/MCInstPrinter.h"
24#include "llvm/MC/MCInstrInfo.h"
Rafael Espindolae28610d2013-12-09 20:26:40 +000025#include "llvm/MC/MCObjectFileInfo.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000026#include "llvm/MC/MCParser/AsmCond.h"
27#include "llvm/MC/MCParser/AsmLexer.h"
28#include "llvm/MC/MCParser/MCAsmParser.h"
Pete Cooper80d21cb2015-06-22 19:35:57 +000029#include "llvm/MC/MCParser/MCAsmParserUtils.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000030#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000031#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Cheng76792992011-07-20 05:58:47 +000032#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000033#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000034#include "llvm/MC/MCStreamer.h"
Daniel Dunbarae7ac012009-06-29 23:43:14 +000035#include "llvm/MC/MCSymbol.h"
Daniel Sanders9f6ad492015-11-12 13:33:00 +000036#include "llvm/MC/MCValue.h"
Benjamin Kramer4efe5062012-01-28 15:28:41 +000037#include "llvm/Support/ErrorHandling.h"
Jim Grosbach76346c32011-06-29 16:05:14 +000038#include "llvm/Support/MathExtras.h"
Kevin Enderbye233dda2010-06-28 21:45:58 +000039#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000040#include "llvm/Support/SourceMgr.h"
Chris Lattner36e02122009-06-21 20:54:55 +000041#include "llvm/Support/raw_ostream.h"
Nick Lewycky0de20af2010-12-19 20:43:38 +000042#include <cctype>
Benjamin Kramerd59664f2014-04-29 23:26:49 +000043#include <deque>
Chad Rosier8bce6642012-10-18 15:49:34 +000044#include <string>
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000045#include <vector>
Chris Lattnerb0133452009-06-21 20:16:42 +000046using namespace llvm;
47
Eric Christophera7c32732012-12-18 00:30:54 +000048MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
Nick Lewyckyac612272012-10-19 07:00:09 +000049
Daniel Dunbar86033402010-07-12 17:54:38 +000050namespace {
Eli Benderskya313ae62013-01-16 18:56:50 +000051/// \brief Helper types for tracking macro definitions.
52typedef std::vector<AsmToken> MCAsmMacroArgument;
53typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000054
55struct MCAsmMacroParameter {
56 StringRef Name;
57 MCAsmMacroArgument Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000058 bool Required;
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +000059 bool Vararg;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000060
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +000061 MCAsmMacroParameter() : Required(false), Vararg(false) {}
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000062};
63
Eli Benderskya313ae62013-01-16 18:56:50 +000064typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
65
66struct MCAsmMacro {
67 StringRef Name;
68 StringRef Body;
69 MCAsmMacroParameters Parameters;
70
71public:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +000072 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
73 : Name(N), Body(B), Parameters(std::move(P)) {}
Eli Benderskya313ae62013-01-16 18:56:50 +000074};
75
Daniel Dunbar43235712010-07-18 18:54:11 +000076/// \brief Helper class for storing information about an active macro
77/// instantiation.
78struct MacroInstantiation {
Daniel Dunbar43235712010-07-18 18:54:11 +000079 /// The location of the instantiation.
80 SMLoc InstantiationLoc;
81
Daniel Dunbar40f1d852012-12-01 01:38:48 +000082 /// The buffer where parsing should resume upon instantiation completion.
83 int ExitBuffer;
84
Daniel Dunbar43235712010-07-18 18:54:11 +000085 /// The location where parsing should resume upon instantiation completion.
86 SMLoc ExitLoc;
87
Nico Weber155dccd12014-07-24 17:08:39 +000088 /// The depth of TheCondStack at the start of the instantiation.
89 size_t CondStackDepth;
90
Daniel Dunbar43235712010-07-18 18:54:11 +000091public:
Rafael Espindola9eef18c2014-08-27 19:49:03 +000092 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
Daniel Dunbar43235712010-07-18 18:54:11 +000093};
94
Eli Friedman0f4871d2012-10-22 23:58:19 +000095struct ParseStatementInfo {
Jim Grosbach4b905842013-09-20 23:08:21 +000096 /// \brief The parsed operands from the last parsed statement.
David Blaikie960ea3f2014-06-08 16:18:35 +000097 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
Eli Friedman0f4871d2012-10-22 23:58:19 +000098
Jim Grosbach4b905842013-09-20 23:08:21 +000099 /// \brief The opcode from the last parsed instruction.
Eli Friedman0f4871d2012-10-22 23:58:19 +0000100 unsigned Opcode;
101
Jim Grosbach4b905842013-09-20 23:08:21 +0000102 /// \brief Was there an error parsing the inline assembly?
Chad Rosier149e8e02012-12-12 22:45:52 +0000103 bool ParseError;
104
Eli Friedman0f4871d2012-10-22 23:58:19 +0000105 SmallVectorImpl<AsmRewrite> *AsmRewrites;
106
Craig Topper353eda42014-04-24 06:44:33 +0000107 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000108 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier149e8e02012-12-12 22:45:52 +0000109 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000110};
111
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000112/// \brief The concrete assembly parser instance.
113class AsmParser : public MCAsmParser {
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000114 AsmParser(const AsmParser &) = delete;
115 void operator=(const AsmParser &) = delete;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000116private:
117 AsmLexer Lexer;
118 MCContext &Ctx;
119 MCStreamer &Out;
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000120 const MCAsmInfo &MAI;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000121 SourceMgr &SrcMgr;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000122 SourceMgr::DiagHandlerTy SavedDiagHandler;
123 void *SavedDiagContext;
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000124 std::unique_ptr<MCAsmParserExtension> PlatformParser;
Rafael Espindola82065cb2011-04-11 21:49:50 +0000125
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000126 /// This is the current buffer index we're lexing from as managed by the
127 /// SourceMgr object.
Alp Tokera55b95b2014-07-06 10:33:31 +0000128 unsigned CurBuffer;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000129
130 AsmCond TheCondState;
131 std::vector<AsmCond> TheCondStack;
132
Jim Grosbach4b905842013-09-20 23:08:21 +0000133 /// \brief maps directive names to handler methods in parser
Eli Bendersky17233942013-01-15 22:59:42 +0000134 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000135 /// addDirectiveHandler.
Eli Bendersky17233942013-01-15 22:59:42 +0000136 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000137
Jim Grosbach4b905842013-09-20 23:08:21 +0000138 /// \brief Map of currently defined macros.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000139 StringMap<MCAsmMacro> MacroMap;
Daniel Dunbarc1f58ec2010-07-18 18:47:21 +0000140
Jim Grosbach4b905842013-09-20 23:08:21 +0000141 /// \brief Stack of active macro instantiations.
Daniel Dunbar43235712010-07-18 18:54:11 +0000142 std::vector<MacroInstantiation*> ActiveMacros;
143
Jim Grosbach4b905842013-09-20 23:08:21 +0000144 /// \brief List of bodies of anonymous macros.
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +0000145 std::deque<MCAsmMacro> MacroLikeBodies;
146
Daniel Dunbar828984f2010-07-18 18:38:02 +0000147 /// Boolean tracking whether macro substitution is enabled.
Eli Benderskyc2f6f922013-01-14 18:08:41 +0000148 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000149
Toma Tabacu217116e2015-04-27 10:50:29 +0000150 /// \brief Keeps track of how many .macro's have been instantiated.
151 unsigned NumOfMacroInstantiations;
152
Daniel Dunbar43325c42010-09-09 22:42:56 +0000153 /// Flag tracking whether any errors have been encountered.
154 unsigned HadError : 1;
155
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000156 /// The values from the last parsed cpp hash file line comment if any.
Tim Northoverc0bef992016-04-13 19:46:54 +0000157 struct CppHashInfoTy {
158 StringRef Filename;
Andrew Kaylorca196472016-04-21 20:09:35 +0000159 int64_t LineNumber = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000160 SMLoc Loc;
Andrew Kaylorca196472016-04-21 20:09:35 +0000161 unsigned Buf = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000162 };
163 CppHashInfoTy CppHashInfo;
164
165 /// \brief List of forward directional labels for diagnosis at the end.
166 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
167
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000168 /// When generating dwarf for assembly source files we need to calculate the
169 /// logical line number based on the last parsed cpp hash file line comment
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000170 /// and current line. Since this is slow and messes up the SourceMgr's
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000171 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
172 SMLoc LastQueryIDLoc;
Alp Tokera55b95b2014-07-06 10:33:31 +0000173 unsigned LastQueryBuffer;
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000174 unsigned LastQueryLine;
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000175
Devang Patela173ee52012-01-31 18:14:05 +0000176 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
177 unsigned AssemblerDialect;
178
Jim Grosbach4b905842013-09-20 23:08:21 +0000179 /// \brief is Darwin compatibility enabled?
Preston Gurd05500642012-09-19 20:36:12 +0000180 bool IsDarwin;
181
Jim Grosbach4b905842013-09-20 23:08:21 +0000182 /// \brief Are we parsing ms-style inline assembly?
Chad Rosier49963552012-10-13 00:26:04 +0000183 bool ParsingInlineAsm;
184
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000185public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000186 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000187 const MCAsmInfo &MAI);
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000188 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000189
Craig Topper59be68f2014-03-08 07:14:16 +0000190 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000191
Craig Topper59be68f2014-03-08 07:14:16 +0000192 void addDirectiveHandler(StringRef Directive,
193 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000194 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000195 }
196
Toma Tabacu11e14a92015-04-21 11:50:52 +0000197 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
198 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
199 }
200
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000201public:
202 /// @name MCAsmParser Interface
203 /// {
204
Craig Topper59be68f2014-03-08 07:14:16 +0000205 SourceMgr &getSourceManager() override { return SrcMgr; }
206 MCAsmLexer &getLexer() override { return Lexer; }
207 MCContext &getContext() override { return Ctx; }
208 MCStreamer &getStreamer() override { return Out; }
209 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000210 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000211 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000212 else
213 return AssemblerDialect;
214 }
Craig Topper59be68f2014-03-08 07:14:16 +0000215 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000216 AssemblerDialect = i;
217 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000218
Craig Topper59be68f2014-03-08 07:14:16 +0000219 void Note(SMLoc L, const Twine &Msg,
220 ArrayRef<SMRange> Ranges = None) override;
221 bool Warning(SMLoc L, const Twine &Msg,
222 ArrayRef<SMRange> Ranges = None) override;
223 bool Error(SMLoc L, const Twine &Msg,
224 ArrayRef<SMRange> Ranges = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000225
Craig Topper59be68f2014-03-08 07:14:16 +0000226 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000227
Craig Topper59be68f2014-03-08 07:14:16 +0000228 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
229 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000230
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000231 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000232 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier37e755c2012-10-23 17:43:43 +0000233 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000234 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000235 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000236 const MCInstrInfo *MII, const MCInstPrinter *IP,
237 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000238
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000239 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000240 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
241 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
242 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000243 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
244 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000245 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000246
Jim Grosbach4b905842013-09-20 23:08:21 +0000247 /// \brief Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000248 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000249 bool parseIdentifier(StringRef &Res) override;
250 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000251
Craig Topper59be68f2014-03-08 07:14:16 +0000252 void checkForValidSection() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000253 /// }
254
255private:
Daniel Dunbare5444a82010-09-09 22:42:59 +0000256
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000257 bool parseStatement(ParseStatementInfo &Info,
258 MCAsmParserSemaCallback *SI);
Marina Yatsina5f5de9f2016-03-07 18:11:16 +0000259 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
Jim Grosbach4b905842013-09-20 23:08:21 +0000260 void eatToEndOfLine();
Craig Topper3c76c522015-09-20 23:35:59 +0000261 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000262
Jim Grosbach4b905842013-09-20 23:08:21 +0000263 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000264 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000265 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000266 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000267 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000268 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000269
Eli Benderskya313ae62013-01-16 18:56:50 +0000270 /// \brief Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000271 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000272
273 /// \brief Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000274 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000275
276 /// \brief Lookup a previously defined macro.
277 /// \param Name Macro name.
278 /// \returns Pointer to macro. NULL if no such macro was defined.
Jim Grosbach4b905842013-09-20 23:08:21 +0000279 const MCAsmMacro* lookupMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000280
281 /// \brief Define a new macro with the given name and information.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000282 void defineMacro(StringRef Name, MCAsmMacro Macro);
Eli Benderskya313ae62013-01-16 18:56:50 +0000283
284 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
Jim Grosbach4b905842013-09-20 23:08:21 +0000285 void undefineMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000286
287 /// \brief Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000288 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000289
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000290 /// \brief Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000291 ///
292 /// \param M The macro.
293 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000294 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000295
296 /// \brief Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000297 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000298
David Majnemer91fc4c22014-01-29 18:57:46 +0000299 /// \brief Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000300 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000301
302 /// \brief Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000303 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000304
Jim Grosbach4b905842013-09-20 23:08:21 +0000305 void printMacroInstantiations();
306 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Dmitri Gribenko3238fb72013-05-05 00:40:33 +0000307 ArrayRef<SMRange> Ranges = None) const {
Chris Lattner72845262011-10-16 05:47:55 +0000308 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000309 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000310 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000311
Jim Grosbach4b905842013-09-20 23:08:21 +0000312 /// \brief Enter the specified file. This returns true on failure.
313 bool enterIncludeFile(const std::string &Filename);
314
315 /// \brief Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000316 /// This returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000317 bool processIncbinFile(const std::string &Filename);
Daniel Dunbar43235712010-07-18 18:54:11 +0000318
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000319 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000320 /// current token is not set; clients should ensure Lex() is called
321 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000322 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000323 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000324 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000325 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000326
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000327 /// \brief Parse up to the end of statement and a return the contents from the
328 /// current token until the end of the statement; the current token on exit
329 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000330 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000331
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000332 /// \brief Parse until the end of a statement or a comma is encountered,
333 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000334 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000335
Jim Grosbach4b905842013-09-20 23:08:21 +0000336 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +0000337 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000338
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000339 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
340 MCBinaryExpr::Opcode &Kind);
341
Jim Grosbach4b905842013-09-20 23:08:21 +0000342 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
343 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
344 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000345
Jim Grosbach4b905842013-09-20 23:08:21 +0000346 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000347
Eli Bendersky17233942013-01-15 22:59:42 +0000348 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000349 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000350 DK_NO_DIRECTIVE, // Placeholder
351 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000352 DK_RELOC,
David Woodhoused6de0d92014-02-01 16:20:59 +0000353 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
354 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky96522722013-01-11 22:55:28 +0000355 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000356 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
Kevin Enderby3aeada22013-08-28 17:50:59 +0000357 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
Lang Hamesf9033bb2016-04-11 18:33:45 +0000358 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER,
Lang Hames1b640e02016-03-15 01:43:05 +0000359 DK_PRIVATE_EXTERN, DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000360 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
361 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000362 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
Sid Manning51c35602015-03-18 14:20:54 +0000363 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
364 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
Eli Bendersky17233942013-01-15 22:59:42 +0000365 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000366 DK_CV_FILE, DK_CV_LOC, DK_CV_LINETABLE, DK_CV_INLINE_LINETABLE,
David Majnemer408b5e62016-02-05 01:55:49 +0000367 DK_CV_DEF_RANGE, DK_CV_STRINGTABLE, DK_CV_FILECHECKSUMS,
Eli Bendersky17233942013-01-15 22:59:42 +0000368 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
369 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
370 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
371 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
372 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000373 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
Nico Weber155dccd12014-07-24 17:08:39 +0000374 DK_MACROS_ON, DK_MACROS_OFF,
375 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000376 DK_SLEB128, DK_ULEB128,
Nico Weber404012b2014-07-24 16:26:06 +0000377 DK_ERR, DK_ERROR, DK_WARNING,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000378 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000379 };
380
Jim Grosbach4b905842013-09-20 23:08:21 +0000381 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000382 /// directives parsed by this class.
383 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000384
385 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000386 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000387 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Jim Grosbach4b905842013-09-20 23:08:21 +0000388 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
David Woodhoused6de0d92014-02-01 16:20:59 +0000389 bool parseDirectiveOctaValue(); // ".octa"
Jim Grosbach4b905842013-09-20 23:08:21 +0000390 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
391 bool parseDirectiveFill(); // ".fill"
392 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000393 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000394 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
395 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000396 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000397 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000398
Eli Bendersky17233942013-01-15 22:59:42 +0000399 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000400 bool parseDirectiveFile(SMLoc DirectiveLoc);
401 bool parseDirectiveLine();
402 bool parseDirectiveLoc();
403 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000404
David Majnemer408b5e62016-02-05 01:55:49 +0000405 // ".cv_file", ".cv_loc", ".cv_linetable", "cv_inline_linetable",
406 // ".cv_def_range"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000407 bool parseDirectiveCVFile();
408 bool parseDirectiveCVLoc();
409 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000410 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000411 bool parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000412 bool parseDirectiveCVStringTable();
413 bool parseDirectiveCVFileChecksums();
414
Eli Bendersky17233942013-01-15 22:59:42 +0000415 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000416 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000417 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000418 bool parseDirectiveCFISections();
419 bool parseDirectiveCFIStartProc();
420 bool parseDirectiveCFIEndProc();
421 bool parseDirectiveCFIDefCfaOffset();
422 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
423 bool parseDirectiveCFIAdjustCfaOffset();
424 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
425 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
426 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
427 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
428 bool parseDirectiveCFIRememberState();
429 bool parseDirectiveCFIRestoreState();
430 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
431 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
432 bool parseDirectiveCFIEscape();
433 bool parseDirectiveCFISignalFrame();
434 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000435
436 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000437 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000438 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000439 bool parseDirectiveEndMacro(StringRef Directive);
440 bool parseDirectiveMacro(SMLoc DirectiveLoc);
441 bool parseDirectiveMacrosOnOff(StringRef Directive);
Eli Bendersky17233942013-01-15 22:59:42 +0000442
Eli Benderskyf483ff92012-12-20 19:05:53 +0000443 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000444 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000445 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000446 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000447 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000448 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000449
Eli Bendersky17233942013-01-15 22:59:42 +0000450 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000451 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000452
453 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000454 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000455
Jim Grosbach4b905842013-09-20 23:08:21 +0000456 /// \brief Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000457 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000458 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000459
Jim Grosbach4b905842013-09-20 23:08:21 +0000460 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000461
Jim Grosbach4b905842013-09-20 23:08:21 +0000462 bool parseDirectiveAbort(); // ".abort"
463 bool parseDirectiveInclude(); // ".include"
464 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000465
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000466 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
467 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000468 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000469 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000470 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000471 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000472 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
473 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000474 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000475 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
476 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
477 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
478 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000479 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000480
Jim Grosbach4b905842013-09-20 23:08:21 +0000481 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000482 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000483
Rafael Espindola34b9c512012-06-03 23:57:14 +0000484 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000485 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
486 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000487 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000488 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000489 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
490 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
491 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000492
Chad Rosierc7f552c2013-02-12 21:33:51 +0000493 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000494 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000495 size_t Len);
496
497 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000498 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000499
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000500 // "end"
501 bool parseDirectiveEnd(SMLoc DirectiveLoc);
502
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000503 // ".err" or ".error"
504 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000505
Nico Weber404012b2014-07-24 16:26:06 +0000506 // ".warning"
507 bool parseDirectiveWarning(SMLoc DirectiveLoc);
508
Eli Bendersky17233942013-01-15 22:59:42 +0000509 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000510};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000511}
Daniel Dunbar86033402010-07-12 17:54:38 +0000512
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000513namespace llvm {
514
515extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000516extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000517extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000518
519}
520
Chris Lattnerc35681b2010-01-19 19:46:13 +0000521enum { DEFAULT_ADDRSPACE = 0 };
522
David Blaikie9f380a32015-03-16 18:06:57 +0000523AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
524 const MCAsmInfo &MAI)
525 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
526 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
Tim Northoverc0bef992016-04-13 19:46:54 +0000527 MacrosEnabledFlag(true), HadError(false), CppHashInfo(),
Oliver Stannardcf6bfb12014-11-03 12:19:03 +0000528 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000529 // Save the old handler.
530 SavedDiagHandler = SrcMgr.getDiagHandler();
531 SavedDiagContext = SrcMgr.getDiagContext();
532 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000533 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000534 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000535
Daniel Dunbarc5011082010-07-12 18:12:02 +0000536 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000537 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
538 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000539 PlatformParser.reset(createCOFFAsmParser());
540 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000541 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000542 PlatformParser.reset(createDarwinAsmParser());
543 IsDarwin = true;
544 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000545 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000546 PlatformParser.reset(createELFAsmParser());
547 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000548 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000549
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000550 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000551 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000552
553 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000554}
555
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000556AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000557 assert((HadError || ActiveMacros.empty()) &&
558 "Unexpected active macro instantiation!");
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000559}
560
Jim Grosbach4b905842013-09-20 23:08:21 +0000561void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000562 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000563 for (std::vector<MacroInstantiation *>::const_reverse_iterator
564 it = ActiveMacros.rbegin(),
565 ie = ActiveMacros.rend();
566 it != ie; ++it)
567 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000568 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000569}
570
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000571void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
572 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
573 printMacroInstantiations();
574}
575
Chris Lattnera3a06812011-10-16 04:47:35 +0000576bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000577 if(getTargetParser().getTargetOptions().MCNoWarn)
578 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000579 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Chris Lattnera3a06812011-10-16 04:47:35 +0000580 return Error(L, Msg, Ranges);
Jim Grosbach4b905842013-09-20 23:08:21 +0000581 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
582 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000583 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000584}
585
Chris Lattnera3a06812011-10-16 04:47:35 +0000586bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000587 HadError = true;
Jim Grosbach4b905842013-09-20 23:08:21 +0000588 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
589 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000590 return true;
591}
592
Jim Grosbach4b905842013-09-20 23:08:21 +0000593bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000594 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000595 unsigned NewBuf =
596 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
597 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000598 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000599
Sean Callanan7a77eae2010-01-21 00:19:58 +0000600 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000601 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000602 return false;
603}
Daniel Dunbar43235712010-07-18 18:54:11 +0000604
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000605/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000606/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000607/// returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000608bool AsmParser::processIncbinFile(const std::string &Filename) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000609 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000610 unsigned NewBuf =
611 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
612 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000613 return true;
614
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000615 // Pick up the bytes from the file and emit them.
Rafael Espindola64e1af82013-07-02 15:49:13 +0000616 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
Kevin Enderby109f25c2011-12-14 21:47:48 +0000617 return false;
618}
619
Alp Tokera55b95b2014-07-06 10:33:31 +0000620void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
621 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000622 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
623 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000624}
625
Sean Callanan7a77eae2010-01-21 00:19:58 +0000626const AsmToken &AsmParser::Lex() {
627 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000628
Sean Callanan7a77eae2010-01-21 00:19:58 +0000629 if (tok->is(AsmToken::Eof)) {
630 // If this is the end of an included file, pop the parent file off the
631 // include stack.
632 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
633 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000634 jumpToLoc(ParentIncludeLoc);
Sean Callanan7a77eae2010-01-21 00:19:58 +0000635 tok = &Lexer.Lex();
636 }
637 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000638
Sean Callanan7a77eae2010-01-21 00:19:58 +0000639 if (tok->is(AsmToken::Error))
Daniel Dunbard8a18452010-07-18 18:31:45 +0000640 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencer530ce852010-10-09 11:00:50 +0000641
Sean Callanan7a77eae2010-01-21 00:19:58 +0000642 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000643}
644
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000645bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000646 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000647 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000648 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000649
Chris Lattner36e02122009-06-21 20:54:55 +0000650 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000651 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000652
653 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000654 AsmCond StartingCondState = TheCondState;
655
Kevin Enderby6469fc22011-11-01 22:27:22 +0000656 // If we are generating dwarf for assembly source files save the initial text
657 // section and generate a .file directive.
658 if (getContext().getGenDwarfForAssembly()) {
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000659 MCSection *Sec = getStreamer().getCurrentSection().first;
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000660 if (!Sec->getBeginSymbol()) {
661 MCSymbol *SectionStartSym = getContext().createTempSymbol();
662 getStreamer().EmitLabel(SectionStartSym);
663 Sec->setBeginSymbol(SectionStartSym);
664 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000665 bool InsertResult = getContext().addGenDwarfSection(Sec);
666 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000667 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000668 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
669 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000670 }
671
Chris Lattner73f36112009-07-02 21:53:43 +0000672 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000673 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman0f4871d2012-10-22 23:58:19 +0000674 ParseStatementInfo Info;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000675 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000676 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000677
Daniel Dunbar43325c42010-09-09 22:42:56 +0000678 // We had an error, validate that one was emitted and recover by skipping to
679 // the next line.
680 assert(HadError && "Parse statement returned an error, but none emitted!");
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000681 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000682 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000683
684 if (TheCondState.TheCond != StartingCondState.TheCond ||
685 TheCondState.Ignore != StartingCondState.Ignore)
686 return TokError("unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000687
688 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000689 const auto &LineTables = getContext().getMCDwarfLineTables();
690 if (!LineTables.empty()) {
691 unsigned Index = 0;
692 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
693 if (File.Name.empty() && Index != 0)
694 TokError("unassigned file number: " + Twine(Index) +
695 " for .file directives");
696 ++Index;
697 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000698 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000699
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000700 // Check to see that all assembler local symbols were actually defined.
701 // Targets that don't do subsections via symbols may not want this, though,
702 // so conservatively exclude them. Only do this if we're finalizing, though,
703 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000704 if (!NoFinalize) {
705 if (MAI.hasSubsectionsViaSymbols()) {
706 for (const auto &TableEntry : getContext().getSymbols()) {
707 MCSymbol *Sym = TableEntry.getValue();
708 // Variable symbols may not be marked as defined, so check those
709 // explicitly. If we know it's a variable, we have a definition for
710 // the purposes of this check.
711 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
712 // FIXME: We would really like to refer back to where the symbol was
713 // first referenced for a source location. We need to add something
714 // to track that. Currently, we just point to the end of the file.
715 HadError |=
716 Error(getLexer().getLoc(), "assembler local symbol '" +
717 Sym->getName() + "' not defined");
718 }
719 }
720
721 // Temporary symbols like the ones for directional jumps don't go in the
722 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000723 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
724 if (std::get<2>(LocSym)->isUndefined()) {
725 // Reset the state of any "# line file" directives we've seen to the
726 // context as it was at the diagnostic site.
727 CppHashInfo = std::get<1>(LocSym);
728 HadError |= Error(std::get<0>(LocSym), "directional label undefined");
729 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000730 }
731 }
732
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000733 // Finalize the output stream if there are no errors and if the client wants
734 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000735 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000736 Out.Finish();
737
Oliver Stannard07b43d32015-11-17 09:58:07 +0000738 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000739}
740
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000741void AsmParser::checkForValidSection() {
Peter Collingbourne2f495b92013-04-17 21:18:16 +0000742 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
Daniel Dunbare5444a82010-09-09 22:42:59 +0000743 TokError("expected section directive before assembly directive");
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000744 Out.InitSections(false);
Daniel Dunbare5444a82010-09-09 22:42:59 +0000745 }
746}
747
Jim Grosbach4b905842013-09-20 23:08:21 +0000748/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000749void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000750 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Sean Callanan686ed8d2010-01-19 20:22:31 +0000751 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000752
Chris Lattnere5074c42009-06-22 01:29:09 +0000753 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000754 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan686ed8d2010-01-19 20:22:31 +0000755 Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000756}
757
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000758StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000759 const char *Start = getTok().getLoc().getPointer();
760
Jim Grosbach4b905842013-09-20 23:08:21 +0000761 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000762 Lex();
763
764 const char *End = getTok().getLoc().getPointer();
765 return StringRef(Start, End - Start);
766}
Chris Lattner78db3622009-06-22 05:51:26 +0000767
Jim Grosbach4b905842013-09-20 23:08:21 +0000768StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000769 const char *Start = getTok().getLoc().getPointer();
770
771 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000772 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000773 Lex();
774
775 const char *End = getTok().getLoc().getPointer();
776 return StringRef(Start, End - Start);
777}
778
Jim Grosbach4b905842013-09-20 23:08:21 +0000779/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000780/// NOTE: This assumes the leading '(' has already been consumed.
781///
782/// parenexpr ::= expr)
783///
Jim Grosbach4b905842013-09-20 23:08:21 +0000784bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
785 if (parseExpression(Res))
786 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000787 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +0000788 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000789 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000790 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +0000791 return false;
792}
Chris Lattner78db3622009-06-22 05:51:26 +0000793
Jim Grosbach4b905842013-09-20 23:08:21 +0000794/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000795/// NOTE: This assumes the leading '[' has already been consumed.
796///
797/// bracketexpr ::= expr]
798///
Jim Grosbach4b905842013-09-20 23:08:21 +0000799bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
800 if (parseExpression(Res))
801 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000802 if (Lexer.isNot(AsmToken::RBrac))
803 return TokError("expected ']' in brackets expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000804 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000805 Lex();
806 return false;
807}
808
Jim Grosbach4b905842013-09-20 23:08:21 +0000809/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000810/// primaryexpr ::= (parenexpr
811/// primaryexpr ::= symbol
812/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +0000813/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +0000814/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +0000815bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000816 SMLoc FirstTokenLoc = getLexer().getLoc();
817 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
818 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +0000819 default:
820 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +0000821 // If we have an error assume that we've already handled it.
822 case AsmToken::Error:
823 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000824 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000825 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000826 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000827 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000828 Res = MCUnaryExpr::createLNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000829 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +0000830 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +0000831 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +0000832 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +0000833 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +0000834 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000835 if (parseIdentifier(Identifier)) {
David Majnemer0c58bc62013-09-25 10:47:21 +0000836 if (FirstTokenKind == AsmToken::Dollar) {
837 if (Lexer.getMAI().getDollarIsPC()) {
838 // This is a '$' reference, which references the current PC. Emit a
839 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000840 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +0000841 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000842 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +0000843 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +0000844 EndLoc = FirstTokenLoc;
845 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +0000846 }
847 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +0000848 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000849 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000850 // Parse symbol variant
851 std::pair<StringRef, StringRef> Split;
852 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +0000853 if (FirstTokenKind == AsmToken::String) {
854 if (Lexer.is(AsmToken::At)) {
855 Lexer.Lex(); // eat @
856 SMLoc AtLoc = getLexer().getLoc();
857 StringRef VName;
858 if (parseIdentifier(VName))
859 return Error(AtLoc, "expected symbol variant after '@'");
860
861 Split = std::make_pair(Identifier, VName);
862 }
863 } else {
864 Split = Identifier.split('@');
865 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000866 } else if (Lexer.is(AsmToken::LParen)) {
867 Lexer.Lex(); // eat (
868 StringRef VName;
869 parseIdentifier(VName);
870 if (Lexer.isNot(AsmToken::RParen)) {
871 return Error(Lexer.getTok().getLoc(),
872 "unexpected token in variant, expected ')'");
873 }
874 Lexer.Lex(); // eat )
875 Split = std::make_pair(Identifier, VName);
876 }
Daniel Dunbar24764322010-08-24 19:13:42 +0000877
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000878 EndLoc = SMLoc::getFromPointer(Identifier.end());
879
Daniel Dunbard20cda02009-10-16 01:34:54 +0000880 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +0000881 StringRef SymbolName = Identifier;
882 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +0000883
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000884 // Lookup the symbol variant if used.
David Peixotto8ad70b32013-12-04 22:43:20 +0000885 if (Split.second.size()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000886 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +0000887 if (Variant != MCSymbolRefExpr::VK_Invalid) {
888 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +0000889 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +0000890 Variant = MCSymbolRefExpr::VK_None;
891 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +0000892 return Error(SMLoc::getFromPointer(Split.second.begin()),
893 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000894 }
895 }
Daniel Dunbar55992562010-03-15 23:51:06 +0000896
Jim Grosbach6f482002015-05-18 18:43:14 +0000897 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +0000898
Daniel Dunbard20cda02009-10-16 01:34:54 +0000899 // If this is an absolute variable reference, substitute it now to preserve
900 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +0000901 if (Sym->isVariable() &&
902 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +0000903 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +0000904 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +0000905
Vedant Kumar86dbd922015-08-31 17:44:53 +0000906 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +0000907 return false;
908 }
909
910 // Otherwise create a symbol ref.
Jim Grosbach13760bd2015-05-30 01:25:56 +0000911 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Chris Lattner78db3622009-06-22 05:51:26 +0000912 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +0000913 }
David Woodhousef42a6662014-02-01 16:20:54 +0000914 case AsmToken::BigNum:
915 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +0000916 case AsmToken::Integer: {
917 SMLoc Loc = getTok().getLoc();
918 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +0000919 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000920 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000921 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +0000922 // Look for 'b' or 'f' following an Integer as a directional label
923 if (Lexer.getKind() == AsmToken::Identifier) {
924 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +0000925 // Lookup the symbol variant if used.
926 std::pair<StringRef, StringRef> Split = IDVal.split('@');
927 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
928 if (Split.first.size() != IDVal.size()) {
929 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +0000930 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +0000931 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000932 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +0000933 }
Jim Grosbach4b905842013-09-20 23:08:21 +0000934 if (IDVal == "f" || IDVal == "b") {
935 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +0000936 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +0000937 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +0000938 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +0000939 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000940 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000941 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +0000942 Lex(); // Eat identifier.
943 }
944 }
Chris Lattner78db3622009-06-22 05:51:26 +0000945 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +0000946 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +0000947 case AsmToken::Real: {
948 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +0000949 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +0000950 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000951 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +0000952 Lex(); // Eat token.
953 return false;
954 }
Chris Lattner6b55cb92010-04-14 04:40:28 +0000955 case AsmToken::Dot: {
956 // This is a '.' reference, which references the current PC. Emit a
957 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000958 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +0000959 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000960 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000961 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +0000962 Lex(); // Eat identifier.
963 return false;
964 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000965 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000966 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +0000967 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000968 case AsmToken::LBrac:
969 if (!PlatformParser->HasBracketExpressions())
970 return TokError("brackets expression not supported on this target");
971 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +0000972 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000973 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000974 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000975 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000976 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000977 Res = MCUnaryExpr::createMinus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000978 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000979 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000980 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000981 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000982 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000983 Res = MCUnaryExpr::createPlus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000984 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000985 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000986 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000987 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000988 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000989 Res = MCUnaryExpr::createNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000990 return false;
Chris Lattner78db3622009-06-22 05:51:26 +0000991 }
992}
Chris Lattner7fdbce72009-06-22 06:32:03 +0000993
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000994bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +0000995 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000996 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +0000997}
998
Daniel Dunbar55f16672010-09-17 02:47:07 +0000999const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001000AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001001 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001002 // Ask the target implementation about this expression first.
1003 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1004 if (NewE)
1005 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001006 // Recurse over the given expression, rebuilding it to apply the given variant
1007 // if there is exactly one symbol.
1008 switch (E->getKind()) {
1009 case MCExpr::Target:
1010 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001011 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001012
1013 case MCExpr::SymbolRef: {
1014 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1015
1016 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001017 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1018 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001019 return E;
1020 }
1021
Jim Grosbach13760bd2015-05-30 01:25:56 +00001022 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001023 }
1024
1025 case MCExpr::Unary: {
1026 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001027 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001028 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001029 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001030 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001031 }
1032
1033 case MCExpr::Binary: {
1034 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001035 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1036 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001037
1038 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001039 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001040
Jim Grosbach4b905842013-09-20 23:08:21 +00001041 if (!LHS)
1042 LHS = BE->getLHS();
1043 if (!RHS)
1044 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001045
Jim Grosbach13760bd2015-05-30 01:25:56 +00001046 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001047 }
1048 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001049
Craig Toppera2886c22012-02-07 05:05:23 +00001050 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001051}
1052
Jim Grosbach4b905842013-09-20 23:08:21 +00001053/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001054///
Jim Grosbachbd164242011-08-20 16:24:13 +00001055/// expr ::= expr &&,|| expr -> lowest.
1056/// expr ::= expr |,^,&,! expr
1057/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1058/// expr ::= expr <<,>> expr
1059/// expr ::= expr +,- expr
1060/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001061/// expr ::= primaryexpr
1062///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001063bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001064 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001065 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001066 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001067 return true;
1068
Daniel Dunbar55f16672010-09-17 02:47:07 +00001069 // As a special case, we support 'a op b @ modifier' by rewriting the
1070 // expression to include the modifier. This is inefficient, but in general we
1071 // expect users to use 'a@modifier op b'.
1072 if (Lexer.getKind() == AsmToken::At) {
1073 Lex();
1074
1075 if (Lexer.isNot(AsmToken::Identifier))
1076 return TokError("unexpected symbol modifier following '@'");
1077
1078 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001079 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001080 if (Variant == MCSymbolRefExpr::VK_Invalid)
1081 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1082
Jim Grosbach4b905842013-09-20 23:08:21 +00001083 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001084 if (!ModifiedRes) {
1085 return TokError("invalid modifier '" + getTok().getIdentifier() +
1086 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001087 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001088
Daniel Dunbar55f16672010-09-17 02:47:07 +00001089 Res = ModifiedRes;
1090 Lex();
1091 }
1092
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001093 // Try to constant fold it up front, if possible.
1094 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001095 if (Res->evaluateAsAbsolute(Value))
1096 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001097
1098 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001099}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001100
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001101bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001102 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001103 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001104}
1105
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001106bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1107 SMLoc &EndLoc) {
1108 if (parseParenExpr(Res, EndLoc))
1109 return true;
1110
1111 for (; ParenDepth > 0; --ParenDepth) {
1112 if (parseBinOpRHS(1, Res, EndLoc))
1113 return true;
1114
1115 // We don't Lex() the last RParen.
1116 // This is the same behavior as parseParenExpression().
1117 if (ParenDepth - 1 > 0) {
1118 if (Lexer.isNot(AsmToken::RParen))
1119 return TokError("expected ')' in parentheses expression");
1120 EndLoc = Lexer.getTok().getEndLoc();
1121 Lex();
1122 }
1123 }
1124 return false;
1125}
1126
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001127bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001128 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001129
Daniel Dunbar75630b32009-06-30 02:10:03 +00001130 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001131 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001132 return true;
1133
Jim Grosbach13760bd2015-05-30 01:25:56 +00001134 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001135 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001136
1137 return false;
1138}
1139
David Majnemer0993e0b2015-10-26 03:15:34 +00001140static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1141 MCBinaryExpr::Opcode &Kind,
1142 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001143 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001144 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001145 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001146
Jim Grosbach4b905842013-09-20 23:08:21 +00001147 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001148 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001149 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001150 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001151 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001152 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001153 return 1;
1154
Jim Grosbach4b905842013-09-20 23:08:21 +00001155 // Low Precedence: |, &, ^
1156 //
1157 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001158 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001159 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001160 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001161 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001162 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001163 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001164 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001165 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001166 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001167
Jim Grosbach4b905842013-09-20 23:08:21 +00001168 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001169 case AsmToken::EqualEqual:
1170 Kind = MCBinaryExpr::EQ;
1171 return 3;
1172 case AsmToken::ExclaimEqual:
1173 case AsmToken::LessGreater:
1174 Kind = MCBinaryExpr::NE;
1175 return 3;
1176 case AsmToken::Less:
1177 Kind = MCBinaryExpr::LT;
1178 return 3;
1179 case AsmToken::LessEqual:
1180 Kind = MCBinaryExpr::LTE;
1181 return 3;
1182 case AsmToken::Greater:
1183 Kind = MCBinaryExpr::GT;
1184 return 3;
1185 case AsmToken::GreaterEqual:
1186 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001187 return 3;
1188
Jim Grosbach4b905842013-09-20 23:08:21 +00001189 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001190 case AsmToken::LessLess:
1191 Kind = MCBinaryExpr::Shl;
1192 return 4;
1193 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001194 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001195 return 4;
1196
Jim Grosbach4b905842013-09-20 23:08:21 +00001197 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001198 case AsmToken::Plus:
1199 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001200 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001201 case AsmToken::Minus:
1202 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001203 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001204
Jim Grosbach4b905842013-09-20 23:08:21 +00001205 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001206 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001207 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001208 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001209 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001210 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001211 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001212 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001213 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001214 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001215 }
1216}
1217
David Majnemer0993e0b2015-10-26 03:15:34 +00001218static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1219 MCBinaryExpr::Opcode &Kind,
1220 bool ShouldUseLogicalShr) {
1221 switch (K) {
1222 default:
1223 return 0; // not a binop.
1224
1225 // Lowest Precedence: &&, ||
1226 case AsmToken::AmpAmp:
1227 Kind = MCBinaryExpr::LAnd;
1228 return 2;
1229 case AsmToken::PipePipe:
1230 Kind = MCBinaryExpr::LOr;
1231 return 1;
1232
1233 // Low Precedence: ==, !=, <>, <, <=, >, >=
1234 case AsmToken::EqualEqual:
1235 Kind = MCBinaryExpr::EQ;
1236 return 3;
1237 case AsmToken::ExclaimEqual:
1238 case AsmToken::LessGreater:
1239 Kind = MCBinaryExpr::NE;
1240 return 3;
1241 case AsmToken::Less:
1242 Kind = MCBinaryExpr::LT;
1243 return 3;
1244 case AsmToken::LessEqual:
1245 Kind = MCBinaryExpr::LTE;
1246 return 3;
1247 case AsmToken::Greater:
1248 Kind = MCBinaryExpr::GT;
1249 return 3;
1250 case AsmToken::GreaterEqual:
1251 Kind = MCBinaryExpr::GTE;
1252 return 3;
1253
1254 // Low Intermediate Precedence: +, -
1255 case AsmToken::Plus:
1256 Kind = MCBinaryExpr::Add;
1257 return 4;
1258 case AsmToken::Minus:
1259 Kind = MCBinaryExpr::Sub;
1260 return 4;
1261
1262 // High Intermediate Precedence: |, &, ^
1263 //
1264 // FIXME: gas seems to support '!' as an infix operator?
1265 case AsmToken::Pipe:
1266 Kind = MCBinaryExpr::Or;
1267 return 5;
1268 case AsmToken::Caret:
1269 Kind = MCBinaryExpr::Xor;
1270 return 5;
1271 case AsmToken::Amp:
1272 Kind = MCBinaryExpr::And;
1273 return 5;
1274
1275 // Highest Precedence: *, /, %, <<, >>
1276 case AsmToken::Star:
1277 Kind = MCBinaryExpr::Mul;
1278 return 6;
1279 case AsmToken::Slash:
1280 Kind = MCBinaryExpr::Div;
1281 return 6;
1282 case AsmToken::Percent:
1283 Kind = MCBinaryExpr::Mod;
1284 return 6;
1285 case AsmToken::LessLess:
1286 Kind = MCBinaryExpr::Shl;
1287 return 6;
1288 case AsmToken::GreaterGreater:
1289 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1290 return 6;
1291 }
1292}
1293
1294unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1295 MCBinaryExpr::Opcode &Kind) {
1296 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1297 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1298 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1299}
1300
Jim Grosbach4b905842013-09-20 23:08:21 +00001301/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001302/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001303bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001304 SMLoc &EndLoc) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001305 while (1) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001306 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001307 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001308
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001309 // If the next token is lower precedence than we are allowed to eat, return
1310 // successfully with what we ate already.
1311 if (TokPrec < Precedence)
1312 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001313
Sean Callanan686ed8d2010-01-19 20:22:31 +00001314 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001315
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001316 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001317 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001318 if (parsePrimaryExpr(RHS, EndLoc))
1319 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001320
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001321 // If BinOp binds less tightly with RHS than the operator after RHS, let
1322 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001323 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001324 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001325 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1326 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001327
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001328 // Merge LHS and RHS according to operator.
Jim Grosbach13760bd2015-05-30 01:25:56 +00001329 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001330 }
1331}
1332
Chris Lattner36e02122009-06-21 20:54:55 +00001333/// ParseStatement:
1334/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001335/// ::= Label* Directive ...Operands... EndOfStatement
1336/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001337bool AsmParser::parseStatement(ParseStatementInfo &Info,
1338 MCAsmParserSemaCallback *SI) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001339 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar8271d1bb2010-05-23 18:36:34 +00001340 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001341 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001342 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001343 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001344
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001345 // Statements always start with an identifier or are a full line comment.
Sean Callanan936b0d32010-01-19 21:44:56 +00001346 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001347 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001348 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001349 int64_t LocalLabelVal = -1;
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001350 // A full line comment is a '#' as the first token.
Kevin Enderby72553612011-09-13 23:45:18 +00001351 if (Lexer.is(AsmToken::Hash))
Jim Grosbach4b905842013-09-20 23:08:21 +00001352 return parseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar3f561042011-03-25 17:47:14 +00001353
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001354 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001355 if (Lexer.is(AsmToken::Integer)) {
1356 LocalLabelVal = getTok().getIntVal();
1357 if (LocalLabelVal < 0) {
1358 if (!TheCondState.Ignore)
1359 return TokError("unexpected token at start of statement");
1360 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001361 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001362 IDVal = getTok().getString();
1363 Lex(); // Consume the integer token to be used as an identifier token.
1364 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands41b4a6b2010-07-12 08:16:59 +00001365 if (!TheCondState.Ignore)
1366 return TokError("unexpected token at start of statement");
Kevin Enderby0510b482010-05-17 23:08:19 +00001367 }
1368 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001369 } else if (Lexer.is(AsmToken::Dot)) {
1370 // Treat '.' as a valid identifier in this context.
1371 Lex();
1372 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001373 } else if (Lexer.is(AsmToken::LCurly)) {
1374 // Treat '{' as a valid identifier in this context.
1375 Lex();
1376 IDVal = "{";
1377
1378 } else if (Lexer.is(AsmToken::RCurly)) {
1379 // Treat '}' as a valid identifier in this context.
1380 Lex();
1381 IDVal = "}";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001382 } else if (parseIdentifier(IDVal)) {
Chris Lattner926885c2010-04-17 18:14:27 +00001383 if (!TheCondState.Ignore)
1384 return TokError("unexpected token at start of statement");
1385 IDVal = "";
1386 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001387
Chris Lattner926885c2010-04-17 18:14:27 +00001388 // Handle conditional assembly here before checking for skipping. We
1389 // have to do this so that .endif isn't skipped in a ".if 0" block for
1390 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001391 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001392 DirectiveKindMap.find(IDVal);
1393 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1394 ? DK_NO_DIRECTIVE
1395 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001396 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001397 default:
1398 break;
1399 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001400 case DK_IFEQ:
1401 case DK_IFGE:
1402 case DK_IFGT:
1403 case DK_IFLE:
1404 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001405 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001406 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001407 case DK_IFB:
1408 return parseDirectiveIfb(IDLoc, true);
1409 case DK_IFNB:
1410 return parseDirectiveIfb(IDLoc, false);
1411 case DK_IFC:
1412 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001413 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001414 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001415 case DK_IFNC:
1416 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001417 case DK_IFNES:
1418 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001419 case DK_IFDEF:
1420 return parseDirectiveIfdef(IDLoc, true);
1421 case DK_IFNDEF:
1422 case DK_IFNOTDEF:
1423 return parseDirectiveIfdef(IDLoc, false);
1424 case DK_ELSEIF:
1425 return parseDirectiveElseIf(IDLoc);
1426 case DK_ELSE:
1427 return parseDirectiveElse(IDLoc);
1428 case DK_ENDIF:
1429 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001430 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001431
Eli Bendersky88024712013-01-16 19:32:36 +00001432 // Ignore the statement if in the middle of inactive conditional
1433 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001434 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001435 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001436 return false;
1437 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001438
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001439 // FIXME: Recurse on local labels?
1440
1441 // See what kind of statement we have.
1442 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001443 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001444 if (!getTargetParser().isLabel(ID))
1445 break;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001446 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00001447
Chris Lattner36e02122009-06-21 20:54:55 +00001448 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001449 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001450
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001451 // Diagnose attempt to use '.' as a label.
1452 if (IDVal == ".")
1453 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1454
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001455 // Diagnose attempt to use a variable as a label.
1456 //
1457 // FIXME: Diagnostics. Note the location of the definition as a label.
1458 // FIXME: This doesn't diagnose assignment to a symbol which has been
1459 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001460 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001461 if (LocalLabelVal == -1) {
1462 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001463 StringRef RewrittenLabel =
1464 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1465 assert(RewrittenLabel.size() &&
1466 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001467 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1468 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001469 IDVal = RewrittenLabel;
1470 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001471 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001472 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001473 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
David Majnemer58cb80c2014-12-24 10:27:50 +00001474
1475 Sym->redefineIfPossible();
1476
Daniel Dunbardeb7ba92010-05-05 19:01:00 +00001477 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001478 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencer530ce852010-10-09 11:00:50 +00001479
Daniel Dunbare73b2672009-08-26 22:13:22 +00001480 // Emit the label.
Chad Rosierf3feab32013-01-07 20:34:12 +00001481 if (!ParsingInlineAsm)
1482 Out.EmitLabel(Sym);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001483
Kevin Enderbye7739d42011-12-09 18:09:40 +00001484 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001485 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001486 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001487 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1488 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001489
Tim Northover1744d0a2013-10-25 12:49:50 +00001490 getTargetParser().onLabelParsed(Sym);
1491
Daniel Dunbar8271d1bb2010-05-23 18:36:34 +00001492 // Consume any end of statement token, if present, to avoid spurious
1493 // AddBlankLine calls().
1494 if (Lexer.is(AsmToken::EndOfStatement)) {
1495 Lex();
1496 if (Lexer.is(AsmToken::Eof))
1497 return false;
1498 }
1499
Eli Friedman0f4871d2012-10-22 23:58:19 +00001500 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001501 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001502
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001503 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001504 if (!getTargetParser().equalIsAsmAssignment())
1505 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001506 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001507 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001508
Jim Grosbach4b905842013-09-20 23:08:21 +00001509 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001510
1511 default: // Normal instruction or directive.
1512 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001513 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001514
1515 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001516 if (areMacrosEnabled())
1517 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1518 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001519 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001520
Michael J. Spencer530ce852010-10-09 11:00:50 +00001521 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001522
Eli Bendersky17233942013-01-15 22:59:42 +00001523 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001524 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001525 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001526 //
Eli Bendersky17233942013-01-15 22:59:42 +00001527 // 1. The target-specific assembly parser. Some directives are target
1528 // specific or may potentially behave differently on certain targets.
1529 // 2. Asm parser extensions. For example, platform-specific parsers
1530 // (like the ELF parser) register themselves as extensions.
1531 // 3. The generic directive parser implemented by this class. These are
1532 // all the directives that behave in a target and platform independent
1533 // manner, or at least have a default behavior that's shared between
1534 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001535
Eli Bendersky17233942013-01-15 22:59:42 +00001536 // First query the target-specific parser. It will return 'true' if it
1537 // isn't interested in this directive.
Akira Hatanakad3590752012-07-05 19:09:33 +00001538 if (!getTargetParser().ParseDirective(ID))
1539 return false;
1540
Alp Tokercb402912014-01-24 17:20:08 +00001541 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001542 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001543 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1544 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001545 if (Handler.first)
1546 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1547
1548 // Finally, if no one else is interested in this directive, it must be
1549 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001550 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001551 default:
1552 break;
1553 case DK_SET:
1554 case DK_EQU:
1555 return parseDirectiveSet(IDVal, true);
1556 case DK_EQUIV:
1557 return parseDirectiveSet(IDVal, false);
1558 case DK_ASCII:
1559 return parseDirectiveAscii(IDVal, false);
1560 case DK_ASCIZ:
1561 case DK_STRING:
1562 return parseDirectiveAscii(IDVal, true);
1563 case DK_BYTE:
1564 return parseDirectiveValue(1);
1565 case DK_SHORT:
1566 case DK_VALUE:
1567 case DK_2BYTE:
1568 return parseDirectiveValue(2);
1569 case DK_LONG:
1570 case DK_INT:
1571 case DK_4BYTE:
1572 return parseDirectiveValue(4);
1573 case DK_QUAD:
1574 case DK_8BYTE:
1575 return parseDirectiveValue(8);
David Woodhoused6de0d92014-02-01 16:20:59 +00001576 case DK_OCTA:
1577 return parseDirectiveOctaValue();
Jim Grosbach4b905842013-09-20 23:08:21 +00001578 case DK_SINGLE:
1579 case DK_FLOAT:
1580 return parseDirectiveRealValue(APFloat::IEEEsingle);
1581 case DK_DOUBLE:
1582 return parseDirectiveRealValue(APFloat::IEEEdouble);
1583 case DK_ALIGN: {
1584 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1585 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1586 }
1587 case DK_ALIGN32: {
1588 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1589 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1590 }
1591 case DK_BALIGN:
1592 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1593 case DK_BALIGNW:
1594 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1595 case DK_BALIGNL:
1596 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1597 case DK_P2ALIGN:
1598 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1599 case DK_P2ALIGNW:
1600 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1601 case DK_P2ALIGNL:
1602 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1603 case DK_ORG:
1604 return parseDirectiveOrg();
1605 case DK_FILL:
1606 return parseDirectiveFill();
1607 case DK_ZERO:
1608 return parseDirectiveZero();
1609 case DK_EXTERN:
1610 eatToEndOfStatement(); // .extern is the default, ignore it.
1611 return false;
1612 case DK_GLOBL:
1613 case DK_GLOBAL:
1614 return parseDirectiveSymbolAttribute(MCSA_Global);
1615 case DK_LAZY_REFERENCE:
1616 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1617 case DK_NO_DEAD_STRIP:
1618 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1619 case DK_SYMBOL_RESOLVER:
1620 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1621 case DK_PRIVATE_EXTERN:
1622 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1623 case DK_REFERENCE:
1624 return parseDirectiveSymbolAttribute(MCSA_Reference);
1625 case DK_WEAK_DEFINITION:
1626 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1627 case DK_WEAK_REFERENCE:
1628 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1629 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1630 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1631 case DK_COMM:
1632 case DK_COMMON:
1633 return parseDirectiveComm(/*IsLocal=*/false);
1634 case DK_LCOMM:
1635 return parseDirectiveComm(/*IsLocal=*/true);
1636 case DK_ABORT:
1637 return parseDirectiveAbort();
1638 case DK_INCLUDE:
1639 return parseDirectiveInclude();
1640 case DK_INCBIN:
1641 return parseDirectiveIncbin();
1642 case DK_CODE16:
1643 case DK_CODE16GCC:
1644 return TokError(Twine(IDVal) + " not supported yet");
1645 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001646 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001647 case DK_IRP:
1648 return parseDirectiveIrp(IDLoc);
1649 case DK_IRPC:
1650 return parseDirectiveIrpc(IDLoc);
1651 case DK_ENDR:
1652 return parseDirectiveEndr(IDLoc);
1653 case DK_BUNDLE_ALIGN_MODE:
1654 return parseDirectiveBundleAlignMode();
1655 case DK_BUNDLE_LOCK:
1656 return parseDirectiveBundleLock();
1657 case DK_BUNDLE_UNLOCK:
1658 return parseDirectiveBundleUnlock();
1659 case DK_SLEB128:
1660 return parseDirectiveLEB128(true);
1661 case DK_ULEB128:
1662 return parseDirectiveLEB128(false);
1663 case DK_SPACE:
1664 case DK_SKIP:
1665 return parseDirectiveSpace(IDVal);
1666 case DK_FILE:
1667 return parseDirectiveFile(IDLoc);
1668 case DK_LINE:
1669 return parseDirectiveLine();
1670 case DK_LOC:
1671 return parseDirectiveLoc();
1672 case DK_STABS:
1673 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001674 case DK_CV_FILE:
1675 return parseDirectiveCVFile();
1676 case DK_CV_LOC:
1677 return parseDirectiveCVLoc();
1678 case DK_CV_LINETABLE:
1679 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00001680 case DK_CV_INLINE_LINETABLE:
1681 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00001682 case DK_CV_DEF_RANGE:
1683 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001684 case DK_CV_STRINGTABLE:
1685 return parseDirectiveCVStringTable();
1686 case DK_CV_FILECHECKSUMS:
1687 return parseDirectiveCVFileChecksums();
Jim Grosbach4b905842013-09-20 23:08:21 +00001688 case DK_CFI_SECTIONS:
1689 return parseDirectiveCFISections();
1690 case DK_CFI_STARTPROC:
1691 return parseDirectiveCFIStartProc();
1692 case DK_CFI_ENDPROC:
1693 return parseDirectiveCFIEndProc();
1694 case DK_CFI_DEF_CFA:
1695 return parseDirectiveCFIDefCfa(IDLoc);
1696 case DK_CFI_DEF_CFA_OFFSET:
1697 return parseDirectiveCFIDefCfaOffset();
1698 case DK_CFI_ADJUST_CFA_OFFSET:
1699 return parseDirectiveCFIAdjustCfaOffset();
1700 case DK_CFI_DEF_CFA_REGISTER:
1701 return parseDirectiveCFIDefCfaRegister(IDLoc);
1702 case DK_CFI_OFFSET:
1703 return parseDirectiveCFIOffset(IDLoc);
1704 case DK_CFI_REL_OFFSET:
1705 return parseDirectiveCFIRelOffset(IDLoc);
1706 case DK_CFI_PERSONALITY:
1707 return parseDirectiveCFIPersonalityOrLsda(true);
1708 case DK_CFI_LSDA:
1709 return parseDirectiveCFIPersonalityOrLsda(false);
1710 case DK_CFI_REMEMBER_STATE:
1711 return parseDirectiveCFIRememberState();
1712 case DK_CFI_RESTORE_STATE:
1713 return parseDirectiveCFIRestoreState();
1714 case DK_CFI_SAME_VALUE:
1715 return parseDirectiveCFISameValue(IDLoc);
1716 case DK_CFI_RESTORE:
1717 return parseDirectiveCFIRestore(IDLoc);
1718 case DK_CFI_ESCAPE:
1719 return parseDirectiveCFIEscape();
1720 case DK_CFI_SIGNAL_FRAME:
1721 return parseDirectiveCFISignalFrame();
1722 case DK_CFI_UNDEFINED:
1723 return parseDirectiveCFIUndefined(IDLoc);
1724 case DK_CFI_REGISTER:
1725 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00001726 case DK_CFI_WINDOW_SAVE:
1727 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00001728 case DK_MACROS_ON:
1729 case DK_MACROS_OFF:
1730 return parseDirectiveMacrosOnOff(IDVal);
1731 case DK_MACRO:
1732 return parseDirectiveMacro(IDLoc);
Nico Weber155dccd12014-07-24 17:08:39 +00001733 case DK_EXITM:
1734 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001735 case DK_ENDM:
1736 case DK_ENDMACRO:
1737 return parseDirectiveEndMacro(IDVal);
1738 case DK_PURGEM:
1739 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00001740 case DK_END:
1741 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00001742 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00001743 return parseDirectiveError(IDLoc, false);
1744 case DK_ERROR:
1745 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00001746 case DK_WARNING:
1747 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00001748 case DK_RELOC:
1749 return parseDirectiveReloc(IDLoc);
Eli Friedman20b02642010-07-19 04:17:25 +00001750 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00001751
Jim Grosbach758e0cc2012-05-01 18:38:27 +00001752 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00001753 }
Chris Lattner36e02122009-06-21 20:54:55 +00001754
Chad Rosierc7f552c2013-02-12 21:33:51 +00001755 // __asm _emit or __asm __emit
1756 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1757 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001758 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00001759
1760 // __asm align
1761 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001762 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00001763
Michael Zuckerman02ecd432015-12-13 17:07:23 +00001764 if (ParsingInlineAsm && (IDVal == "even"))
1765 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001766 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00001767
Chris Lattner7cbfa442010-05-19 23:34:33 +00001768 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00001769 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00001770 ParseInstructionInfo IInfo(Info.AsmRewrites);
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001771 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001772 Info.ParsedOperands);
Chad Rosier149e8e02012-12-12 22:45:52 +00001773 Info.ParseError = HadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00001774
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001775 // Dump the parsed representation, if requested.
1776 if (getShowParsedOperands()) {
1777 SmallString<256> Str;
1778 raw_svector_ostream OS(Str);
1779 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001780 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001781 if (i != 0)
1782 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001783 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001784 }
1785 OS << "]";
1786
Jim Grosbach4b905842013-09-20 23:08:21 +00001787 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001788 }
1789
Oliver Stannard8b273082014-06-19 15:52:37 +00001790 // If we are generating dwarf for the current section then generate a .loc
1791 // directive for the instruction.
Kevin Enderby6469fc22011-11-01 22:27:22 +00001792 if (!HadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00001793 getContext().getGenDwarfSectionSyms().count(
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00001794 getStreamer().getCurrentSection().first)) {
1795 unsigned Line;
1796 if (ActiveMacros.empty())
1797 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1798 else
Frederic Riss16238d92015-06-25 21:57:33 +00001799 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
1800 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001801
Eli Bendersky88024712013-01-16 19:32:36 +00001802 // If we previously parsed a cpp hash file line comment then make sure the
1803 // current Dwarf File is for the CppHashFilename if not then emit the
1804 // Dwarf File table for it and adjust the line number for the .loc.
Tim Northoverc0bef992016-04-13 19:46:54 +00001805 if (CppHashInfo.Filename.size()) {
David Blaikiec714ef42014-03-17 01:52:11 +00001806 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00001807 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00001808 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001809
Jim Grosbach4b905842013-09-20 23:08:21 +00001810 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1811 // cache with the different Loc from the call above we save the last
1812 // info we queried here with SrcMgr.FindLineNumber().
1813 unsigned CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00001814 if (LastQueryIDLoc == CppHashInfo.Loc &&
1815 LastQueryBuffer == CppHashInfo.Buf)
Jim Grosbach4b905842013-09-20 23:08:21 +00001816 CppHashLocLineNo = LastQueryLine;
1817 else {
Tim Northoverc0bef992016-04-13 19:46:54 +00001818 CppHashLocLineNo =
1819 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Jim Grosbach4b905842013-09-20 23:08:21 +00001820 LastQueryLine = CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00001821 LastQueryIDLoc = CppHashInfo.Loc;
1822 LastQueryBuffer = CppHashInfo.Buf;
Jim Grosbach4b905842013-09-20 23:08:21 +00001823 }
Tim Northoverc0bef992016-04-13 19:46:54 +00001824 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00001825 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001826
Jim Grosbach4b905842013-09-20 23:08:21 +00001827 getStreamer().EmitDwarfLocDirective(
1828 getContext().getGenDwarfFileNumber(), Line, 0,
1829 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1830 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00001831 }
1832
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00001833 // If parsing succeeded, match the instruction.
Chad Rosier49963552012-10-13 00:26:04 +00001834 if (!HadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00001835 uint64_t ErrorInfo;
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001836 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1837 Info.ParsedOperands, Out,
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00001838 ErrorInfo, ParsingInlineAsm);
Chad Rosier49963552012-10-13 00:26:04 +00001839 }
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001840
Chris Lattnera2a9d162010-09-11 16:18:25 +00001841 // Don't skip the rest of the line, the instruction parser is responsible for
1842 // that.
1843 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00001844}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00001845
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00001846// Parse and erase curly braces marking block start/end
1847bool
1848AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
1849 // Identify curly brace marking block start/end
1850 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
1851 return false;
1852
1853 SMLoc StartLoc = Lexer.getLoc();
1854 Lex(); // Eat the brace
1855 if (Lexer.is(AsmToken::EndOfStatement))
1856 Lex(); // Eat EndOfStatement following the brace
1857
1858 // Erase the block start/end brace from the output asm string
1859 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
1860 StartLoc.getPointer());
1861 return true;
1862}
1863
Jim Grosbach4b905842013-09-20 23:08:21 +00001864/// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
Kevin Enderby72553612011-09-13 23:45:18 +00001865/// since they may not be able to be tokenized to get to the end of line token.
Jim Grosbach4b905842013-09-20 23:08:21 +00001866void AsmParser::eatToEndOfLine() {
Rafael Espindolae0d09082011-10-19 18:48:52 +00001867 if (!Lexer.is(AsmToken::EndOfStatement))
1868 Lexer.LexUntilEndOfLine();
Jim Grosbach4b905842013-09-20 23:08:21 +00001869 // Eat EOL.
1870 Lex();
Kevin Enderby72553612011-09-13 23:45:18 +00001871}
1872
Jim Grosbach4b905842013-09-20 23:08:21 +00001873/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00001874/// ::= # number "filename"
1875/// or just as a full line comment if it doesn't have a number and a string.
Craig Topper3c76c522015-09-20 23:35:59 +00001876bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00001877 Lex(); // Eat the hash token.
1878
1879 if (getLexer().isNot(AsmToken::Integer)) {
1880 // Consume the line since in cases it is not a well-formed line directive,
1881 // as if were simply a full line comment.
Jim Grosbach4b905842013-09-20 23:08:21 +00001882 eatToEndOfLine();
Kevin Enderby72553612011-09-13 23:45:18 +00001883 return false;
1884 }
1885
1886 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00001887 Lex();
1888
1889 if (getLexer().isNot(AsmToken::String)) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001890 eatToEndOfLine();
Kevin Enderby72553612011-09-13 23:45:18 +00001891 return false;
1892 }
1893
1894 StringRef Filename = getTok().getString();
1895 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00001896 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00001897
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001898 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00001899 CppHashInfo.Loc = L;
1900 CppHashInfo.Filename = Filename;
1901 CppHashInfo.LineNumber = LineNumber;
1902 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00001903
1904 // Ignore any trailing characters, they're just comment.
Jim Grosbach4b905842013-09-20 23:08:21 +00001905 eatToEndOfLine();
Kevin Enderby72553612011-09-13 23:45:18 +00001906 return false;
1907}
1908
Jim Grosbach4b905842013-09-20 23:08:21 +00001909/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001910/// for the Filename and LineNo if any in the diagnostic.
1911void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001912 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001913 raw_ostream &OS = errs();
1914
1915 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00001916 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00001917 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1918 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00001919 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001920
Jim Grosbach4b905842013-09-20 23:08:21 +00001921 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001922 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00001923 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1924 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1925 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001926 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1927 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001928 }
1929
Eric Christophera7c32732012-12-18 00:30:54 +00001930 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001931 // manager changed or buffer changed (like in a nested include) then just
1932 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00001933 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001934 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00001935 if (Parser->SavedDiagHandler)
1936 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1937 else
Craig Topper353eda42014-04-24 06:44:33 +00001938 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001939 return;
1940 }
1941
Eric Christophera7c32732012-12-18 00:30:54 +00001942 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00001943 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
1944 // for the diagnostic.
1945 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001946
1947 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1948 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00001949 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00001950 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00001951 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001952
Jim Grosbach4b905842013-09-20 23:08:21 +00001953 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1954 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00001955 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001956
Benjamin Kramer47f5e302011-10-16 10:48:29 +00001957 if (Parser->SavedDiagHandler)
1958 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1959 else
Craig Topper353eda42014-04-24 06:44:33 +00001960 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001961}
1962
Rafael Espindola2c064482012-08-21 18:29:30 +00001963// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1964// difference being that that function accepts '@' as part of identifiers and
1965// we can't do that. AsmLexer.cpp should probably be changed to handle
1966// '@' as a special case when needed.
1967static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001968 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1969 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00001970}
1971
Rafael Espindola34b9c512012-06-03 23:57:14 +00001972bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00001973 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00001974 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00001975 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00001976 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00001977 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00001978 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00001979 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001980
Preston Gurd05500642012-09-19 20:36:12 +00001981 // A macro without parameters is handled differently on Darwin:
1982 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001983 while (!Body.empty()) {
1984 // Scan for the next substitution.
1985 std::size_t End = Body.size(), Pos = 0;
1986 for (; Pos != End; ++Pos) {
1987 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00001988 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00001989 // This macro has no parameters, look for $0, $1, etc.
1990 if (Body[Pos] != '$' || Pos + 1 == End)
1991 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001992
Rafael Espindola1134ab232011-06-05 02:43:45 +00001993 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00001994 if (Next == '$' || Next == 'n' ||
1995 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00001996 break;
1997 } else {
1998 // This macro has parameters, look for \foo, \bar, etc.
1999 if (Body[Pos] == '\\' && Pos + 1 != End)
2000 break;
2001 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002002 }
2003
2004 // Add the prefix.
2005 OS << Body.slice(0, Pos);
2006
2007 // Check if we reached the end.
2008 if (Pos == End)
2009 break;
2010
Benjamin Kramer513e7442014-02-20 13:36:32 +00002011 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002012 switch (Body[Pos + 1]) {
2013 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002014 case '$':
2015 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002016 break;
2017
Jim Grosbach4b905842013-09-20 23:08:21 +00002018 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002019 case 'n':
2020 OS << A.size();
2021 break;
2022
Jim Grosbach4b905842013-09-20 23:08:21 +00002023 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002024 default: {
2025 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002026 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002027 if (Index >= A.size())
2028 break;
2029
2030 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002031 for (const AsmToken &Token : A[Index])
2032 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002033 break;
2034 }
2035 }
2036 Pos += 2;
2037 } else {
2038 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002039
2040 // Check for the \@ pseudo-variable.
2041 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002042 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002043 else
2044 while (isIdentifierChar(Body[I]) && I + 1 != End)
2045 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002046
Jim Grosbach4b905842013-09-20 23:08:21 +00002047 const char *Begin = Body.data() + Pos + 1;
2048 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002049 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002050
Toma Tabacu217116e2015-04-27 10:50:29 +00002051 if (Argument == "@") {
2052 OS << NumOfMacroInstantiations;
2053 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002054 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002055 for (; Index < NParameters; ++Index)
2056 if (Parameters[Index].Name == Argument)
2057 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002058
Toma Tabacu217116e2015-04-27 10:50:29 +00002059 if (Index == NParameters) {
2060 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2061 Pos += 3;
2062 else {
2063 OS << '\\' << Argument;
2064 Pos = I;
2065 }
2066 } else {
2067 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002068 for (const AsmToken &Token : A[Index])
Toma Tabacu217116e2015-04-27 10:50:29 +00002069 // We expect no quotes around the string's contents when
2070 // parsing for varargs.
Craig Topper84008482015-10-10 05:38:14 +00002071 if (Token.getKind() != AsmToken::String || VarargParameter)
2072 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002073 else
Craig Topper84008482015-10-10 05:38:14 +00002074 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002075
2076 Pos += 1 + Argument.size();
2077 }
Preston Gurd05500642012-09-19 20:36:12 +00002078 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002079 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002080 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002081 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002082 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002083
Rafael Espindola1134ab232011-06-05 02:43:45 +00002084 return false;
2085}
Daniel Dunbar43235712010-07-18 18:54:11 +00002086
Nico Weber2a8f9222014-07-24 16:29:04 +00002087MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002088 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002089 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002090 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002091
Jim Grosbach4b905842013-09-20 23:08:21 +00002092static bool isOperator(AsmToken::TokenKind kind) {
2093 switch (kind) {
2094 default:
2095 return false;
2096 case AsmToken::Plus:
2097 case AsmToken::Minus:
2098 case AsmToken::Tilde:
2099 case AsmToken::Slash:
2100 case AsmToken::Star:
2101 case AsmToken::Dot:
2102 case AsmToken::Equal:
2103 case AsmToken::EqualEqual:
2104 case AsmToken::Pipe:
2105 case AsmToken::PipePipe:
2106 case AsmToken::Caret:
2107 case AsmToken::Amp:
2108 case AsmToken::AmpAmp:
2109 case AsmToken::Exclaim:
2110 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002111 case AsmToken::Less:
2112 case AsmToken::LessEqual:
2113 case AsmToken::LessLess:
2114 case AsmToken::LessGreater:
2115 case AsmToken::Greater:
2116 case AsmToken::GreaterEqual:
2117 case AsmToken::GreaterGreater:
2118 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002119 }
2120}
2121
David Majnemer16252452014-01-29 00:07:39 +00002122namespace {
2123class AsmLexerSkipSpaceRAII {
2124public:
2125 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2126 Lexer.setSkipSpace(SkipSpace);
2127 }
2128
2129 ~AsmLexerSkipSpaceRAII() {
2130 Lexer.setSkipSpace(true);
2131 }
2132
2133private:
2134 AsmLexer &Lexer;
2135};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002136}
David Majnemer16252452014-01-29 00:07:39 +00002137
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002138bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2139
2140 if (Vararg) {
2141 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2142 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002143 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002144 }
2145 return false;
2146 }
2147
Rafael Espindola768b41c2012-06-15 14:02:34 +00002148 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002149
David Majnemer16252452014-01-29 00:07:39 +00002150 // Darwin doesn't use spaces to delmit arguments.
2151 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002152
Scott Egertona1fa68a2016-02-11 13:48:49 +00002153 bool SpaceEaten;
2154
Rafael Espindola768b41c2012-06-15 14:02:34 +00002155 for (;;) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002156 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002157 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002158 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002159
Scott Egertona1fa68a2016-02-11 13:48:49 +00002160 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002161
Scott Egertona1fa68a2016-02-11 13:48:49 +00002162 if (Lexer.is(AsmToken::Comma))
2163 break;
2164
2165 if (Lexer.is(AsmToken::Space)) {
2166 SpaceEaten = true;
2167 Lex(); // Eat spaces
2168 }
Preston Gurd05500642012-09-19 20:36:12 +00002169
2170 // Spaces can delimit parameters, but could also be part an expression.
2171 // If the token after a space is an operator, add the token and the next
2172 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002173 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002174 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002175 MA.push_back(getTok());
2176 Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002177
Scott Egertona1fa68a2016-02-11 13:48:49 +00002178 // Whitespace after an operator can be ignored.
2179 if (Lexer.is(AsmToken::Space))
2180 Lex();
2181
2182 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002183 }
2184 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002185 if (SpaceEaten)
2186 break;
Preston Gurd05500642012-09-19 20:36:12 +00002187 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002188
Jim Grosbach4b905842013-09-20 23:08:21 +00002189 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002190 // to be able to fill in the remaining default parameter values
2191 if (Lexer.is(AsmToken::EndOfStatement))
2192 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002193
2194 // Adjust the current parentheses level.
2195 if (Lexer.is(AsmToken::LParen))
2196 ++ParenLevel;
2197 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2198 --ParenLevel;
2199
2200 // Append the token to the current argument list.
2201 MA.push_back(getTok());
2202 Lex();
2203 }
Preston Gurd05500642012-09-19 20:36:12 +00002204
Rafael Espindola768b41c2012-06-15 14:02:34 +00002205 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002206 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002207 return false;
2208}
2209
2210// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002211bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002212 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002213 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002214 bool NamedParametersFound = false;
2215 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002216
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002217 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002218 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002219
Rafael Espindola768b41c2012-06-15 14:02:34 +00002220 // Parse two kinds of macro invocations:
2221 // - macros defined without any parameters accept an arbitrary number of them
2222 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002223 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002224 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2225 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002226 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002227 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002228
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002229 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002230 if (parseIdentifier(FA.Name)) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002231 Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002232 eatToEndOfStatement();
2233 return true;
2234 }
2235
2236 if (!Lexer.is(AsmToken::Equal)) {
2237 TokError("expected '=' after formal parameter identifier");
2238 eatToEndOfStatement();
2239 return true;
2240 }
2241 Lex();
2242
2243 NamedParametersFound = true;
2244 }
2245
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002246 if (NamedParametersFound && FA.Name.empty()) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002247 Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002248 eatToEndOfStatement();
2249 return true;
2250 }
2251
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002252 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2253 if (parseMacroArgument(FA.Value, Vararg))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002254 return true;
2255
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002256 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002257 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002258 unsigned FAI = 0;
2259 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002260 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002261 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002262
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002263 if (FAI >= NParameters) {
Oliver Stannard8b273082014-06-19 15:52:37 +00002264 assert(M && "expected macro to be defined");
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002265 Error(IDLoc,
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002266 "parameter named '" + FA.Name + "' does not exist for macro '" +
Saleem Abdulrasool3f44cd72014-03-17 17:13:57 +00002267 M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002268 return true;
2269 }
2270 PI = FAI;
2271 }
2272
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002273 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002274 if (A.size() <= PI)
2275 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002276 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002277
2278 if (FALocs.size() <= PI)
2279 FALocs.resize(PI + 1);
2280
2281 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002282 }
Jim Grosbach206661622012-07-30 22:44:17 +00002283
Preston Gurd242ed3152012-09-19 20:29:04 +00002284 // At the end of the statement, fill in remaining arguments that have
2285 // default values. If there aren't any, then the next argument is
2286 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002287 if (Lexer.is(AsmToken::EndOfStatement)) {
2288 bool Failure = false;
2289 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2290 if (A[FAI].empty()) {
2291 if (M->Parameters[FAI].Required) {
2292 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2293 "missing value for required parameter "
2294 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2295 Failure = true;
2296 }
2297
2298 if (!M->Parameters[FAI].Value.empty())
2299 A[FAI] = M->Parameters[FAI].Value;
2300 }
2301 }
2302 return Failure;
2303 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002304
2305 if (Lexer.is(AsmToken::Comma))
2306 Lex();
2307 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002308
2309 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002310}
2311
Jim Grosbach4b905842013-09-20 23:08:21 +00002312const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002313 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2314 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002315}
2316
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002317void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2318 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002319}
2320
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002321void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002322
Jim Grosbach4b905842013-09-20 23:08:21 +00002323bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbar43235712010-07-18 18:54:11 +00002324 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2325 // this, although we should protect against infinite loops.
2326 if (ActiveMacros.size() == 20)
2327 return TokError("macros cannot be nested more than 20 levels deep");
2328
Eli Bendersky38274122013-01-14 23:22:36 +00002329 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002330 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002331 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002332
Rafael Espindola1134ab232011-06-05 02:43:45 +00002333 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2334 // to hold the macro body with substitutions.
2335 SmallString<256> Buf;
2336 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002337 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002338
Toma Tabacu217116e2015-04-27 10:50:29 +00002339 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002340 return true;
2341
Eli Bendersky38274122013-01-14 23:22:36 +00002342 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002343 // instantiation.
2344 OS << ".endmacro\n";
2345
Rafael Espindola3560ff22014-08-27 20:03:13 +00002346 std::unique_ptr<MemoryBuffer> Instantiation =
2347 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002348
Daniel Dunbar43235712010-07-18 18:54:11 +00002349 // Create the macro instantiation object and add to the current macro
2350 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002351 MacroInstantiation *MI = new MacroInstantiation(
2352 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002353 ActiveMacros.push_back(MI);
2354
Toma Tabacu217116e2015-04-27 10:50:29 +00002355 ++NumOfMacroInstantiations;
2356
Daniel Dunbar43235712010-07-18 18:54:11 +00002357 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002358 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002359 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002360 Lex();
2361
2362 return false;
2363}
2364
Jim Grosbach4b905842013-09-20 23:08:21 +00002365void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002366 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002367 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002368 Lex();
2369
2370 // Pop the instantiation entry.
2371 delete ActiveMacros.back();
2372 ActiveMacros.pop_back();
2373}
2374
Jim Grosbach4b905842013-09-20 23:08:21 +00002375bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002376 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002377 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002378 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002379 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2380 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002381 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002382
Pete Cooper80d21cb2015-06-22 19:35:57 +00002383 if (!Sym) {
2384 // In the case where we parse an expression starting with a '.', we will
2385 // not generate an error, nor will we create a symbol. In this case we
2386 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002387 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002388 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002389
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002390 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002391 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002392 if (NoDeadStrip)
2393 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2394
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002395 return false;
2396}
2397
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002398/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002399/// ::= identifier
2400/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002401bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002402 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002403 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2404 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002405 // handle this as a context dependent token, instead we detect adjacent tokens
2406 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002407 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2408 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002409
Hans Wennborgce69d772013-10-18 20:46:28 +00002410 // Consume the prefix character, and check for a following identifier.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002411 Lex();
2412 if (Lexer.isNot(AsmToken::Identifier))
2413 return true;
2414
Hans Wennborgce69d772013-10-18 20:46:28 +00002415 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2416 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002417 return true;
2418
2419 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002420 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002421 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002422 Lex();
2423 return false;
2424 }
2425
Jim Grosbach4b905842013-09-20 23:08:21 +00002426 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002427 return true;
2428
Sean Callanan936b0d32010-01-19 21:44:56 +00002429 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002430
Sean Callanan686ed8d2010-01-19 20:22:31 +00002431 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002432
2433 return false;
2434}
2435
Jim Grosbach4b905842013-09-20 23:08:21 +00002436/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002437/// ::= .equ identifier ',' expression
2438/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002439/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002440bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002441 StringRef Name;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002442
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002443 if (parseIdentifier(Name))
Roman Divacky41e6ceb2010-10-28 16:57:58 +00002444 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencer530ce852010-10-09 11:00:50 +00002445
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002446 if (getLexer().isNot(AsmToken::Comma))
Roman Divacky41e6ceb2010-10-28 16:57:58 +00002447 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002448 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002449
Jim Grosbach4b905842013-09-20 23:08:21 +00002450 return parseAssignment(Name, allow_redef, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002451}
2452
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002453bool AsmParser::parseEscapedString(std::string &Data) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002454 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbaref668c12009-08-14 18:19:52 +00002455
2456 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002457 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002458 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2459 if (Str[i] != '\\') {
2460 Data += Str[i];
2461 continue;
2462 }
2463
2464 // Recognize escaped characters. Note that this escape semantics currently
2465 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2466 ++i;
2467 if (i == e)
2468 return TokError("unexpected backslash at end of string");
2469
2470 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002471 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002472 // Consume up to three octal characters.
2473 unsigned Value = Str[i] - '0';
2474
Jim Grosbach4b905842013-09-20 23:08:21 +00002475 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002476 ++i;
2477 Value = Value * 8 + (Str[i] - '0');
2478
Jim Grosbach4b905842013-09-20 23:08:21 +00002479 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002480 ++i;
2481 Value = Value * 8 + (Str[i] - '0');
2482 }
2483 }
2484
2485 if (Value > 255)
2486 return TokError("invalid octal escape sequence (out of range)");
2487
Jim Grosbach4b905842013-09-20 23:08:21 +00002488 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002489 continue;
2490 }
2491
2492 // Otherwise recognize individual escapes.
2493 switch (Str[i]) {
2494 default:
2495 // Just reject invalid escape sequences for now.
2496 return TokError("invalid escape sequence (unrecognized character)");
2497
2498 case 'b': Data += '\b'; break;
2499 case 'f': Data += '\f'; break;
2500 case 'n': Data += '\n'; break;
2501 case 'r': Data += '\r'; break;
2502 case 't': Data += '\t'; break;
2503 case '"': Data += '"'; break;
2504 case '\\': Data += '\\'; break;
2505 }
2506 }
2507
2508 return false;
2509}
2510
Jim Grosbach4b905842013-09-20 23:08:21 +00002511/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002512/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002513bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002514 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002515 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002516
Daniel Dunbara10e5192009-06-24 23:30:00 +00002517 for (;;) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002518 if (getLexer().isNot(AsmToken::String))
Rafael Espindola63760ba2010-10-28 20:02:27 +00002519 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002520
Daniel Dunbaref668c12009-08-14 18:19:52 +00002521 std::string Data;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002522 if (parseEscapedString(Data))
Daniel Dunbaref668c12009-08-14 18:19:52 +00002523 return true;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002524
Rafael Espindola64e1af82013-07-02 15:49:13 +00002525 getStreamer().EmitBytes(Data);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002526 if (ZeroTerminated)
Rafael Espindola64e1af82013-07-02 15:49:13 +00002527 getStreamer().EmitBytes(StringRef("\0", 1));
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002528
Sean Callanan686ed8d2010-01-19 20:22:31 +00002529 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002530
2531 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002532 break;
2533
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002534 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola63760ba2010-10-28 20:02:27 +00002535 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002536 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002537 }
2538 }
2539
Sean Callanan686ed8d2010-01-19 20:22:31 +00002540 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002541 return false;
2542}
2543
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002544/// parseDirectiveReloc
2545/// ::= .reloc expression , identifier [ , expression ]
2546bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2547 const MCExpr *Offset;
2548 const MCExpr *Expr = nullptr;
2549
2550 SMLoc OffsetLoc = Lexer.getTok().getLoc();
2551 if (parseExpression(Offset))
2552 return true;
2553
2554 // We can only deal with constant expressions at the moment.
2555 int64_t OffsetValue;
2556 if (!Offset->evaluateAsAbsolute(OffsetValue))
2557 return Error(OffsetLoc, "expression is not a constant value");
2558
David Majnemerce108422016-01-19 23:05:27 +00002559 if (OffsetValue < 0)
2560 return Error(OffsetLoc, "expression is negative");
2561
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002562 if (Lexer.isNot(AsmToken::Comma))
2563 return TokError("expected comma");
2564 Lexer.Lex();
2565
2566 if (Lexer.isNot(AsmToken::Identifier))
2567 return TokError("expected relocation name");
2568 SMLoc NameLoc = Lexer.getTok().getLoc();
2569 StringRef Name = Lexer.getTok().getIdentifier();
2570 Lexer.Lex();
2571
2572 if (Lexer.is(AsmToken::Comma)) {
2573 Lexer.Lex();
2574 SMLoc ExprLoc = Lexer.getLoc();
2575 if (parseExpression(Expr))
2576 return true;
2577
2578 MCValue Value;
2579 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2580 return Error(ExprLoc, "expression must be relocatable");
2581 }
2582
2583 if (Lexer.isNot(AsmToken::EndOfStatement))
2584 return TokError("unexpected token in .reloc directive");
2585
2586 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2587 return Error(NameLoc, "unknown relocation name");
2588
2589 return false;
2590}
2591
Jim Grosbach4b905842013-09-20 23:08:21 +00002592/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002593/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002594bool AsmParser::parseDirectiveValue(unsigned Size) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002595 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002596 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002597
Daniel Dunbara10e5192009-06-24 23:30:00 +00002598 for (;;) {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002599 const MCExpr *Value;
Jim Grosbach76346c32011-06-29 16:05:14 +00002600 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002601 if (parseExpression(Value))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002602 return true;
2603
Daniel Dunbar6738a2e2010-05-23 18:36:38 +00002604 // Special case constant expressions to match code generator.
Jim Grosbach76346c32011-06-29 16:05:14 +00002605 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2606 assert(Size <= 8 && "Invalid size");
2607 uint64_t IntValue = MCE->getValue();
2608 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2609 return Error(ExprLoc, "literal value out of range for directive");
Rafael Espindola64e1af82013-07-02 15:49:13 +00002610 getStreamer().EmitIntValue(IntValue, Size);
Jim Grosbach76346c32011-06-29 16:05:14 +00002611 } else
Kevin Enderby96918bc2014-04-22 17:27:29 +00002612 getStreamer().EmitValue(Value, Size, ExprLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002613
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002614 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002615 break;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002616
Daniel Dunbara10e5192009-06-24 23:30:00 +00002617 // FIXME: Improve diagnostic.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002618 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002619 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002620 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002621 }
2622 }
2623
Sean Callanan686ed8d2010-01-19 20:22:31 +00002624 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002625 return false;
2626}
2627
David Woodhoused6de0d92014-02-01 16:20:59 +00002628/// ParseDirectiveOctaValue
2629/// ::= .octa [ hexconstant (, hexconstant)* ]
2630bool AsmParser::parseDirectiveOctaValue() {
2631 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2632 checkForValidSection();
2633
2634 for (;;) {
2635 if (Lexer.getKind() == AsmToken::Error)
2636 return true;
2637 if (Lexer.getKind() != AsmToken::Integer &&
2638 Lexer.getKind() != AsmToken::BigNum)
2639 return TokError("unknown token in expression");
2640
2641 SMLoc ExprLoc = getLexer().getLoc();
2642 APInt IntValue = getTok().getAPIntVal();
2643 Lex();
2644
2645 uint64_t hi, lo;
2646 if (IntValue.isIntN(64)) {
2647 hi = 0;
2648 lo = IntValue.getZExtValue();
2649 } else if (IntValue.isIntN(128)) {
David Woodhouse6c9a6f92014-02-01 16:52:33 +00002650 // It might actually have more than 128 bits, but the top ones are zero.
2651 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002652 lo = IntValue.getLoBits(64).getZExtValue();
2653 } else
2654 return Error(ExprLoc, "literal value out of range for directive");
2655
2656 if (MAI.isLittleEndian()) {
2657 getStreamer().EmitIntValue(lo, 8);
2658 getStreamer().EmitIntValue(hi, 8);
2659 } else {
2660 getStreamer().EmitIntValue(hi, 8);
2661 getStreamer().EmitIntValue(lo, 8);
2662 }
2663
2664 if (getLexer().is(AsmToken::EndOfStatement))
2665 break;
2666
2667 // FIXME: Improve diagnostic.
2668 if (getLexer().isNot(AsmToken::Comma))
2669 return TokError("unexpected token in directive");
2670 Lex();
2671 }
2672 }
2673
2674 Lex();
2675 return false;
2676}
2677
Jim Grosbach4b905842013-09-20 23:08:21 +00002678/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00002679/// ::= (.single | .double) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002680bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
Daniel Dunbar2af16532010-09-24 01:59:56 +00002681 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002682 checkForValidSection();
Daniel Dunbar2af16532010-09-24 01:59:56 +00002683
2684 for (;;) {
2685 // We don't truly support arithmetic on floating point expressions, so we
2686 // have to manually parse unary prefixes.
2687 bool IsNeg = false;
2688 if (getLexer().is(AsmToken::Minus)) {
2689 Lex();
2690 IsNeg = true;
2691 } else if (getLexer().is(AsmToken::Plus))
2692 Lex();
2693
Michael J. Spencer530ce852010-10-09 11:00:50 +00002694 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby5bbe9572011-03-29 21:11:52 +00002695 getLexer().isNot(AsmToken::Real) &&
2696 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbar2af16532010-09-24 01:59:56 +00002697 return TokError("unexpected token in directive");
2698
2699 // Convert to an APFloat.
2700 APFloat Value(Semantics);
Kevin Enderby5bbe9572011-03-29 21:11:52 +00002701 StringRef IDVal = getTok().getString();
2702 if (getLexer().is(AsmToken::Identifier)) {
2703 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2704 Value = APFloat::getInf(Semantics);
2705 else if (!IDVal.compare_lower("nan"))
2706 Value = APFloat::getNaN(Semantics, false, ~0);
2707 else
2708 return TokError("invalid floating point literal");
2709 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Jim Grosbach4b905842013-09-20 23:08:21 +00002710 APFloat::opInvalidOp)
Daniel Dunbar2af16532010-09-24 01:59:56 +00002711 return TokError("invalid floating point literal");
2712 if (IsNeg)
2713 Value.changeSign();
2714
2715 // Consume the numeric token.
2716 Lex();
2717
2718 // Emit the value as an integer.
2719 APInt AsInt = Value.bitcastToAPInt();
2720 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
Rafael Espindola64e1af82013-07-02 15:49:13 +00002721 AsInt.getBitWidth() / 8);
Daniel Dunbar2af16532010-09-24 01:59:56 +00002722
2723 if (getLexer().is(AsmToken::EndOfStatement))
2724 break;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002725
Daniel Dunbar2af16532010-09-24 01:59:56 +00002726 if (getLexer().isNot(AsmToken::Comma))
2727 return TokError("unexpected token in directive");
2728 Lex();
2729 }
2730 }
2731
2732 Lex();
2733 return false;
2734}
2735
Jim Grosbach4b905842013-09-20 23:08:21 +00002736/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00002737/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002738bool AsmParser::parseDirectiveZero() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002739 checkForValidSection();
Rafael Espindola922e3f42010-09-16 15:03:59 +00002740
Petr Hosek67a94a72016-05-28 05:57:48 +00002741 SMLoc NumBytesLoc = Lexer.getLoc();
2742 const MCExpr *NumBytes;
2743 if (parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00002744 return true;
2745
Rafael Espindolab91bac62010-10-05 19:42:57 +00002746 int64_t Val = 0;
2747 if (getLexer().is(AsmToken::Comma)) {
2748 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002749 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00002750 return true;
2751 }
2752
Rafael Espindola922e3f42010-09-16 15:03:59 +00002753 if (getLexer().isNot(AsmToken::EndOfStatement))
2754 return TokError("unexpected token in '.zero' directive");
2755
2756 Lex();
2757
Petr Hosek67a94a72016-05-28 05:57:48 +00002758 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00002759
2760 return false;
2761}
2762
Jim Grosbach4b905842013-09-20 23:08:21 +00002763/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00002764/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002765bool AsmParser::parseDirectiveFill() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002766 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002767
Petr Hosek67a94a72016-05-28 05:57:48 +00002768 SMLoc NumValuesLoc = Lexer.getLoc();
2769 const MCExpr *NumValues;
2770 if (parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002771 return true;
2772
Roman Divackye33098f2013-09-24 17:44:41 +00002773 int64_t FillSize = 1;
2774 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002775
David Majnemer522d3db2014-02-01 07:19:38 +00002776 SMLoc SizeLoc, ExprLoc;
Roman Divackye33098f2013-09-24 17:44:41 +00002777 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2778 if (getLexer().isNot(AsmToken::Comma))
2779 return TokError("unexpected token in '.fill' directive");
2780 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002781
David Majnemer522d3db2014-02-01 07:19:38 +00002782 SizeLoc = getLexer().getLoc();
Roman Divackye33098f2013-09-24 17:44:41 +00002783 if (parseAbsoluteExpression(FillSize))
2784 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002785
Roman Divackye33098f2013-09-24 17:44:41 +00002786 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2787 if (getLexer().isNot(AsmToken::Comma))
2788 return TokError("unexpected token in '.fill' directive");
2789 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002790
David Majnemer522d3db2014-02-01 07:19:38 +00002791 ExprLoc = getLexer().getLoc();
Roman Divackye33098f2013-09-24 17:44:41 +00002792 if (parseAbsoluteExpression(FillExpr))
2793 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002794
Roman Divackye33098f2013-09-24 17:44:41 +00002795 if (getLexer().isNot(AsmToken::EndOfStatement))
2796 return TokError("unexpected token in '.fill' directive");
2797
2798 Lex();
2799 }
2800 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002801
David Majnemer522d3db2014-02-01 07:19:38 +00002802 if (FillSize < 0) {
2803 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00002804 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00002805 }
2806 if (FillSize > 8) {
2807 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2808 FillSize = 8;
2809 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002810
David Majnemer522d3db2014-02-01 07:19:38 +00002811 if (!isUInt<32>(FillExpr) && FillSize > 4)
2812 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2813
Petr Hosek67a94a72016-05-28 05:57:48 +00002814 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002815
2816 return false;
2817}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002818
Jim Grosbach4b905842013-09-20 23:08:21 +00002819/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002820/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002821bool AsmParser::parseDirectiveOrg() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002822 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002823
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002824 const MCExpr *Offset;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002825 if (parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002826 return true;
2827
2828 // Parse optional fill expression.
2829 int64_t FillExpr = 0;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002830 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2831 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002832 return TokError("unexpected token in '.org' directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002833 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00002834
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002835 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002836 return true;
2837
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002838 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002839 return TokError("unexpected token in '.org' directive");
2840 }
2841
Sean Callanan686ed8d2010-01-19 20:22:31 +00002842 Lex();
Rafael Espindola7ae65d82015-11-04 23:59:18 +00002843 getStreamer().emitValueToOffset(Offset, FillExpr);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002844 return false;
2845}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002846
Jim Grosbach4b905842013-09-20 23:08:21 +00002847/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002848/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00002849bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002850 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002851
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002852 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002853 int64_t Alignment;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002854 if (parseAbsoluteExpression(Alignment))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002855 return true;
2856
2857 SMLoc MaxBytesLoc;
2858 bool HasFillExpr = false;
2859 int64_t FillExpr = 0;
2860 int64_t MaxBytesToFill = 0;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002861 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2862 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002863 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002864 Lex();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002865
2866 // The fill expression can be omitted while specifying a maximum number of
2867 // alignment bytes, e.g:
2868 // .align 3,,4
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002869 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002870 HasFillExpr = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002871 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002872 return true;
2873 }
2874
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002875 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2876 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002877 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002878 Lex();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002879
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002880 MaxBytesLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002881 if (parseAbsoluteExpression(MaxBytesToFill))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002882 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002883
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002884 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002885 return TokError("unexpected token in directive");
2886 }
2887 }
2888
Sean Callanan686ed8d2010-01-19 20:22:31 +00002889 Lex();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002890
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002891 if (!HasFillExpr)
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002892 FillExpr = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002893
2894 // Compute alignment in bytes.
2895 if (IsPow2) {
2896 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002897 if (Alignment >= 32) {
2898 Error(AlignmentLoc, "invalid alignment value");
2899 Alignment = 31;
2900 }
2901
Benjamin Kramer63951ad2009-09-06 09:35:10 +00002902 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00002903 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00002904 // Reject alignments that aren't either a power of two or zero,
2905 // for gas compatibility. Alignment of zero is silently rounded
2906 // up to one.
2907 if (Alignment == 0)
2908 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00002909 if (!isPowerOf2_64(Alignment))
2910 Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002911 }
2912
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002913 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002914 if (MaxBytesLoc.isValid()) {
2915 if (MaxBytesToFill < 1) {
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002916 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00002917 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00002918 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002919 }
2920
2921 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00002922 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00002923 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002924 MaxBytesToFill = 0;
2925 }
2926 }
2927
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002928 // Check whether we should use optimal code alignment for this .align
2929 // directive.
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00002930 const MCSection *Section = getStreamer().getCurrentSection().first;
2931 assert(Section && "must have section to emit alignment");
2932 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002933 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2934 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002935 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002936 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00002937 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00002938 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2939 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002940 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002941
2942 return false;
2943}
2944
Jim Grosbach4b905842013-09-20 23:08:21 +00002945/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00002946/// ::= .file [number] filename
2947/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00002948bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00002949 // FIXME: I'm not sure what this is.
2950 int64_t FileNumber = -1;
2951 SMLoc FileNumberLoc = getLexer().getLoc();
2952 if (getLexer().is(AsmToken::Integer)) {
2953 FileNumber = getTok().getIntVal();
2954 Lex();
2955
2956 if (FileNumber < 1)
2957 return TokError("file number less than one");
2958 }
2959
2960 if (getLexer().isNot(AsmToken::String))
2961 return TokError("unexpected token in '.file' directive");
2962
2963 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002964 // Allow the strings to have escaped octal character sequence.
2965 std::string Path = getTok().getString();
2966 if (parseEscapedString(Path))
2967 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00002968 Lex();
2969
2970 StringRef Directory;
2971 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002972 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00002973 if (getLexer().is(AsmToken::String)) {
2974 if (FileNumber == -1)
2975 return TokError("explicit path specified, but no file number");
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002976 if (parseEscapedString(FilenameData))
2977 return true;
2978 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00002979 Directory = Path;
2980 Lex();
2981 } else {
2982 Filename = Path;
2983 }
2984
2985 if (getLexer().isNot(AsmToken::EndOfStatement))
2986 return TokError("unexpected token in '.file' directive");
2987
2988 if (FileNumber == -1)
2989 getStreamer().EmitFileDirective(Filename);
2990 else {
David Blaikie22748082016-05-26 00:22:26 +00002991 // If there is -g option as well as debug info from directive file,
2992 // we turn off -g option, directly use the existing debug info instead.
David Blaikiedc3f01e2015-03-09 01:57:13 +00002993 if (getContext().getGenDwarfForAssembly())
David Blaikie22748082016-05-26 00:22:26 +00002994 getContext().setGenDwarfForAssembly(false);
2995 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
David Blaikiec714ef42014-03-17 01:52:11 +00002996 0)
Eli Bendersky17233942013-01-15 22:59:42 +00002997 Error(FileNumberLoc, "file number already allocated");
2998 }
2999
3000 return false;
3001}
3002
Jim Grosbach4b905842013-09-20 23:08:21 +00003003/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003004/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003005bool AsmParser::parseDirectiveLine() {
Eli Bendersky17233942013-01-15 22:59:42 +00003006 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3007 if (getLexer().isNot(AsmToken::Integer))
3008 return TokError("unexpected token in '.line' directive");
3009
3010 int64_t LineNumber = getTok().getIntVal();
Jim Grosbach4b905842013-09-20 23:08:21 +00003011 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003012 Lex();
3013
3014 // FIXME: Do something with the .line.
3015 }
3016
3017 if (getLexer().isNot(AsmToken::EndOfStatement))
3018 return TokError("unexpected token in '.line' directive");
3019
3020 return false;
3021}
3022
Jim Grosbach4b905842013-09-20 23:08:21 +00003023/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003024/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3025/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3026/// The first number is a file number, must have been previously assigned with
3027/// a .file directive, the second number is the line number and optionally the
3028/// third number is a column position (zero if not specified). The remaining
3029/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003030bool AsmParser::parseDirectiveLoc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003031 if (getLexer().isNot(AsmToken::Integer))
3032 return TokError("unexpected token in '.loc' directive");
3033 int64_t FileNumber = getTok().getIntVal();
3034 if (FileNumber < 1)
3035 return TokError("file number less than one in '.loc' directive");
3036 if (!getContext().isValidDwarfFileNumber(FileNumber))
3037 return TokError("unassigned file number in '.loc' directive");
3038 Lex();
3039
3040 int64_t LineNumber = 0;
3041 if (getLexer().is(AsmToken::Integer)) {
3042 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003043 if (LineNumber < 0)
3044 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003045 Lex();
3046 }
3047
3048 int64_t ColumnPos = 0;
3049 if (getLexer().is(AsmToken::Integer)) {
3050 ColumnPos = getTok().getIntVal();
3051 if (ColumnPos < 0)
3052 return TokError("column position less than zero in '.loc' directive");
3053 Lex();
3054 }
3055
3056 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3057 unsigned Isa = 0;
3058 int64_t Discriminator = 0;
3059 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3060 for (;;) {
3061 if (getLexer().is(AsmToken::EndOfStatement))
3062 break;
3063
3064 StringRef Name;
3065 SMLoc Loc = getTok().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003066 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003067 return TokError("unexpected token in '.loc' directive");
3068
3069 if (Name == "basic_block")
3070 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3071 else if (Name == "prologue_end")
3072 Flags |= DWARF2_FLAG_PROLOGUE_END;
3073 else if (Name == "epilogue_begin")
3074 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3075 else if (Name == "is_stmt") {
3076 Loc = getTok().getLoc();
3077 const MCExpr *Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003078 if (parseExpression(Value))
Eli Bendersky17233942013-01-15 22:59:42 +00003079 return true;
3080 // The expression must be the constant 0 or 1.
3081 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3082 int Value = MCE->getValue();
3083 if (Value == 0)
3084 Flags &= ~DWARF2_FLAG_IS_STMT;
3085 else if (Value == 1)
3086 Flags |= DWARF2_FLAG_IS_STMT;
3087 else
3088 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003089 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003090 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3091 }
Craig Topperf15655b2013-04-22 04:22:40 +00003092 } else if (Name == "isa") {
Eli Bendersky17233942013-01-15 22:59:42 +00003093 Loc = getTok().getLoc();
3094 const MCExpr *Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003095 if (parseExpression(Value))
Eli Bendersky17233942013-01-15 22:59:42 +00003096 return true;
3097 // The expression must be a constant greater or equal to 0.
3098 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3099 int Value = MCE->getValue();
3100 if (Value < 0)
3101 return Error(Loc, "isa number less than zero");
3102 Isa = Value;
Craig Topperf15655b2013-04-22 04:22:40 +00003103 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003104 return Error(Loc, "isa number not a constant value");
3105 }
Craig Topperf15655b2013-04-22 04:22:40 +00003106 } else if (Name == "discriminator") {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003107 if (parseAbsoluteExpression(Discriminator))
Eli Bendersky17233942013-01-15 22:59:42 +00003108 return true;
Craig Topperf15655b2013-04-22 04:22:40 +00003109 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003110 return Error(Loc, "unknown sub-directive in '.loc' directive");
3111 }
3112
3113 if (getLexer().is(AsmToken::EndOfStatement))
3114 break;
3115 }
3116 }
3117
3118 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3119 Isa, Discriminator, StringRef());
3120
3121 return false;
3122}
3123
Jim Grosbach4b905842013-09-20 23:08:21 +00003124/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003125/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003126bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003127 return TokError("unsupported directive '.stabs'");
3128}
3129
Reid Kleckner2214ed82016-01-29 00:49:42 +00003130/// parseDirectiveCVFile
3131/// ::= .cv_file number filename
3132bool AsmParser::parseDirectiveCVFile() {
3133 SMLoc FileNumberLoc = getLexer().getLoc();
3134 if (getLexer().isNot(AsmToken::Integer))
3135 return TokError("expected file number in '.cv_file' directive");
3136
3137 int64_t FileNumber = getTok().getIntVal();
3138 Lex();
3139
3140 if (FileNumber < 1)
3141 return TokError("file number less than one");
3142
3143 if (getLexer().isNot(AsmToken::String))
3144 return TokError("unexpected token in '.cv_file' directive");
3145
3146 // Usually the directory and filename together, otherwise just the directory.
3147 // Allow the strings to have escaped octal character sequence.
3148 std::string Filename;
3149 if (parseEscapedString(Filename))
3150 return true;
3151 Lex();
3152
3153 if (getLexer().isNot(AsmToken::EndOfStatement))
3154 return TokError("unexpected token in '.cv_file' directive");
3155
3156 if (getStreamer().EmitCVFileDirective(FileNumber, Filename) == 0)
3157 Error(FileNumberLoc, "file number already allocated");
3158
3159 return false;
3160}
3161
3162/// parseDirectiveCVLoc
3163/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3164/// [is_stmt VALUE]
3165/// The first number is a file number, must have been previously assigned with
3166/// a .file directive, the second number is the line number and optionally the
3167/// third number is a column position (zero if not specified). The remaining
3168/// optional items are .loc sub-directives.
3169bool AsmParser::parseDirectiveCVLoc() {
3170 if (getLexer().isNot(AsmToken::Integer))
3171 return TokError("unexpected token in '.cv_loc' directive");
3172
3173 int64_t FunctionId = getTok().getIntVal();
3174 if (FunctionId < 0)
3175 return TokError("function id less than zero in '.cv_loc' directive");
3176 Lex();
3177
3178 int64_t FileNumber = getTok().getIntVal();
3179 if (FileNumber < 1)
3180 return TokError("file number less than one in '.cv_loc' directive");
3181 if (!getContext().isValidCVFileNumber(FileNumber))
3182 return TokError("unassigned file number in '.cv_loc' directive");
3183 Lex();
3184
3185 int64_t LineNumber = 0;
3186 if (getLexer().is(AsmToken::Integer)) {
3187 LineNumber = getTok().getIntVal();
3188 if (LineNumber < 0)
3189 return TokError("line number less than zero in '.cv_loc' directive");
3190 Lex();
3191 }
3192
3193 int64_t ColumnPos = 0;
3194 if (getLexer().is(AsmToken::Integer)) {
3195 ColumnPos = getTok().getIntVal();
3196 if (ColumnPos < 0)
3197 return TokError("column position less than zero in '.cv_loc' directive");
3198 Lex();
3199 }
3200
3201 bool PrologueEnd = false;
3202 uint64_t IsStmt = 0;
3203 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3204 StringRef Name;
3205 SMLoc Loc = getTok().getLoc();
3206 if (parseIdentifier(Name))
3207 return TokError("unexpected token in '.cv_loc' directive");
3208
3209 if (Name == "prologue_end")
3210 PrologueEnd = true;
3211 else if (Name == "is_stmt") {
3212 Loc = getTok().getLoc();
3213 const MCExpr *Value;
3214 if (parseExpression(Value))
3215 return true;
3216 // The expression must be the constant 0 or 1.
3217 IsStmt = ~0ULL;
3218 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3219 IsStmt = MCE->getValue();
3220
3221 if (IsStmt > 1)
3222 return Error(Loc, "is_stmt value not 0 or 1");
3223 } else {
3224 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3225 }
3226 }
3227
3228 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
3229 ColumnPos, PrologueEnd, IsStmt, StringRef());
3230 return false;
3231}
3232
3233/// parseDirectiveCVLinetable
3234/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3235bool AsmParser::parseDirectiveCVLinetable() {
3236 int64_t FunctionId = getTok().getIntVal();
3237 if (FunctionId < 0)
3238 return TokError("function id less than zero in '.cv_linetable' directive");
3239 Lex();
3240
3241 if (Lexer.isNot(AsmToken::Comma))
3242 return TokError("unexpected token in '.cv_linetable' directive");
3243 Lex();
3244
3245 SMLoc Loc = getLexer().getLoc();
3246 StringRef FnStartName;
3247 if (parseIdentifier(FnStartName))
3248 return Error(Loc, "expected identifier in directive");
3249
3250 if (Lexer.isNot(AsmToken::Comma))
3251 return TokError("unexpected token in '.cv_linetable' directive");
3252 Lex();
3253
3254 Loc = getLexer().getLoc();
3255 StringRef FnEndName;
3256 if (parseIdentifier(FnEndName))
3257 return Error(Loc, "expected identifier in directive");
3258
3259 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3260 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3261
3262 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3263 return false;
3264}
3265
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003266/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003267/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003268/// ("contains" SecondaryFunctionId+)?
3269bool AsmParser::parseDirectiveCVInlineLinetable() {
3270 int64_t PrimaryFunctionId = getTok().getIntVal();
3271 if (PrimaryFunctionId < 0)
3272 return TokError(
3273 "function id less than zero in '.cv_inline_linetable' directive");
3274 Lex();
3275
3276 int64_t SourceFileId = getTok().getIntVal();
3277 if (SourceFileId <= 0)
3278 return TokError(
3279 "File id less than zero in '.cv_inline_linetable' directive");
3280 Lex();
3281
3282 int64_t SourceLineNum = getTok().getIntVal();
3283 if (SourceLineNum < 0)
3284 return TokError(
3285 "Line number less than zero in '.cv_inline_linetable' directive");
3286 Lex();
3287
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003288 SMLoc Loc = getLexer().getLoc();
3289 StringRef FnStartName;
3290 if (parseIdentifier(FnStartName))
3291 return Error(Loc, "expected identifier in directive");
3292 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3293
David Majnemerc9911f22016-02-02 19:22:34 +00003294 Loc = getLexer().getLoc();
3295 StringRef FnEndName;
3296 if (parseIdentifier(FnEndName))
3297 return Error(Loc, "expected identifier in directive");
3298 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3299
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003300 SmallVector<unsigned, 8> SecondaryFunctionIds;
3301 if (getLexer().is(AsmToken::Identifier)) {
3302 if (getTok().getIdentifier() != "contains")
3303 return TokError(
3304 "unexpected identifier in '.cv_inline_linetable' directive");
3305 Lex();
3306
3307 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3308 int64_t SecondaryFunctionId = getTok().getIntVal();
3309 if (SecondaryFunctionId < 0)
3310 return TokError(
3311 "function id less than zero in '.cv_inline_linetable' directive");
3312 Lex();
3313
3314 SecondaryFunctionIds.push_back(SecondaryFunctionId);
3315 }
3316 }
3317
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003318 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3319 SourceLineNum, FnStartSym,
David Majnemerc9911f22016-02-02 19:22:34 +00003320 FnEndSym, SecondaryFunctionIds);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003321 return false;
3322}
3323
David Majnemer408b5e62016-02-05 01:55:49 +00003324/// parseDirectiveCVDefRange
3325/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3326bool AsmParser::parseDirectiveCVDefRange() {
3327 SMLoc Loc;
3328 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3329 while (getLexer().is(AsmToken::Identifier)) {
3330 Loc = getLexer().getLoc();
3331 StringRef GapStartName;
3332 if (parseIdentifier(GapStartName))
3333 return Error(Loc, "expected identifier in directive");
3334 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3335
3336 Loc = getLexer().getLoc();
3337 StringRef GapEndName;
3338 if (parseIdentifier(GapEndName))
3339 return Error(Loc, "expected identifier in directive");
3340 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3341
3342 Ranges.push_back({GapStartSym, GapEndSym});
3343 }
3344
3345 if (getLexer().isNot(AsmToken::Comma))
3346 return TokError("unexpected token in directive");
3347 Lex();
3348
3349 std::string FixedSizePortion;
3350 if (parseEscapedString(FixedSizePortion))
3351 return true;
3352 Lex();
3353
3354 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3355 return false;
3356}
3357
Reid Kleckner2214ed82016-01-29 00:49:42 +00003358/// parseDirectiveCVStringTable
3359/// ::= .cv_stringtable
3360bool AsmParser::parseDirectiveCVStringTable() {
3361 getStreamer().EmitCVStringTableDirective();
3362 return false;
3363}
3364
3365/// parseDirectiveCVFileChecksums
3366/// ::= .cv_filechecksums
3367bool AsmParser::parseDirectiveCVFileChecksums() {
3368 getStreamer().EmitCVFileChecksumsDirective();
3369 return false;
3370}
3371
Jim Grosbach4b905842013-09-20 23:08:21 +00003372/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003373/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003374bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003375 StringRef Name;
3376 bool EH = false;
3377 bool Debug = false;
3378
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003379 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003380 return TokError("Expected an identifier");
3381
3382 if (Name == ".eh_frame")
3383 EH = true;
3384 else if (Name == ".debug_frame")
3385 Debug = true;
3386
3387 if (getLexer().is(AsmToken::Comma)) {
3388 Lex();
3389
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003390 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003391 return TokError("Expected an identifier");
3392
3393 if (Name == ".eh_frame")
3394 EH = true;
3395 else if (Name == ".debug_frame")
3396 Debug = true;
3397 }
3398
3399 getStreamer().EmitCFISections(EH, Debug);
3400 return false;
3401}
3402
Jim Grosbach4b905842013-09-20 23:08:21 +00003403/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003404/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003405bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003406 StringRef Simple;
3407 if (getLexer().isNot(AsmToken::EndOfStatement))
3408 if (parseIdentifier(Simple) || Simple != "simple")
3409 return TokError("unexpected token in .cfi_startproc directive");
3410
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003411 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003412 return false;
3413}
3414
Jim Grosbach4b905842013-09-20 23:08:21 +00003415/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003416/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003417bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003418 getStreamer().EmitCFIEndProc();
3419 return false;
3420}
3421
Jim Grosbach4b905842013-09-20 23:08:21 +00003422/// \brief parse register name or number.
3423bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003424 SMLoc DirectiveLoc) {
3425 unsigned RegNo;
3426
3427 if (getLexer().isNot(AsmToken::Integer)) {
3428 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3429 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003430 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003431 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003432 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003433
3434 return false;
3435}
3436
Jim Grosbach4b905842013-09-20 23:08:21 +00003437/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003438/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003439bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003440 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003441 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003442 return true;
3443
3444 if (getLexer().isNot(AsmToken::Comma))
3445 return TokError("unexpected token in directive");
3446 Lex();
3447
3448 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003449 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003450 return true;
3451
3452 getStreamer().EmitCFIDefCfa(Register, Offset);
3453 return false;
3454}
3455
Jim Grosbach4b905842013-09-20 23:08:21 +00003456/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003457/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003458bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003459 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003460 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003461 return true;
3462
3463 getStreamer().EmitCFIDefCfaOffset(Offset);
3464 return false;
3465}
3466
Jim Grosbach4b905842013-09-20 23:08:21 +00003467/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003468/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003469bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003470 int64_t Register1 = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003471 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003472 return true;
3473
3474 if (getLexer().isNot(AsmToken::Comma))
3475 return TokError("unexpected token in directive");
3476 Lex();
3477
3478 int64_t Register2 = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003479 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003480 return true;
3481
3482 getStreamer().EmitCFIRegister(Register1, Register2);
3483 return false;
3484}
3485
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003486/// parseDirectiveCFIWindowSave
3487/// ::= .cfi_window_save
3488bool AsmParser::parseDirectiveCFIWindowSave() {
3489 getStreamer().EmitCFIWindowSave();
3490 return false;
3491}
3492
Jim Grosbach4b905842013-09-20 23:08:21 +00003493/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003494/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003495bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003496 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003497 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003498 return true;
3499
3500 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3501 return false;
3502}
3503
Jim Grosbach4b905842013-09-20 23:08:21 +00003504/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003505/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003506bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003507 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003508 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003509 return true;
3510
3511 getStreamer().EmitCFIDefCfaRegister(Register);
3512 return false;
3513}
3514
Jim Grosbach4b905842013-09-20 23:08:21 +00003515/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003516/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003517bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003518 int64_t Register = 0;
3519 int64_t Offset = 0;
3520
Jim Grosbach4b905842013-09-20 23:08:21 +00003521 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003522 return true;
3523
3524 if (getLexer().isNot(AsmToken::Comma))
3525 return TokError("unexpected token in directive");
3526 Lex();
3527
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003528 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003529 return true;
3530
3531 getStreamer().EmitCFIOffset(Register, Offset);
3532 return false;
3533}
3534
Jim Grosbach4b905842013-09-20 23:08:21 +00003535/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003536/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003537bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003538 int64_t Register = 0;
3539
Jim Grosbach4b905842013-09-20 23:08:21 +00003540 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003541 return true;
3542
3543 if (getLexer().isNot(AsmToken::Comma))
3544 return TokError("unexpected token in directive");
3545 Lex();
3546
3547 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003548 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003549 return true;
3550
3551 getStreamer().EmitCFIRelOffset(Register, Offset);
3552 return false;
3553}
3554
3555static bool isValidEncoding(int64_t Encoding) {
3556 if (Encoding & ~0xff)
3557 return false;
3558
3559 if (Encoding == dwarf::DW_EH_PE_omit)
3560 return true;
3561
3562 const unsigned Format = Encoding & 0xf;
3563 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3564 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3565 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3566 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3567 return false;
3568
3569 const unsigned Application = Encoding & 0x70;
3570 if (Application != dwarf::DW_EH_PE_absptr &&
3571 Application != dwarf::DW_EH_PE_pcrel)
3572 return false;
3573
3574 return true;
3575}
3576
Jim Grosbach4b905842013-09-20 23:08:21 +00003577/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003578/// IsPersonality true for cfi_personality, false for cfi_lsda
3579/// ::= .cfi_personality encoding, [symbol_name]
3580/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003581bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003582 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003583 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003584 return true;
3585 if (Encoding == dwarf::DW_EH_PE_omit)
3586 return false;
3587
3588 if (!isValidEncoding(Encoding))
3589 return TokError("unsupported encoding.");
3590
3591 if (getLexer().isNot(AsmToken::Comma))
3592 return TokError("unexpected token in directive");
3593 Lex();
3594
3595 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003596 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003597 return TokError("expected identifier in directive");
3598
Jim Grosbach6f482002015-05-18 18:43:14 +00003599 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003600
3601 if (IsPersonality)
3602 getStreamer().EmitCFIPersonality(Sym, Encoding);
3603 else
3604 getStreamer().EmitCFILsda(Sym, Encoding);
3605 return false;
3606}
3607
Jim Grosbach4b905842013-09-20 23:08:21 +00003608/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00003609/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003610bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003611 getStreamer().EmitCFIRememberState();
3612 return false;
3613}
3614
Jim Grosbach4b905842013-09-20 23:08:21 +00003615/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00003616/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003617bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003618 getStreamer().EmitCFIRestoreState();
3619 return false;
3620}
3621
Jim Grosbach4b905842013-09-20 23:08:21 +00003622/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00003623/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00003624bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003625 int64_t Register = 0;
3626
Jim Grosbach4b905842013-09-20 23:08:21 +00003627 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003628 return true;
3629
3630 getStreamer().EmitCFISameValue(Register);
3631 return false;
3632}
3633
Jim Grosbach4b905842013-09-20 23:08:21 +00003634/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00003635/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00003636bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003637 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003638 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003639 return true;
3640
3641 getStreamer().EmitCFIRestore(Register);
3642 return false;
3643}
3644
Jim Grosbach4b905842013-09-20 23:08:21 +00003645/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00003646/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003647bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00003648 std::string Values;
3649 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003650 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003651 return true;
3652
3653 Values.push_back((uint8_t)CurrValue);
3654
3655 while (getLexer().is(AsmToken::Comma)) {
3656 Lex();
3657
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003658 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003659 return true;
3660
3661 Values.push_back((uint8_t)CurrValue);
3662 }
3663
3664 getStreamer().EmitCFIEscape(Values);
3665 return false;
3666}
3667
Jim Grosbach4b905842013-09-20 23:08:21 +00003668/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00003669/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00003670bool AsmParser::parseDirectiveCFISignalFrame() {
Eli Bendersky17233942013-01-15 22:59:42 +00003671 if (getLexer().isNot(AsmToken::EndOfStatement))
3672 return Error(getLexer().getLoc(),
3673 "unexpected token in '.cfi_signal_frame'");
3674
3675 getStreamer().EmitCFISignalFrame();
3676 return false;
3677}
3678
Jim Grosbach4b905842013-09-20 23:08:21 +00003679/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00003680/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00003681bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003682 int64_t Register = 0;
3683
Jim Grosbach4b905842013-09-20 23:08:21 +00003684 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003685 return true;
3686
3687 getStreamer().EmitCFIUndefined(Register);
3688 return false;
3689}
3690
Jim Grosbach4b905842013-09-20 23:08:21 +00003691/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00003692/// ::= .macros_on
3693/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00003694bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00003695 if (getLexer().isNot(AsmToken::EndOfStatement))
3696 return Error(getLexer().getLoc(),
3697 "unexpected token in '" + Directive + "' directive");
3698
Jim Grosbach4b905842013-09-20 23:08:21 +00003699 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00003700 return false;
3701}
3702
Jim Grosbach4b905842013-09-20 23:08:21 +00003703/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003704/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00003705bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003706 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003707 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003708 return TokError("expected identifier in '.macro' directive");
3709
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003710 if (getLexer().is(AsmToken::Comma))
3711 Lex();
3712
Eli Bendersky17233942013-01-15 22:59:42 +00003713 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00003714 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003715
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003716 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003717 return Error(Lexer.getLoc(),
3718 "Vararg parameter '" + Parameters.back().Name +
3719 "' should be last one in the list of parameters.");
3720
David Majnemer91fc4c22014-01-29 18:57:46 +00003721 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003722 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00003723 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003724
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003725 if (Lexer.is(AsmToken::Colon)) {
3726 Lex(); // consume ':'
3727
3728 SMLoc QualLoc;
3729 StringRef Qualifier;
3730
3731 QualLoc = Lexer.getLoc();
3732 if (parseIdentifier(Qualifier))
3733 return Error(QualLoc, "missing parameter qualifier for "
3734 "'" + Parameter.Name + "' in macro '" + Name + "'");
3735
3736 if (Qualifier == "req")
3737 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00003738 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003739 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003740 else
3741 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3742 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3743 }
3744
David Majnemer91fc4c22014-01-29 18:57:46 +00003745 if (getLexer().is(AsmToken::Equal)) {
3746 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003747
3748 SMLoc ParamLoc;
3749
3750 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003751 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00003752 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003753
3754 if (Parameter.Required)
3755 Warning(ParamLoc, "pointless default value for required parameter "
3756 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00003757 }
David Majnemer91fc4c22014-01-29 18:57:46 +00003758
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003759 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00003760
3761 if (getLexer().is(AsmToken::Comma))
3762 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003763 }
3764
3765 // Eat the end of statement.
3766 Lex();
3767
3768 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003769 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003770
3771 // Lex the macro definition.
3772 for (;;) {
3773 // Check whether we have reached the end of the file.
3774 if (getLexer().is(AsmToken::Eof))
3775 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3776
3777 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003778 if (getLexer().is(AsmToken::Identifier)) {
3779 if (getTok().getIdentifier() == ".endm" ||
3780 getTok().getIdentifier() == ".endmacro") {
3781 if (MacroDepth == 0) { // Outermost macro.
3782 EndToken = getTok();
3783 Lex();
3784 if (getLexer().isNot(AsmToken::EndOfStatement))
3785 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3786 "' directive");
3787 break;
3788 } else {
3789 // Otherwise we just found the end of an inner macro.
3790 --MacroDepth;
3791 }
3792 } else if (getTok().getIdentifier() == ".macro") {
3793 // We allow nested macros. Those aren't instantiated until the outermost
3794 // macro is expanded so just ignore them for now.
3795 ++MacroDepth;
3796 }
Eli Bendersky17233942013-01-15 22:59:42 +00003797 }
3798
3799 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003800 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00003801 }
3802
Jim Grosbach4b905842013-09-20 23:08:21 +00003803 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00003804 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3805 }
3806
3807 const char *BodyStart = StartToken.getLoc().getPointer();
3808 const char *BodyEnd = EndToken.getLoc().getPointer();
3809 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00003810 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003811 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00003812 return false;
3813}
3814
Jim Grosbach4b905842013-09-20 23:08:21 +00003815/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00003816///
3817/// With the support added for named parameters there may be code out there that
3818/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00003819/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00003820/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00003821/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00003822/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3823/// warning that the positional parameter found in body which have no effect.
3824/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00003825/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00003826/// intended or change the macro to use the named parameters. It is possible
3827/// this warning will trigger when the none of the named parameters are used
3828/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00003829void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00003830 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00003831 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00003832 // If this macro is not defined with named parameters the warning we are
3833 // checking for here doesn't apply.
3834 unsigned NParameters = Parameters.size();
3835 if (NParameters == 0)
3836 return;
3837
3838 bool NamedParametersFound = false;
3839 bool PositionalParametersFound = false;
3840
3841 // Look at the body of the macro for use of both the named parameters and what
3842 // are likely to be positional parameters. This is what expandMacro() is
3843 // doing when it finds the parameters in the body.
3844 while (!Body.empty()) {
3845 // Scan for the next possible parameter.
3846 std::size_t End = Body.size(), Pos = 0;
3847 for (; Pos != End; ++Pos) {
3848 // Check for a substitution or escape.
3849 // This macro is defined with parameters, look for \foo, \bar, etc.
3850 if (Body[Pos] == '\\' && Pos + 1 != End)
3851 break;
3852
3853 // This macro should have parameters, but look for $0, $1, ..., $n too.
3854 if (Body[Pos] != '$' || Pos + 1 == End)
3855 continue;
3856 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00003857 if (Next == '$' || Next == 'n' ||
3858 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00003859 break;
3860 }
3861
3862 // Check if we reached the end.
3863 if (Pos == End)
3864 break;
3865
3866 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00003867 switch (Body[Pos + 1]) {
3868 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00003869 case '$':
3870 break;
3871
Jim Grosbach4b905842013-09-20 23:08:21 +00003872 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00003873 case 'n':
3874 PositionalParametersFound = true;
3875 break;
3876
Jim Grosbach4b905842013-09-20 23:08:21 +00003877 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00003878 default: {
3879 PositionalParametersFound = true;
3880 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00003881 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00003882 }
3883 Pos += 2;
3884 } else {
3885 unsigned I = Pos + 1;
3886 while (isIdentifierChar(Body[I]) && I + 1 != End)
3887 ++I;
3888
Jim Grosbach4b905842013-09-20 23:08:21 +00003889 const char *Begin = Body.data() + Pos + 1;
3890 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00003891 unsigned Index = 0;
3892 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003893 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00003894 break;
3895
3896 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00003897 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3898 Pos += 3;
3899 else {
3900 Pos = I;
3901 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00003902 } else {
3903 NamedParametersFound = true;
3904 Pos += 1 + Argument.size();
3905 }
3906 }
3907 // Update the scan point.
3908 Body = Body.substr(Pos);
3909 }
3910
3911 if (!NamedParametersFound && PositionalParametersFound)
3912 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3913 "used in macro body, possible positional parameter "
3914 "found in body which will have no effect");
3915}
3916
Nico Weber155dccd12014-07-24 17:08:39 +00003917/// parseDirectiveExitMacro
3918/// ::= .exitm
3919bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3920 if (getLexer().isNot(AsmToken::EndOfStatement))
3921 return TokError("unexpected token in '" + Directive + "' directive");
3922
3923 if (!isInsideMacroInstantiation())
3924 return TokError("unexpected '" + Directive + "' in file, "
3925 "no current macro definition");
3926
3927 // Exit all conditionals that are active in the current macro.
3928 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3929 TheCondState = TheCondStack.back();
3930 TheCondStack.pop_back();
3931 }
3932
3933 handleMacroExit();
3934 return false;
3935}
3936
Jim Grosbach4b905842013-09-20 23:08:21 +00003937/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00003938/// ::= .endm
3939/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00003940bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00003941 if (getLexer().isNot(AsmToken::EndOfStatement))
3942 return TokError("unexpected token in '" + Directive + "' directive");
3943
3944 // If we are inside a macro instantiation, terminate the current
3945 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00003946 if (isInsideMacroInstantiation()) {
3947 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00003948 return false;
3949 }
3950
3951 // Otherwise, this .endmacro is a stray entry in the file; well formed
3952 // .endmacro directives are handled during the macro definition parsing.
3953 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00003954 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00003955}
3956
Jim Grosbach4b905842013-09-20 23:08:21 +00003957/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00003958/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00003959bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003960 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003961 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003962 return TokError("expected identifier in '.purgem' directive");
3963
3964 if (getLexer().isNot(AsmToken::EndOfStatement))
3965 return TokError("unexpected token in '.purgem' directive");
3966
Jim Grosbach4b905842013-09-20 23:08:21 +00003967 if (!lookupMacro(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003968 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3969
Jim Grosbach4b905842013-09-20 23:08:21 +00003970 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003971 return false;
3972}
Eli Benderskyf483ff92012-12-20 19:05:53 +00003973
Jim Grosbach4b905842013-09-20 23:08:21 +00003974/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00003975/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003976bool AsmParser::parseDirectiveBundleAlignMode() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003977 checkForValidSection();
Eli Benderskyf483ff92012-12-20 19:05:53 +00003978
3979 // Expect a single argument: an expression that evaluates to a constant
3980 // in the inclusive range 0-30.
3981 SMLoc ExprLoc = getLexer().getLoc();
3982 int64_t AlignSizePow2;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003983 if (parseAbsoluteExpression(AlignSizePow2))
Eli Benderskyf483ff92012-12-20 19:05:53 +00003984 return true;
3985 else if (getLexer().isNot(AsmToken::EndOfStatement))
3986 return TokError("unexpected token after expression in"
3987 " '.bundle_align_mode' directive");
3988 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3989 return Error(ExprLoc,
3990 "invalid bundle alignment size (expected between 0 and 30)");
3991
3992 Lex();
3993
3994 // Because of AlignSizePow2's verified range we can safely truncate it to
3995 // unsigned.
3996 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3997 return false;
3998}
3999
Jim Grosbach4b905842013-09-20 23:08:21 +00004000/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004001/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004002bool AsmParser::parseDirectiveBundleLock() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004003 checkForValidSection();
Eli Bendersky802b6282013-01-07 21:51:08 +00004004 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004005
Eli Bendersky802b6282013-01-07 21:51:08 +00004006 if (getLexer().isNot(AsmToken::EndOfStatement)) {
4007 StringRef Option;
4008 SMLoc Loc = getTok().getLoc();
4009 const char *kInvalidOptionError =
Jim Grosbach4b905842013-09-20 23:08:21 +00004010 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004011
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004012 if (parseIdentifier(Option))
Eli Bendersky802b6282013-01-07 21:51:08 +00004013 return Error(Loc, kInvalidOptionError);
4014
4015 if (Option != "align_to_end")
4016 return Error(Loc, kInvalidOptionError);
4017 else if (getLexer().isNot(AsmToken::EndOfStatement))
4018 return Error(Loc,
4019 "unexpected token after '.bundle_lock' directive option");
4020 AlignToEnd = true;
4021 }
4022
Eli Benderskyf483ff92012-12-20 19:05:53 +00004023 Lex();
4024
Eli Bendersky802b6282013-01-07 21:51:08 +00004025 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004026 return false;
4027}
4028
Jim Grosbach4b905842013-09-20 23:08:21 +00004029/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004030/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004031bool AsmParser::parseDirectiveBundleUnlock() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004032 checkForValidSection();
Eli Benderskyf483ff92012-12-20 19:05:53 +00004033
4034 if (getLexer().isNot(AsmToken::EndOfStatement))
4035 return TokError("unexpected token in '.bundle_unlock' directive");
4036 Lex();
4037
4038 getStreamer().EmitBundleUnlock();
4039 return false;
4040}
4041
Jim Grosbach4b905842013-09-20 23:08:21 +00004042/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004043/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004044bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004045 checkForValidSection();
Eli Bendersky17233942013-01-15 22:59:42 +00004046
Petr Hosek67a94a72016-05-28 05:57:48 +00004047 SMLoc NumBytesLoc = Lexer.getLoc();
4048 const MCExpr *NumBytes;
4049 if (parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004050 return true;
4051
4052 int64_t FillExpr = 0;
4053 if (getLexer().isNot(AsmToken::EndOfStatement)) {
4054 if (getLexer().isNot(AsmToken::Comma))
4055 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
4056 Lex();
4057
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004058 if (parseAbsoluteExpression(FillExpr))
Eli Bendersky17233942013-01-15 22:59:42 +00004059 return true;
4060
4061 if (getLexer().isNot(AsmToken::EndOfStatement))
4062 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
4063 }
4064
4065 Lex();
4066
Eli Bendersky17233942013-01-15 22:59:42 +00004067 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004068 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004069
4070 return false;
4071}
4072
Jim Grosbach4b905842013-09-20 23:08:21 +00004073/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004074/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004075bool AsmParser::parseDirectiveLEB128(bool Signed) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004076 checkForValidSection();
Eli Bendersky17233942013-01-15 22:59:42 +00004077 const MCExpr *Value;
4078
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004079 for (;;) {
4080 if (parseExpression(Value))
4081 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004082
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004083 if (Signed)
4084 getStreamer().EmitSLEB128Value(Value);
4085 else
4086 getStreamer().EmitULEB128Value(Value);
Eli Bendersky17233942013-01-15 22:59:42 +00004087
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004088 if (getLexer().is(AsmToken::EndOfStatement))
4089 break;
4090
4091 if (getLexer().isNot(AsmToken::Comma))
4092 return TokError("unexpected token in directive");
4093 Lex();
4094 }
Eli Bendersky17233942013-01-15 22:59:42 +00004095
4096 return false;
4097}
4098
Jim Grosbach4b905842013-09-20 23:08:21 +00004099/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004100/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004101bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004102 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbara5508c82009-06-30 00:33:19 +00004103 for (;;) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004104 StringRef Name;
Jim Grosbachebdf32f2011-09-15 17:56:49 +00004105 SMLoc Loc = getTok().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004106
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004107 if (parseIdentifier(Name))
Jim Grosbachebdf32f2011-09-15 17:56:49 +00004108 return Error(Loc, "expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004109
Jim Grosbach6f482002015-05-18 18:43:14 +00004110 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbara5508c82009-06-30 00:33:19 +00004111
Jim Grosbachebdf32f2011-09-15 17:56:49 +00004112 // Assembler local symbols don't make any sense here. Complain loudly.
4113 if (Sym->isTemporary())
4114 return Error(Loc, "non-local symbol required in directive");
4115
Saleem Abdulrasool4208b612013-08-09 01:52:03 +00004116 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4117 return Error(Loc, "unable to emit symbol attribute");
Daniel Dunbara5508c82009-06-30 00:33:19 +00004118
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004119 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara5508c82009-06-30 00:33:19 +00004120 break;
4121
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004122 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara5508c82009-06-30 00:33:19 +00004123 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004124 Lex();
Daniel Dunbara5508c82009-06-30 00:33:19 +00004125 }
4126 }
4127
Sean Callanan686ed8d2010-01-19 20:22:31 +00004128 Lex();
Jan Wen Voungc7682872010-09-30 01:09:20 +00004129 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004130}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004131
Jim Grosbach4b905842013-09-20 23:08:21 +00004132/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004133/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004134bool AsmParser::parseDirectiveComm(bool IsLocal) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004135 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00004136
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004137 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004138 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004139 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004140 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004141
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004142 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004143 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004144
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004145 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004146 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004147 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004148
4149 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004150 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004151 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004152 return true;
4153
4154 int64_t Pow2Alignment = 0;
4155 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004156 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004157 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004158 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004159 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004160 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004161
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004162 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4163 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004164 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4165
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004166 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004167 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4168 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004169 if (!isPowerOf2_64(Pow2Alignment))
4170 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4171 Pow2Alignment = Log2_64(Pow2Alignment);
4172 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004173 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004174
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004175 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner28ad7542009-07-09 17:25:12 +00004176 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004177
Sean Callanan686ed8d2010-01-19 20:22:31 +00004178 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004179
Chris Lattner28ad7542009-07-09 17:25:12 +00004180 // NOTE: a size of zero for a .comm should create a undefined symbol
4181 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004182 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004183 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004184 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004185
Eric Christopherbc818852010-05-14 01:38:54 +00004186 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004187 // may internally end up wanting an alignment in bytes.
4188 // FIXME: Diagnose overflow.
4189 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004190 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004191 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004192
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004193 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004194 return Error(IDLoc, "invalid symbol redefinition");
4195
Chris Lattner28ad7542009-07-09 17:25:12 +00004196 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004197 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004198 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004199 return false;
4200 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004201
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004202 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004203 return false;
4204}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004205
Jim Grosbach4b905842013-09-20 23:08:21 +00004206/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004207/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004208bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004209 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004210 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004211
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004212 StringRef Str = parseStringToEndOfStatement();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004213 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby56523ce2009-07-13 23:15:14 +00004214 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004215
Sean Callanan686ed8d2010-01-19 20:22:31 +00004216 Lex();
Kevin Enderby56523ce2009-07-13 23:15:14 +00004217
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004218 if (Str.empty())
4219 Error(Loc, ".abort detected. Assembly stopping.");
4220 else
4221 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004222 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004223
4224 return false;
4225}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004226
Jim Grosbach4b905842013-09-20 23:08:21 +00004227/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004228/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004229bool AsmParser::parseDirectiveInclude() {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004230 if (getLexer().isNot(AsmToken::String))
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004231 return TokError("expected string in '.include' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004232
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004233 // Allow the strings to have escaped octal character sequence.
4234 std::string Filename;
4235 if (parseEscapedString(Filename))
4236 return true;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004237 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00004238 Lex();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004239
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004240 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004241 return TokError("unexpected token in '.include' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004242
Chris Lattner693fbb82009-07-16 06:14:39 +00004243 // Attempt to switch the lexer to the included file before consuming the end
4244 // of statement to avoid losing it when we switch.
Jim Grosbach4b905842013-09-20 23:08:21 +00004245 if (enterIncludeFile(Filename)) {
Daniel Dunbard8a18452010-07-18 18:31:45 +00004246 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner693fbb82009-07-16 06:14:39 +00004247 return true;
4248 }
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004249
4250 return false;
4251}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004252
Jim Grosbach4b905842013-09-20 23:08:21 +00004253/// parseDirectiveIncbin
Kevin Enderby109f25c2011-12-14 21:47:48 +00004254/// ::= .incbin "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004255bool AsmParser::parseDirectiveIncbin() {
Kevin Enderby109f25c2011-12-14 21:47:48 +00004256 if (getLexer().isNot(AsmToken::String))
4257 return TokError("expected string in '.incbin' directive");
4258
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004259 // Allow the strings to have escaped octal character sequence.
4260 std::string Filename;
4261 if (parseEscapedString(Filename))
4262 return true;
Kevin Enderby109f25c2011-12-14 21:47:48 +00004263 SMLoc IncbinLoc = getLexer().getLoc();
4264 Lex();
4265
4266 if (getLexer().isNot(AsmToken::EndOfStatement))
4267 return TokError("unexpected token in '.incbin' directive");
4268
Kevin Enderby109f25c2011-12-14 21:47:48 +00004269 // Attempt to process the included file.
Jim Grosbach4b905842013-09-20 23:08:21 +00004270 if (processIncbinFile(Filename)) {
Kevin Enderby109f25c2011-12-14 21:47:48 +00004271 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
4272 return true;
4273 }
4274
4275 return false;
4276}
4277
Jim Grosbach4b905842013-09-20 23:08:21 +00004278/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004279/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4280bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004281 TheCondStack.push_back(TheCondState);
4282 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004283 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004284 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004285 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004286 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004287 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004288 return true;
4289
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004290 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004291 return TokError("unexpected token in '.if' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004292
Sean Callanan686ed8d2010-01-19 20:22:31 +00004293 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004294
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004295 switch (DirKind) {
4296 default:
4297 llvm_unreachable("unsupported directive");
4298 case DK_IF:
4299 case DK_IFNE:
4300 break;
4301 case DK_IFEQ:
4302 ExprValue = ExprValue == 0;
4303 break;
4304 case DK_IFGE:
4305 ExprValue = ExprValue >= 0;
4306 break;
4307 case DK_IFGT:
4308 ExprValue = ExprValue > 0;
4309 break;
4310 case DK_IFLE:
4311 ExprValue = ExprValue <= 0;
4312 break;
4313 case DK_IFLT:
4314 ExprValue = ExprValue < 0;
4315 break;
4316 }
4317
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004318 TheCondState.CondMet = ExprValue;
4319 TheCondState.Ignore = !TheCondState.CondMet;
4320 }
4321
4322 return false;
4323}
4324
Jim Grosbach4b905842013-09-20 23:08:21 +00004325/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004326/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004327bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004328 TheCondStack.push_back(TheCondState);
4329 TheCondState.TheCond = AsmCond::IfCond;
4330
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004331 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004332 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004333 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004334 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004335
4336 if (getLexer().isNot(AsmToken::EndOfStatement))
4337 return TokError("unexpected token in '.ifb' directive");
4338
4339 Lex();
4340
4341 TheCondState.CondMet = ExpectBlank == Str.empty();
4342 TheCondState.Ignore = !TheCondState.CondMet;
4343 }
4344
4345 return false;
4346}
4347
Jim Grosbach4b905842013-09-20 23:08:21 +00004348/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004349/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004350/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004351bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004352 TheCondStack.push_back(TheCondState);
4353 TheCondState.TheCond = AsmCond::IfCond;
4354
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004355 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004356 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004357 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004358 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004359
4360 if (getLexer().isNot(AsmToken::Comma))
4361 return TokError("unexpected token in '.ifc' directive");
4362
4363 Lex();
4364
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004365 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004366
4367 if (getLexer().isNot(AsmToken::EndOfStatement))
4368 return TokError("unexpected token in '.ifc' directive");
4369
4370 Lex();
4371
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004372 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004373 TheCondState.Ignore = !TheCondState.CondMet;
4374 }
4375
4376 return false;
4377}
4378
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004379/// parseDirectiveIfeqs
4380/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004381bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004382 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004383 if (ExpectEqual)
4384 TokError("expected string parameter for '.ifeqs' directive");
4385 else
4386 TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004387 eatToEndOfStatement();
4388 return true;
4389 }
4390
4391 StringRef String1 = getTok().getStringContents();
4392 Lex();
4393
4394 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004395 if (ExpectEqual)
4396 TokError("expected comma after first string for '.ifeqs' directive");
4397 else
4398 TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004399 eatToEndOfStatement();
4400 return true;
4401 }
4402
4403 Lex();
4404
4405 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004406 if (ExpectEqual)
4407 TokError("expected string parameter for '.ifeqs' directive");
4408 else
4409 TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004410 eatToEndOfStatement();
4411 return true;
4412 }
4413
4414 StringRef String2 = getTok().getStringContents();
4415 Lex();
4416
4417 TheCondStack.push_back(TheCondState);
4418 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004419 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004420 TheCondState.Ignore = !TheCondState.CondMet;
4421
4422 return false;
4423}
4424
Jim Grosbach4b905842013-09-20 23:08:21 +00004425/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004426/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004427bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004428 StringRef Name;
4429 TheCondStack.push_back(TheCondState);
4430 TheCondState.TheCond = AsmCond::IfCond;
4431
4432 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004433 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004434 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004435 if (parseIdentifier(Name))
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004436 return TokError("expected identifier after '.ifdef'");
4437
4438 Lex();
4439
Jim Grosbach6f482002015-05-18 18:43:14 +00004440 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004441
4442 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004443 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004444 else
Craig Topper353eda42014-04-24 06:44:33 +00004445 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004446 TheCondState.Ignore = !TheCondState.CondMet;
4447 }
4448
4449 return false;
4450}
4451
Jim Grosbach4b905842013-09-20 23:08:21 +00004452/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004453/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004454bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004455 if (TheCondState.TheCond != AsmCond::IfCond &&
4456 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper2172ad62013-04-22 04:24:02 +00004457 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4458 " an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004459 TheCondState.TheCond = AsmCond::ElseIfCond;
4460
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004461 bool LastIgnoreState = false;
4462 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004463 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004464 if (LastIgnoreState || TheCondState.CondMet) {
4465 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004466 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004467 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004468 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004469 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004470 return true;
4471
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004472 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004473 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004474
Sean Callanan686ed8d2010-01-19 20:22:31 +00004475 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004476 TheCondState.CondMet = ExprValue;
4477 TheCondState.Ignore = !TheCondState.CondMet;
4478 }
4479
4480 return false;
4481}
4482
Jim Grosbach4b905842013-09-20 23:08:21 +00004483/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004484/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004485bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004486 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004487 return TokError("unexpected token in '.else' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004488
Sean Callanan686ed8d2010-01-19 20:22:31 +00004489 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004490
4491 if (TheCondState.TheCond != AsmCond::IfCond &&
4492 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper2172ad62013-04-22 04:24:02 +00004493 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4494 ".elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004495 TheCondState.TheCond = AsmCond::ElseCond;
4496 bool LastIgnoreState = false;
4497 if (!TheCondStack.empty())
4498 LastIgnoreState = TheCondStack.back().Ignore;
4499 if (LastIgnoreState || TheCondState.CondMet)
4500 TheCondState.Ignore = true;
4501 else
4502 TheCondState.Ignore = false;
4503
4504 return false;
4505}
4506
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004507/// parseDirectiveEnd
4508/// ::= .end
4509bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4510 if (getLexer().isNot(AsmToken::EndOfStatement))
4511 return TokError("unexpected token in '.end' directive");
4512
4513 Lex();
4514
4515 while (Lexer.isNot(AsmToken::Eof))
4516 Lex();
4517
4518 return false;
4519}
4520
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004521/// parseDirectiveError
4522/// ::= .err
4523/// ::= .error [string]
4524bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4525 if (!TheCondStack.empty()) {
4526 if (TheCondStack.back().Ignore) {
4527 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004528 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004529 }
4530 }
4531
4532 if (!WithMessage)
4533 return Error(L, ".err encountered");
4534
4535 StringRef Message = ".error directive invoked in source file";
4536 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4537 if (Lexer.isNot(AsmToken::String)) {
4538 TokError(".error argument must be a string");
4539 eatToEndOfStatement();
4540 return true;
4541 }
4542
4543 Message = getTok().getStringContents();
4544 Lex();
4545 }
4546
4547 Error(L, Message);
4548 return true;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004549}
4550
Nico Weber404012b2014-07-24 16:26:06 +00004551/// parseDirectiveWarning
4552/// ::= .warning [string]
4553bool AsmParser::parseDirectiveWarning(SMLoc L) {
4554 if (!TheCondStack.empty()) {
4555 if (TheCondStack.back().Ignore) {
4556 eatToEndOfStatement();
4557 return false;
4558 }
4559 }
4560
4561 StringRef Message = ".warning directive invoked in source file";
4562 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4563 if (Lexer.isNot(AsmToken::String)) {
4564 TokError(".warning argument must be a string");
4565 eatToEndOfStatement();
4566 return true;
4567 }
4568
4569 Message = getTok().getStringContents();
4570 Lex();
4571 }
4572
4573 Warning(L, Message);
4574 return false;
4575}
4576
Jim Grosbach4b905842013-09-20 23:08:21 +00004577/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004578/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00004579bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004580 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004581 return TokError("unexpected token in '.endif' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004582
Sean Callanan686ed8d2010-01-19 20:22:31 +00004583 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004584
Jim Grosbach4b905842013-09-20 23:08:21 +00004585 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004586 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4587 ".else");
4588 if (!TheCondStack.empty()) {
4589 TheCondState = TheCondStack.back();
4590 TheCondStack.pop_back();
4591 }
4592
4593 return false;
4594}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00004595
Eli Bendersky17233942013-01-15 22:59:42 +00004596void AsmParser::initializeDirectiveKindMap() {
4597 DirectiveKindMap[".set"] = DK_SET;
4598 DirectiveKindMap[".equ"] = DK_EQU;
4599 DirectiveKindMap[".equiv"] = DK_EQUIV;
4600 DirectiveKindMap[".ascii"] = DK_ASCII;
4601 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4602 DirectiveKindMap[".string"] = DK_STRING;
4603 DirectiveKindMap[".byte"] = DK_BYTE;
4604 DirectiveKindMap[".short"] = DK_SHORT;
4605 DirectiveKindMap[".value"] = DK_VALUE;
4606 DirectiveKindMap[".2byte"] = DK_2BYTE;
4607 DirectiveKindMap[".long"] = DK_LONG;
4608 DirectiveKindMap[".int"] = DK_INT;
4609 DirectiveKindMap[".4byte"] = DK_4BYTE;
4610 DirectiveKindMap[".quad"] = DK_QUAD;
4611 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00004612 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00004613 DirectiveKindMap[".single"] = DK_SINGLE;
4614 DirectiveKindMap[".float"] = DK_FLOAT;
4615 DirectiveKindMap[".double"] = DK_DOUBLE;
4616 DirectiveKindMap[".align"] = DK_ALIGN;
4617 DirectiveKindMap[".align32"] = DK_ALIGN32;
4618 DirectiveKindMap[".balign"] = DK_BALIGN;
4619 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4620 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4621 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4622 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4623 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4624 DirectiveKindMap[".org"] = DK_ORG;
4625 DirectiveKindMap[".fill"] = DK_FILL;
4626 DirectiveKindMap[".zero"] = DK_ZERO;
4627 DirectiveKindMap[".extern"] = DK_EXTERN;
4628 DirectiveKindMap[".globl"] = DK_GLOBL;
4629 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00004630 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4631 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4632 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4633 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4634 DirectiveKindMap[".reference"] = DK_REFERENCE;
4635 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4636 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4637 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4638 DirectiveKindMap[".comm"] = DK_COMM;
4639 DirectiveKindMap[".common"] = DK_COMMON;
4640 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4641 DirectiveKindMap[".abort"] = DK_ABORT;
4642 DirectiveKindMap[".include"] = DK_INCLUDE;
4643 DirectiveKindMap[".incbin"] = DK_INCBIN;
4644 DirectiveKindMap[".code16"] = DK_CODE16;
4645 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4646 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004647 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00004648 DirectiveKindMap[".irp"] = DK_IRP;
4649 DirectiveKindMap[".irpc"] = DK_IRPC;
4650 DirectiveKindMap[".endr"] = DK_ENDR;
4651 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4652 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4653 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4654 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004655 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4656 DirectiveKindMap[".ifge"] = DK_IFGE;
4657 DirectiveKindMap[".ifgt"] = DK_IFGT;
4658 DirectiveKindMap[".ifle"] = DK_IFLE;
4659 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00004660 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00004661 DirectiveKindMap[".ifb"] = DK_IFB;
4662 DirectiveKindMap[".ifnb"] = DK_IFNB;
4663 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004664 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00004665 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00004666 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00004667 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4668 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4669 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4670 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4671 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004672 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00004673 DirectiveKindMap[".endif"] = DK_ENDIF;
4674 DirectiveKindMap[".skip"] = DK_SKIP;
4675 DirectiveKindMap[".space"] = DK_SPACE;
4676 DirectiveKindMap[".file"] = DK_FILE;
4677 DirectiveKindMap[".line"] = DK_LINE;
4678 DirectiveKindMap[".loc"] = DK_LOC;
4679 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004680 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
4681 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
4682 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00004683 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
David Majnemer408b5e62016-02-05 01:55:49 +00004684 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004685 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
4686 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Eli Bendersky17233942013-01-15 22:59:42 +00004687 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4688 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4689 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4690 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4691 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4692 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4693 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4694 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4695 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4696 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4697 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4698 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4699 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4700 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4701 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4702 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4703 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4704 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4705 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4706 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4707 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00004708 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00004709 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4710 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4711 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00004712 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00004713 DirectiveKindMap[".endm"] = DK_ENDM;
4714 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4715 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004716 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004717 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00004718 DirectiveKindMap[".warning"] = DK_WARNING;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00004719 DirectiveKindMap[".reloc"] = DK_RELOC;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00004720}
4721
Jim Grosbach4b905842013-09-20 23:08:21 +00004722MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004723 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004724
Rafael Espindola34b9c512012-06-03 23:57:14 +00004725 unsigned NestLevel = 0;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004726 for (;;) {
4727 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00004728 if (getLexer().is(AsmToken::Eof)) {
4729 Error(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00004730 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004731 }
4732
Rafael Espindola34b9c512012-06-03 23:57:14 +00004733 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00004734 (getTok().getIdentifier() == ".rept" ||
4735 getTok().getIdentifier() == ".irp" ||
4736 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004737 ++NestLevel;
4738 }
4739
4740 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00004741 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004742 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004743 EndToken = getTok();
4744 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004745 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4746 TokError("unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00004747 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004748 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004749 break;
4750 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004751 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004752 }
4753
Rafael Espindola34b9c512012-06-03 23:57:14 +00004754 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004755 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004756 }
4757
4758 const char *BodyStart = StartToken.getLoc().getPointer();
4759 const char *BodyEnd = EndToken.getLoc().getPointer();
4760 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4761
Rafael Espindola34b9c512012-06-03 23:57:14 +00004762 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004763 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00004764 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004765}
4766
Jim Grosbach4b905842013-09-20 23:08:21 +00004767void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00004768 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004769 OS << ".endr\n";
4770
Rafael Espindola3560ff22014-08-27 20:03:13 +00004771 std::unique_ptr<MemoryBuffer> Instantiation =
4772 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004773
Rafael Espindola34b9c512012-06-03 23:57:14 +00004774 // Create the macro instantiation object and add to the current macro
4775 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00004776 MacroInstantiation *MI = new MacroInstantiation(
4777 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00004778 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004779
Rafael Espindola34b9c512012-06-03 23:57:14 +00004780 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00004781 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00004782 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00004783 Lex();
4784}
4785
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004786/// parseDirectiveRept
4787/// ::= .rep | .rept count
4788bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004789 const MCExpr *CountExpr;
4790 SMLoc CountLoc = getTok().getLoc();
4791 if (parseExpression(CountExpr))
4792 return true;
4793
Rafael Espindola34b9c512012-06-03 23:57:14 +00004794 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00004795 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004796 eatToEndOfStatement();
4797 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4798 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004799
4800 if (Count < 0)
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004801 return Error(CountLoc, "Count is negative");
Rafael Espindola34b9c512012-06-03 23:57:14 +00004802
4803 if (Lexer.isNot(AsmToken::EndOfStatement))
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004804 return TokError("unexpected token in '" + Dir + "' directive");
Rafael Espindola34b9c512012-06-03 23:57:14 +00004805
4806 // Eat the end of statement.
4807 Lex();
4808
4809 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004810 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00004811 if (!M)
4812 return true;
4813
4814 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4815 // to hold the macro body with substitutions.
4816 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004817 raw_svector_ostream OS(Buf);
4818 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00004819 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4820 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00004821 return true;
4822 }
Jim Grosbach4b905842013-09-20 23:08:21 +00004823 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004824
4825 return false;
4826}
4827
Jim Grosbach4b905842013-09-20 23:08:21 +00004828/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00004829/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00004830bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00004831 MCAsmMacroParameter Parameter;
Rafael Espindola768b41c2012-06-15 14:02:34 +00004832
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004833 if (parseIdentifier(Parameter.Name))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004834 return TokError("expected identifier in '.irp' directive");
4835
Rafael Espindola768b41c2012-06-15 14:02:34 +00004836 if (Lexer.isNot(AsmToken::Comma))
4837 return TokError("expected comma in '.irp' directive");
4838
4839 Lex();
4840
Eli Bendersky38274122013-01-14 23:22:36 +00004841 MCAsmMacroArguments A;
Craig Topper353eda42014-04-24 06:44:33 +00004842 if (parseMacroArguments(nullptr, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004843 return true;
4844
4845 // Eat the end of statement.
4846 Lex();
4847
4848 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004849 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00004850 if (!M)
4851 return true;
4852
4853 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4854 // to hold the macro body with substitutions.
4855 SmallString<256> Buf;
4856 raw_svector_ostream OS(Buf);
4857
Craig Topper84008482015-10-10 05:38:14 +00004858 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00004859 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4860 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00004861 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004862 return true;
4863 }
4864
Jim Grosbach4b905842013-09-20 23:08:21 +00004865 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00004866
4867 return false;
4868}
4869
Jim Grosbach4b905842013-09-20 23:08:21 +00004870/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004871/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00004872bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00004873 MCAsmMacroParameter Parameter;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004874
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004875 if (parseIdentifier(Parameter.Name))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004876 return TokError("expected identifier in '.irpc' directive");
4877
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004878 if (Lexer.isNot(AsmToken::Comma))
4879 return TokError("expected comma in '.irpc' directive");
4880
4881 Lex();
4882
Eli Bendersky38274122013-01-14 23:22:36 +00004883 MCAsmMacroArguments A;
Craig Topper353eda42014-04-24 06:44:33 +00004884 if (parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004885 return true;
4886
4887 if (A.size() != 1 || A.front().size() != 1)
4888 return TokError("unexpected token in '.irpc' directive");
4889
4890 // Eat the end of statement.
4891 Lex();
4892
4893 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004894 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004895 if (!M)
4896 return true;
4897
4898 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4899 // to hold the macro body with substitutions.
4900 SmallString<256> Buf;
4901 raw_svector_ostream OS(Buf);
4902
4903 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004904 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00004905 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004906 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004907
Toma Tabacu217116e2015-04-27 10:50:29 +00004908 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
4909 // This is undocumented, but GAS seems to support it.
4910 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004911 return true;
4912 }
4913
Jim Grosbach4b905842013-09-20 23:08:21 +00004914 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004915
4916 return false;
4917}
4918
Jim Grosbach4b905842013-09-20 23:08:21 +00004919bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004920 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00004921 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004922
4923 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00004924 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004925 assert(getLexer().is(AsmToken::EndOfStatement));
4926
Jim Grosbach4b905842013-09-20 23:08:21 +00004927 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004928 return false;
4929}
Rafael Espindola12d73d12010-09-11 16:45:15 +00004930
Jim Grosbach4b905842013-09-20 23:08:21 +00004931bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00004932 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00004933 const MCExpr *Value;
4934 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004935 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00004936 return true;
4937 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4938 if (!MCE)
4939 return Error(ExprLoc, "unexpected expression in _emit");
4940 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00004941 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00004942 return Error(ExprLoc, "literal value out of range for directive");
4943
Craig Topper7d5b2312015-10-10 05:25:02 +00004944 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00004945 return false;
4946}
4947
Jim Grosbach4b905842013-09-20 23:08:21 +00004948bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00004949 const MCExpr *Value;
4950 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004951 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00004952 return true;
4953 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4954 if (!MCE)
4955 return Error(ExprLoc, "unexpected expression in align");
4956 uint64_t IntValue = MCE->getValue();
4957 if (!isPowerOf2_64(IntValue))
4958 return Error(ExprLoc, "literal value not a power of two greater then zero");
4959
Craig Topper7d5b2312015-10-10 05:25:02 +00004960 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00004961 return false;
4962}
4963
Chad Rosierf43fcf52013-02-13 21:27:17 +00004964// We are comparing pointers, but the pointers are relative to a single string.
4965// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00004966static int rewritesSort(const AsmRewrite *AsmRewriteA,
4967 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00004968 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4969 return -1;
4970 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4971 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004972
Chad Rosierfce4fab2013-04-08 17:43:47 +00004973 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4974 // rewrite to the same location. Make sure the SizeDirective rewrite is
4975 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4976 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00004977 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4978 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004979 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00004980
Jim Grosbach4b905842013-09-20 23:08:21 +00004981 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4982 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004983 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00004984 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00004985}
4986
Jim Grosbach4b905842013-09-20 23:08:21 +00004987bool AsmParser::parseMSInlineAsm(
4988 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4989 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4990 SmallVectorImpl<std::string> &Constraints,
4991 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4992 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00004993 SmallVector<void *, 4> InputDecls;
4994 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00004995 SmallVector<bool, 4> InputDeclsAddressOf;
4996 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00004997 SmallVector<std::string, 4> InputConstraints;
4998 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00004999 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005000
Benjamin Kramer1a136112013-02-15 20:37:21 +00005001 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005002
5003 // Prime the lexer.
5004 Lex();
5005
5006 // While we have input, parse each statement.
5007 unsigned InputIdx = 0;
5008 unsigned OutputIdx = 0;
5009 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005010 // Parse curly braces marking block start/end
5011 if (parseCurlyBlockScope(AsmStrRewrites))
5012 continue;
5013
Eli Friedman0f4871d2012-10-22 23:58:19 +00005014 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005015 if (parseStatement(Info, &SI))
Chad Rosierf1f6a722012-10-19 22:57:33 +00005016 return true;
Chad Rosier8bce6642012-10-18 15:49:34 +00005017
Chad Rosier149e8e02012-12-12 22:45:52 +00005018 if (Info.ParseError)
5019 return true;
5020
Benjamin Kramer1a136112013-02-15 20:37:21 +00005021 if (Info.Opcode == ~0U)
5022 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005023
Benjamin Kramer1a136112013-02-15 20:37:21 +00005024 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005025
Benjamin Kramer1a136112013-02-15 20:37:21 +00005026 // Build the list of clobbers, outputs and inputs.
5027 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005028 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005029
Benjamin Kramer1a136112013-02-15 20:37:21 +00005030 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005031 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005032 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005033
Benjamin Kramer1a136112013-02-15 20:37:21 +00005034 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005035 if (Operand.isReg() && !Operand.needAddressOf() &&
5036 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005037 unsigned NumDefs = Desc.getNumDefs();
5038 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005039 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5040 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005041 continue;
5042 }
5043
5044 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005045 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005046 if (SymName.empty())
5047 continue;
5048
David Blaikie960ea3f2014-06-08 16:18:35 +00005049 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005050 if (!OpDecl)
5051 continue;
5052
5053 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005054 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005055 if (isOutput) {
5056 ++InputIdx;
5057 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005058 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005059 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005060 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005061 } else {
5062 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005063 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5064 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005065 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005066 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005067 }
Reid Kleckneree088972013-12-10 18:27:32 +00005068
5069 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005070 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5071 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005072 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005073 }
5074
5075 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005076 NumOutputs = OutputDecls.size();
5077 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005078
5079 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005080 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5081 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5082 ClobberRegs.end());
5083 Clobbers.assign(ClobberRegs.size(), std::string());
5084 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5085 raw_string_ostream OS(Clobbers[I]);
5086 IP->printRegName(OS, ClobberRegs[I]);
5087 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005088
5089 // Merge the various outputs and inputs. Output are expected first.
5090 if (NumOutputs || NumInputs) {
5091 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005092 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005093 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005094 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005095 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005096 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005097 }
5098 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005099 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005100 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005101 }
5102 }
5103
5104 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005105 std::string AsmStringIR;
5106 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005107 StringRef ASMString =
5108 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5109 const char *AsmStart = ASMString.begin();
5110 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005111 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005112 for (const AsmRewrite &AR : AsmStrRewrites) {
5113 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005114 if (Kind == AOK_Delete)
5115 continue;
5116
David Majnemer8114c1a2014-06-23 02:17:16 +00005117 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005118 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005119
Chad Rosier120eefd2013-03-19 17:32:17 +00005120 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005121 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005122 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005123
Chad Rosier37e755c2012-10-23 17:43:43 +00005124 // Skip the original expression.
5125 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005126 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005127 continue;
5128 }
5129
Chad Rosierff10ed12013-04-12 16:26:42 +00005130 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005131 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005132 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005133 default:
5134 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005135 case AOK_Imm:
David Majnemer8114c1a2014-06-23 02:17:16 +00005136 OS << "$$" << AR.Val;
Chad Rosier11c42f22012-10-26 18:04:20 +00005137 break;
5138 case AOK_ImmPrefix:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005139 OS << "$$";
Chad Rosier8bce6642012-10-18 15:49:34 +00005140 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005141 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005142 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005143 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005144 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005145 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005146 break;
5147 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005148 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005149 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005150 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005151 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005152 default: break;
5153 case 8: OS << "byte ptr "; break;
5154 case 16: OS << "word ptr "; break;
5155 case 32: OS << "dword ptr "; break;
5156 case 64: OS << "qword ptr "; break;
5157 case 80: OS << "xword ptr "; break;
5158 case 128: OS << "xmmword ptr "; break;
5159 case 256: OS << "ymmword ptr "; break;
5160 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005161 break;
5162 case AOK_Emit:
5163 OS << ".byte";
5164 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005165 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005166 // MS alignment directives are measured in bytes. If the native assembler
5167 // measures alignment in bytes, we can pass it straight through.
5168 OS << ".align";
5169 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5170 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005171
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005172 // Alignment is in log2 form, so print that instead and skip the original
5173 // immediate.
5174 unsigned Val = AR.Val;
5175 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005176 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005177 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5178 break;
5179 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005180 case AOK_EVEN:
5181 OS << ".even";
5182 break;
Chad Rosierf0e87202012-10-25 20:41:34 +00005183 case AOK_DotOperator:
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005184 // Insert the dot if the user omitted it.
Alp Tokere69170a2014-06-26 22:52:05 +00005185 OS.flush();
5186 if (AsmStringIR.back() != '.')
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005187 OS << '.';
David Majnemer8114c1a2014-06-23 02:17:16 +00005188 OS << AR.Val;
Chad Rosierf0e87202012-10-25 20:41:34 +00005189 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005190 case AOK_EndOfStatement:
5191 OS << "\n\t";
5192 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005193 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005194
Chad Rosier8bce6642012-10-18 15:49:34 +00005195 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005196 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005197 }
5198
5199 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005200 if (AsmStart != AsmEnd)
5201 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005202
5203 AsmString = OS.str();
5204 return false;
5205}
5206
Pete Cooper80d21cb2015-06-22 19:35:57 +00005207namespace llvm {
5208namespace MCParserUtils {
5209
5210/// Returns whether the given symbol is used anywhere in the given expression,
5211/// or subexpressions.
5212static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5213 switch (Value->getKind()) {
5214 case MCExpr::Binary: {
5215 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5216 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5217 isSymbolUsedInExpression(Sym, BE->getRHS());
5218 }
5219 case MCExpr::Target:
5220 case MCExpr::Constant:
5221 return false;
5222 case MCExpr::SymbolRef: {
5223 const MCSymbol &S =
5224 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5225 if (S.isVariable())
5226 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5227 return &S == Sym;
5228 }
5229 case MCExpr::Unary:
5230 return isSymbolUsedInExpression(
5231 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5232 }
5233
5234 llvm_unreachable("Unknown expr kind!");
5235}
5236
5237bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5238 MCAsmParser &Parser, MCSymbol *&Sym,
5239 const MCExpr *&Value) {
5240 MCAsmLexer &Lexer = Parser.getLexer();
5241
5242 // FIXME: Use better location, we should use proper tokens.
5243 SMLoc EqualLoc = Lexer.getLoc();
5244
5245 if (Parser.parseExpression(Value)) {
5246 Parser.TokError("missing expression");
5247 Parser.eatToEndOfStatement();
5248 return true;
5249 }
5250
5251 // Note: we don't count b as used in "a = b". This is to allow
5252 // a = b
5253 // b = c
5254
5255 if (Lexer.isNot(AsmToken::EndOfStatement))
5256 return Parser.TokError("unexpected token in assignment");
5257
5258 // Eat the end of statement marker.
5259 Parser.Lex();
5260
5261 // Validate that the LHS is allowed to be a variable (either it has not been
5262 // used as a symbol, or it is an absolute symbol).
5263 Sym = Parser.getContext().lookupSymbol(Name);
5264 if (Sym) {
5265 // Diagnose assignment to a label.
5266 //
5267 // FIXME: Diagnostics. Note the location of the definition as a label.
5268 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5269 if (isSymbolUsedInExpression(Sym, Value))
5270 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005271 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5272 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005273 ; // Allow redefinitions of undefined symbols only used in directives.
5274 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5275 ; // Allow redefinitions of variables that haven't yet been used.
5276 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5277 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5278 else if (!Sym->isVariable())
5279 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5280 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5281 return Parser.Error(EqualLoc,
5282 "invalid reassignment of non-absolute variable '" +
5283 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005284 } else if (Name == ".") {
Rafael Espindola7ae65d82015-11-04 23:59:18 +00005285 Parser.getStreamer().emitValueToOffset(Value, 0);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005286 return false;
5287 } else
5288 Sym = Parser.getContext().getOrCreateSymbol(Name);
5289
5290 Sym->setRedefinable(allow_redef);
5291
5292 return false;
5293}
5294
5295} // namespace MCParserUtils
5296} // namespace llvm
5297
Daniel Dunbar01e36072010-07-17 02:26:10 +00005298/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005299MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
5300 MCStreamer &Out, const MCAsmInfo &MAI) {
Jim Grosbach345768c2011-08-16 18:33:49 +00005301 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005302}