blob: 5b8c4ee5df19b75d48c264fdc091bc593de9a49b [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() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000627 if (Lexer.getTok().is(AsmToken::Error))
628 Error(Lexer.getErrLoc(), Lexer.getErr());
629
Sean Callanan7a77eae2010-01-21 00:19:58 +0000630 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000631
Sean Callanan7a77eae2010-01-21 00:19:58 +0000632 if (tok->is(AsmToken::Eof)) {
633 // If this is the end of an included file, pop the parent file off the
634 // include stack.
635 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
636 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000637 jumpToLoc(ParentIncludeLoc);
Sean Callanan7a77eae2010-01-21 00:19:58 +0000638 tok = &Lexer.Lex();
639 }
640 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000641
Michael J. Spencer530ce852010-10-09 11:00:50 +0000642
Sean Callanan7a77eae2010-01-21 00:19:58 +0000643 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000644}
645
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000646bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000647 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000648 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000649 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000650
Chris Lattner36e02122009-06-21 20:54:55 +0000651 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000652 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000653
654 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000655 AsmCond StartingCondState = TheCondState;
656
Kevin Enderby6469fc22011-11-01 22:27:22 +0000657 // If we are generating dwarf for assembly source files save the initial text
658 // section and generate a .file directive.
659 if (getContext().getGenDwarfForAssembly()) {
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000660 MCSection *Sec = getStreamer().getCurrentSection().first;
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000661 if (!Sec->getBeginSymbol()) {
662 MCSymbol *SectionStartSym = getContext().createTempSymbol();
663 getStreamer().EmitLabel(SectionStartSym);
664 Sec->setBeginSymbol(SectionStartSym);
665 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000666 bool InsertResult = getContext().addGenDwarfSection(Sec);
667 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000668 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000669 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
670 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000671 }
672
Chris Lattner73f36112009-07-02 21:53:43 +0000673 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000674 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman0f4871d2012-10-22 23:58:19 +0000675 ParseStatementInfo Info;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000676 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000677 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000678
Nirav Dave1180e6892016-06-02 17:15:05 +0000679 // If we've failed, but on a Error Token, but did not consume it in
680 // favor of a better message, emit it now.
681 if (Lexer.getTok().is(AsmToken::Error)) {
682 Lex();
683 }
684
Daniel Dunbar43325c42010-09-09 22:42:56 +0000685 // We had an error, validate that one was emitted and recover by skipping to
686 // the next line.
687 assert(HadError && "Parse statement returned an error, but none emitted!");
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000688 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000689 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000690
691 if (TheCondState.TheCond != StartingCondState.TheCond ||
692 TheCondState.Ignore != StartingCondState.Ignore)
693 return TokError("unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000694
695 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000696 const auto &LineTables = getContext().getMCDwarfLineTables();
697 if (!LineTables.empty()) {
698 unsigned Index = 0;
699 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
700 if (File.Name.empty() && Index != 0)
701 TokError("unassigned file number: " + Twine(Index) +
702 " for .file directives");
703 ++Index;
704 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000705 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000706
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000707 // Check to see that all assembler local symbols were actually defined.
708 // Targets that don't do subsections via symbols may not want this, though,
709 // so conservatively exclude them. Only do this if we're finalizing, though,
710 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000711 if (!NoFinalize) {
712 if (MAI.hasSubsectionsViaSymbols()) {
713 for (const auto &TableEntry : getContext().getSymbols()) {
714 MCSymbol *Sym = TableEntry.getValue();
715 // Variable symbols may not be marked as defined, so check those
716 // explicitly. If we know it's a variable, we have a definition for
717 // the purposes of this check.
718 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
719 // FIXME: We would really like to refer back to where the symbol was
720 // first referenced for a source location. We need to add something
721 // to track that. Currently, we just point to the end of the file.
722 HadError |=
723 Error(getLexer().getLoc(), "assembler local symbol '" +
724 Sym->getName() + "' not defined");
725 }
726 }
727
728 // Temporary symbols like the ones for directional jumps don't go in the
729 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000730 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
731 if (std::get<2>(LocSym)->isUndefined()) {
732 // Reset the state of any "# line file" directives we've seen to the
733 // context as it was at the diagnostic site.
734 CppHashInfo = std::get<1>(LocSym);
735 HadError |= Error(std::get<0>(LocSym), "directional label undefined");
736 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000737 }
738 }
739
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000740 // Finalize the output stream if there are no errors and if the client wants
741 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000742 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000743 Out.Finish();
744
Oliver Stannard07b43d32015-11-17 09:58:07 +0000745 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000746}
747
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000748void AsmParser::checkForValidSection() {
Peter Collingbourne2f495b92013-04-17 21:18:16 +0000749 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
Daniel Dunbare5444a82010-09-09 22:42:59 +0000750 TokError("expected section directive before assembly directive");
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000751 Out.InitSections(false);
Daniel Dunbare5444a82010-09-09 22:42:59 +0000752 }
753}
754
Jim Grosbach4b905842013-09-20 23:08:21 +0000755/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000756void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000757 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000758 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000759
Chris Lattnere5074c42009-06-22 01:29:09 +0000760 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000761 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000762 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000763}
764
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000765StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000766 const char *Start = getTok().getLoc().getPointer();
767
Jim Grosbach4b905842013-09-20 23:08:21 +0000768 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000769 Lex();
770
771 const char *End = getTok().getLoc().getPointer();
772 return StringRef(Start, End - Start);
773}
Chris Lattner78db3622009-06-22 05:51:26 +0000774
Jim Grosbach4b905842013-09-20 23:08:21 +0000775StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000776 const char *Start = getTok().getLoc().getPointer();
777
778 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000779 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000780 Lex();
781
782 const char *End = getTok().getLoc().getPointer();
783 return StringRef(Start, End - Start);
784}
785
Jim Grosbach4b905842013-09-20 23:08:21 +0000786/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000787/// NOTE: This assumes the leading '(' has already been consumed.
788///
789/// parenexpr ::= expr)
790///
Jim Grosbach4b905842013-09-20 23:08:21 +0000791bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
792 if (parseExpression(Res))
793 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000794 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +0000795 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000796 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000797 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +0000798 return false;
799}
Chris Lattner78db3622009-06-22 05:51:26 +0000800
Jim Grosbach4b905842013-09-20 23:08:21 +0000801/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000802/// NOTE: This assumes the leading '[' has already been consumed.
803///
804/// bracketexpr ::= expr]
805///
Jim Grosbach4b905842013-09-20 23:08:21 +0000806bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
807 if (parseExpression(Res))
808 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000809 if (Lexer.isNot(AsmToken::RBrac))
810 return TokError("expected ']' in brackets expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000811 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000812 Lex();
813 return false;
814}
815
Jim Grosbach4b905842013-09-20 23:08:21 +0000816/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000817/// primaryexpr ::= (parenexpr
818/// primaryexpr ::= symbol
819/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +0000820/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +0000821/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +0000822bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000823 SMLoc FirstTokenLoc = getLexer().getLoc();
824 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
825 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +0000826 default:
827 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +0000828 // If we have an error assume that we've already handled it.
829 case AsmToken::Error:
830 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000831 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000832 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000833 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000834 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000835 Res = MCUnaryExpr::createLNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000836 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +0000837 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +0000838 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +0000839 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +0000840 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +0000841 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000842 if (parseIdentifier(Identifier)) {
David Majnemer0c58bc62013-09-25 10:47:21 +0000843 if (FirstTokenKind == AsmToken::Dollar) {
844 if (Lexer.getMAI().getDollarIsPC()) {
845 // This is a '$' reference, which references the current PC. Emit a
846 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000847 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +0000848 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000849 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +0000850 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +0000851 EndLoc = FirstTokenLoc;
852 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +0000853 }
854 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +0000855 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000856 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000857 // Parse symbol variant
858 std::pair<StringRef, StringRef> Split;
859 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +0000860 if (FirstTokenKind == AsmToken::String) {
861 if (Lexer.is(AsmToken::At)) {
862 Lexer.Lex(); // eat @
863 SMLoc AtLoc = getLexer().getLoc();
864 StringRef VName;
865 if (parseIdentifier(VName))
866 return Error(AtLoc, "expected symbol variant after '@'");
867
868 Split = std::make_pair(Identifier, VName);
869 }
870 } else {
871 Split = Identifier.split('@');
872 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000873 } else if (Lexer.is(AsmToken::LParen)) {
874 Lexer.Lex(); // eat (
875 StringRef VName;
876 parseIdentifier(VName);
877 if (Lexer.isNot(AsmToken::RParen)) {
878 return Error(Lexer.getTok().getLoc(),
879 "unexpected token in variant, expected ')'");
880 }
881 Lexer.Lex(); // eat )
882 Split = std::make_pair(Identifier, VName);
883 }
Daniel Dunbar24764322010-08-24 19:13:42 +0000884
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000885 EndLoc = SMLoc::getFromPointer(Identifier.end());
886
Daniel Dunbard20cda02009-10-16 01:34:54 +0000887 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +0000888 StringRef SymbolName = Identifier;
889 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +0000890
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000891 // Lookup the symbol variant if used.
David Peixotto8ad70b32013-12-04 22:43:20 +0000892 if (Split.second.size()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000893 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +0000894 if (Variant != MCSymbolRefExpr::VK_Invalid) {
895 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +0000896 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +0000897 Variant = MCSymbolRefExpr::VK_None;
898 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +0000899 return Error(SMLoc::getFromPointer(Split.second.begin()),
900 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000901 }
902 }
Daniel Dunbar55992562010-03-15 23:51:06 +0000903
Jim Grosbach6f482002015-05-18 18:43:14 +0000904 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +0000905
Daniel Dunbard20cda02009-10-16 01:34:54 +0000906 // If this is an absolute variable reference, substitute it now to preserve
907 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +0000908 if (Sym->isVariable() &&
909 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +0000910 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +0000911 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +0000912
Vedant Kumar86dbd922015-08-31 17:44:53 +0000913 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +0000914 return false;
915 }
916
917 // Otherwise create a symbol ref.
Jim Grosbach13760bd2015-05-30 01:25:56 +0000918 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Chris Lattner78db3622009-06-22 05:51:26 +0000919 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +0000920 }
David Woodhousef42a6662014-02-01 16:20:54 +0000921 case AsmToken::BigNum:
922 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +0000923 case AsmToken::Integer: {
924 SMLoc Loc = getTok().getLoc();
925 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +0000926 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000927 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000928 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +0000929 // Look for 'b' or 'f' following an Integer as a directional label
930 if (Lexer.getKind() == AsmToken::Identifier) {
931 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +0000932 // Lookup the symbol variant if used.
933 std::pair<StringRef, StringRef> Split = IDVal.split('@');
934 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
935 if (Split.first.size() != IDVal.size()) {
936 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +0000937 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +0000938 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000939 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +0000940 }
Jim Grosbach4b905842013-09-20 23:08:21 +0000941 if (IDVal == "f" || IDVal == "b") {
942 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +0000943 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +0000944 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +0000945 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +0000946 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000947 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000948 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +0000949 Lex(); // Eat identifier.
950 }
951 }
Chris Lattner78db3622009-06-22 05:51:26 +0000952 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +0000953 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +0000954 case AsmToken::Real: {
955 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +0000956 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +0000957 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000958 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +0000959 Lex(); // Eat token.
960 return false;
961 }
Chris Lattner6b55cb92010-04-14 04:40:28 +0000962 case AsmToken::Dot: {
963 // This is a '.' reference, which references the current PC. Emit a
964 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000965 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +0000966 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000967 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000968 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +0000969 Lex(); // Eat identifier.
970 return false;
971 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000972 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000973 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +0000974 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000975 case AsmToken::LBrac:
976 if (!PlatformParser->HasBracketExpressions())
977 return TokError("brackets expression not supported on this target");
978 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +0000979 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000980 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000981 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000982 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000983 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000984 Res = MCUnaryExpr::createMinus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000985 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000986 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000987 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000988 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000989 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000990 Res = MCUnaryExpr::createPlus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000991 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000992 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000993 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000994 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000995 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000996 Res = MCUnaryExpr::createNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000997 return false;
Chris Lattner78db3622009-06-22 05:51:26 +0000998 }
999}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001000
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001001bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001002 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001003 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001004}
1005
Daniel Dunbar55f16672010-09-17 02:47:07 +00001006const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001007AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001008 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001009 // Ask the target implementation about this expression first.
1010 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1011 if (NewE)
1012 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001013 // Recurse over the given expression, rebuilding it to apply the given variant
1014 // if there is exactly one symbol.
1015 switch (E->getKind()) {
1016 case MCExpr::Target:
1017 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001018 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001019
1020 case MCExpr::SymbolRef: {
1021 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1022
1023 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001024 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1025 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001026 return E;
1027 }
1028
Jim Grosbach13760bd2015-05-30 01:25:56 +00001029 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001030 }
1031
1032 case MCExpr::Unary: {
1033 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001034 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001035 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001036 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001037 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001038 }
1039
1040 case MCExpr::Binary: {
1041 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001042 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1043 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001044
1045 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001046 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001047
Jim Grosbach4b905842013-09-20 23:08:21 +00001048 if (!LHS)
1049 LHS = BE->getLHS();
1050 if (!RHS)
1051 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001052
Jim Grosbach13760bd2015-05-30 01:25:56 +00001053 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001054 }
1055 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001056
Craig Toppera2886c22012-02-07 05:05:23 +00001057 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001058}
1059
Jim Grosbach4b905842013-09-20 23:08:21 +00001060/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001061///
Jim Grosbachbd164242011-08-20 16:24:13 +00001062/// expr ::= expr &&,|| expr -> lowest.
1063/// expr ::= expr |,^,&,! expr
1064/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1065/// expr ::= expr <<,>> expr
1066/// expr ::= expr +,- expr
1067/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001068/// expr ::= primaryexpr
1069///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001070bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001071 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001072 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001073 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001074 return true;
1075
Daniel Dunbar55f16672010-09-17 02:47:07 +00001076 // As a special case, we support 'a op b @ modifier' by rewriting the
1077 // expression to include the modifier. This is inefficient, but in general we
1078 // expect users to use 'a@modifier op b'.
1079 if (Lexer.getKind() == AsmToken::At) {
1080 Lex();
1081
1082 if (Lexer.isNot(AsmToken::Identifier))
1083 return TokError("unexpected symbol modifier following '@'");
1084
1085 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001086 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001087 if (Variant == MCSymbolRefExpr::VK_Invalid)
1088 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1089
Jim Grosbach4b905842013-09-20 23:08:21 +00001090 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001091 if (!ModifiedRes) {
1092 return TokError("invalid modifier '" + getTok().getIdentifier() +
1093 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001094 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001095
Daniel Dunbar55f16672010-09-17 02:47:07 +00001096 Res = ModifiedRes;
1097 Lex();
1098 }
1099
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001100 // Try to constant fold it up front, if possible.
1101 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001102 if (Res->evaluateAsAbsolute(Value))
1103 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001104
1105 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001106}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001107
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001108bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001109 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001110 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001111}
1112
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001113bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1114 SMLoc &EndLoc) {
1115 if (parseParenExpr(Res, EndLoc))
1116 return true;
1117
1118 for (; ParenDepth > 0; --ParenDepth) {
1119 if (parseBinOpRHS(1, Res, EndLoc))
1120 return true;
1121
1122 // We don't Lex() the last RParen.
1123 // This is the same behavior as parseParenExpression().
1124 if (ParenDepth - 1 > 0) {
1125 if (Lexer.isNot(AsmToken::RParen))
1126 return TokError("expected ')' in parentheses expression");
1127 EndLoc = Lexer.getTok().getEndLoc();
1128 Lex();
1129 }
1130 }
1131 return false;
1132}
1133
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001134bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001135 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001136
Daniel Dunbar75630b32009-06-30 02:10:03 +00001137 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001138 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001139 return true;
1140
Jim Grosbach13760bd2015-05-30 01:25:56 +00001141 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001142 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001143
1144 return false;
1145}
1146
David Majnemer0993e0b2015-10-26 03:15:34 +00001147static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1148 MCBinaryExpr::Opcode &Kind,
1149 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001150 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001151 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001152 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001153
Jim Grosbach4b905842013-09-20 23:08:21 +00001154 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001155 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001156 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001157 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001158 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001159 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001160 return 1;
1161
Jim Grosbach4b905842013-09-20 23:08:21 +00001162 // Low Precedence: |, &, ^
1163 //
1164 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001165 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001166 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001167 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001168 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001169 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001170 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001171 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001172 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001173 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001174
Jim Grosbach4b905842013-09-20 23:08:21 +00001175 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001176 case AsmToken::EqualEqual:
1177 Kind = MCBinaryExpr::EQ;
1178 return 3;
1179 case AsmToken::ExclaimEqual:
1180 case AsmToken::LessGreater:
1181 Kind = MCBinaryExpr::NE;
1182 return 3;
1183 case AsmToken::Less:
1184 Kind = MCBinaryExpr::LT;
1185 return 3;
1186 case AsmToken::LessEqual:
1187 Kind = MCBinaryExpr::LTE;
1188 return 3;
1189 case AsmToken::Greater:
1190 Kind = MCBinaryExpr::GT;
1191 return 3;
1192 case AsmToken::GreaterEqual:
1193 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001194 return 3;
1195
Jim Grosbach4b905842013-09-20 23:08:21 +00001196 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001197 case AsmToken::LessLess:
1198 Kind = MCBinaryExpr::Shl;
1199 return 4;
1200 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001201 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001202 return 4;
1203
Jim Grosbach4b905842013-09-20 23:08:21 +00001204 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001205 case AsmToken::Plus:
1206 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001207 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001208 case AsmToken::Minus:
1209 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001210 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001211
Jim Grosbach4b905842013-09-20 23:08:21 +00001212 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001213 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001214 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001215 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001216 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001217 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001218 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001219 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001220 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001221 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001222 }
1223}
1224
David Majnemer0993e0b2015-10-26 03:15:34 +00001225static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1226 MCBinaryExpr::Opcode &Kind,
1227 bool ShouldUseLogicalShr) {
1228 switch (K) {
1229 default:
1230 return 0; // not a binop.
1231
1232 // Lowest Precedence: &&, ||
1233 case AsmToken::AmpAmp:
1234 Kind = MCBinaryExpr::LAnd;
1235 return 2;
1236 case AsmToken::PipePipe:
1237 Kind = MCBinaryExpr::LOr;
1238 return 1;
1239
1240 // Low Precedence: ==, !=, <>, <, <=, >, >=
1241 case AsmToken::EqualEqual:
1242 Kind = MCBinaryExpr::EQ;
1243 return 3;
1244 case AsmToken::ExclaimEqual:
1245 case AsmToken::LessGreater:
1246 Kind = MCBinaryExpr::NE;
1247 return 3;
1248 case AsmToken::Less:
1249 Kind = MCBinaryExpr::LT;
1250 return 3;
1251 case AsmToken::LessEqual:
1252 Kind = MCBinaryExpr::LTE;
1253 return 3;
1254 case AsmToken::Greater:
1255 Kind = MCBinaryExpr::GT;
1256 return 3;
1257 case AsmToken::GreaterEqual:
1258 Kind = MCBinaryExpr::GTE;
1259 return 3;
1260
1261 // Low Intermediate Precedence: +, -
1262 case AsmToken::Plus:
1263 Kind = MCBinaryExpr::Add;
1264 return 4;
1265 case AsmToken::Minus:
1266 Kind = MCBinaryExpr::Sub;
1267 return 4;
1268
1269 // High Intermediate Precedence: |, &, ^
1270 //
1271 // FIXME: gas seems to support '!' as an infix operator?
1272 case AsmToken::Pipe:
1273 Kind = MCBinaryExpr::Or;
1274 return 5;
1275 case AsmToken::Caret:
1276 Kind = MCBinaryExpr::Xor;
1277 return 5;
1278 case AsmToken::Amp:
1279 Kind = MCBinaryExpr::And;
1280 return 5;
1281
1282 // Highest Precedence: *, /, %, <<, >>
1283 case AsmToken::Star:
1284 Kind = MCBinaryExpr::Mul;
1285 return 6;
1286 case AsmToken::Slash:
1287 Kind = MCBinaryExpr::Div;
1288 return 6;
1289 case AsmToken::Percent:
1290 Kind = MCBinaryExpr::Mod;
1291 return 6;
1292 case AsmToken::LessLess:
1293 Kind = MCBinaryExpr::Shl;
1294 return 6;
1295 case AsmToken::GreaterGreater:
1296 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1297 return 6;
1298 }
1299}
1300
1301unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1302 MCBinaryExpr::Opcode &Kind) {
1303 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1304 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1305 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1306}
1307
Jim Grosbach4b905842013-09-20 23:08:21 +00001308/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001309/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001310bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001311 SMLoc &EndLoc) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001312 while (1) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001313 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001314 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001315
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001316 // If the next token is lower precedence than we are allowed to eat, return
1317 // successfully with what we ate already.
1318 if (TokPrec < Precedence)
1319 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001320
Sean Callanan686ed8d2010-01-19 20:22:31 +00001321 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001322
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001323 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001324 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001325 if (parsePrimaryExpr(RHS, EndLoc))
1326 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001327
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001328 // If BinOp binds less tightly with RHS than the operator after RHS, let
1329 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001330 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001331 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001332 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1333 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001334
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001335 // Merge LHS and RHS according to operator.
Jim Grosbach13760bd2015-05-30 01:25:56 +00001336 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001337 }
1338}
1339
Chris Lattner36e02122009-06-21 20:54:55 +00001340/// ParseStatement:
1341/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001342/// ::= Label* Directive ...Operands... EndOfStatement
1343/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001344bool AsmParser::parseStatement(ParseStatementInfo &Info,
1345 MCAsmParserSemaCallback *SI) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001346 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar8271d1bb2010-05-23 18:36:34 +00001347 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001348 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001349 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001350 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001351
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001352 // Statements always start with an identifier or are a full line comment.
Sean Callanan936b0d32010-01-19 21:44:56 +00001353 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001354 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001355 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001356 int64_t LocalLabelVal = -1;
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001357 // A full line comment is a '#' as the first token.
Kevin Enderby72553612011-09-13 23:45:18 +00001358 if (Lexer.is(AsmToken::Hash))
Jim Grosbach4b905842013-09-20 23:08:21 +00001359 return parseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar3f561042011-03-25 17:47:14 +00001360
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001361 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001362 if (Lexer.is(AsmToken::Integer)) {
1363 LocalLabelVal = getTok().getIntVal();
1364 if (LocalLabelVal < 0) {
1365 if (!TheCondState.Ignore)
1366 return TokError("unexpected token at start of statement");
1367 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001368 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001369 IDVal = getTok().getString();
1370 Lex(); // Consume the integer token to be used as an identifier token.
1371 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands41b4a6b2010-07-12 08:16:59 +00001372 if (!TheCondState.Ignore)
1373 return TokError("unexpected token at start of statement");
Kevin Enderby0510b482010-05-17 23:08:19 +00001374 }
1375 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001376 } else if (Lexer.is(AsmToken::Dot)) {
1377 // Treat '.' as a valid identifier in this context.
1378 Lex();
1379 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001380 } else if (Lexer.is(AsmToken::LCurly)) {
1381 // Treat '{' as a valid identifier in this context.
1382 Lex();
1383 IDVal = "{";
1384
1385 } else if (Lexer.is(AsmToken::RCurly)) {
1386 // Treat '}' as a valid identifier in this context.
1387 Lex();
1388 IDVal = "}";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001389 } else if (parseIdentifier(IDVal)) {
Chris Lattner926885c2010-04-17 18:14:27 +00001390 if (!TheCondState.Ignore)
1391 return TokError("unexpected token at start of statement");
1392 IDVal = "";
1393 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001394
Chris Lattner926885c2010-04-17 18:14:27 +00001395 // Handle conditional assembly here before checking for skipping. We
1396 // have to do this so that .endif isn't skipped in a ".if 0" block for
1397 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001398 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001399 DirectiveKindMap.find(IDVal);
1400 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1401 ? DK_NO_DIRECTIVE
1402 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001403 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001404 default:
1405 break;
1406 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001407 case DK_IFEQ:
1408 case DK_IFGE:
1409 case DK_IFGT:
1410 case DK_IFLE:
1411 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001412 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001413 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001414 case DK_IFB:
1415 return parseDirectiveIfb(IDLoc, true);
1416 case DK_IFNB:
1417 return parseDirectiveIfb(IDLoc, false);
1418 case DK_IFC:
1419 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001420 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001421 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001422 case DK_IFNC:
1423 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001424 case DK_IFNES:
1425 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001426 case DK_IFDEF:
1427 return parseDirectiveIfdef(IDLoc, true);
1428 case DK_IFNDEF:
1429 case DK_IFNOTDEF:
1430 return parseDirectiveIfdef(IDLoc, false);
1431 case DK_ELSEIF:
1432 return parseDirectiveElseIf(IDLoc);
1433 case DK_ELSE:
1434 return parseDirectiveElse(IDLoc);
1435 case DK_ENDIF:
1436 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001437 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001438
Eli Bendersky88024712013-01-16 19:32:36 +00001439 // Ignore the statement if in the middle of inactive conditional
1440 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001441 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001442 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001443 return false;
1444 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001445
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001446 // FIXME: Recurse on local labels?
1447
1448 // See what kind of statement we have.
1449 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001450 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001451 if (!getTargetParser().isLabel(ID))
1452 break;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001453 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00001454
Chris Lattner36e02122009-06-21 20:54:55 +00001455 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001456 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001457
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001458 // Diagnose attempt to use '.' as a label.
1459 if (IDVal == ".")
1460 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1461
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001462 // Diagnose attempt to use a variable as a label.
1463 //
1464 // FIXME: Diagnostics. Note the location of the definition as a label.
1465 // FIXME: This doesn't diagnose assignment to a symbol which has been
1466 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001467 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001468 if (LocalLabelVal == -1) {
1469 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001470 StringRef RewrittenLabel =
1471 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1472 assert(RewrittenLabel.size() &&
1473 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001474 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1475 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001476 IDVal = RewrittenLabel;
1477 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001478 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001479 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001480 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
David Majnemer58cb80c2014-12-24 10:27:50 +00001481
1482 Sym->redefineIfPossible();
1483
Daniel Dunbardeb7ba92010-05-05 19:01:00 +00001484 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001485 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencer530ce852010-10-09 11:00:50 +00001486
Daniel Dunbare73b2672009-08-26 22:13:22 +00001487 // Emit the label.
Chad Rosierf3feab32013-01-07 20:34:12 +00001488 if (!ParsingInlineAsm)
1489 Out.EmitLabel(Sym);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001490
Kevin Enderbye7739d42011-12-09 18:09:40 +00001491 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001492 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001493 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001494 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1495 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001496
Tim Northover1744d0a2013-10-25 12:49:50 +00001497 getTargetParser().onLabelParsed(Sym);
1498
Daniel Dunbar8271d1bb2010-05-23 18:36:34 +00001499 // Consume any end of statement token, if present, to avoid spurious
1500 // AddBlankLine calls().
1501 if (Lexer.is(AsmToken::EndOfStatement)) {
1502 Lex();
1503 if (Lexer.is(AsmToken::Eof))
1504 return false;
1505 }
1506
Eli Friedman0f4871d2012-10-22 23:58:19 +00001507 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001508 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001509
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001510 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001511 if (!getTargetParser().equalIsAsmAssignment())
1512 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001513 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001514 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001515
Jim Grosbach4b905842013-09-20 23:08:21 +00001516 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001517
1518 default: // Normal instruction or directive.
1519 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001520 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001521
1522 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001523 if (areMacrosEnabled())
1524 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1525 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001526 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001527
Michael J. Spencer530ce852010-10-09 11:00:50 +00001528 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001529
Eli Bendersky17233942013-01-15 22:59:42 +00001530 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001531 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001532 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001533 //
Eli Bendersky17233942013-01-15 22:59:42 +00001534 // 1. The target-specific assembly parser. Some directives are target
1535 // specific or may potentially behave differently on certain targets.
1536 // 2. Asm parser extensions. For example, platform-specific parsers
1537 // (like the ELF parser) register themselves as extensions.
1538 // 3. The generic directive parser implemented by this class. These are
1539 // all the directives that behave in a target and platform independent
1540 // manner, or at least have a default behavior that's shared between
1541 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001542
Eli Bendersky17233942013-01-15 22:59:42 +00001543 // First query the target-specific parser. It will return 'true' if it
1544 // isn't interested in this directive.
Akira Hatanakad3590752012-07-05 19:09:33 +00001545 if (!getTargetParser().ParseDirective(ID))
1546 return false;
1547
Alp Tokercb402912014-01-24 17:20:08 +00001548 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001549 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001550 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1551 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001552 if (Handler.first)
1553 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1554
1555 // Finally, if no one else is interested in this directive, it must be
1556 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001557 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001558 default:
1559 break;
1560 case DK_SET:
1561 case DK_EQU:
1562 return parseDirectiveSet(IDVal, true);
1563 case DK_EQUIV:
1564 return parseDirectiveSet(IDVal, false);
1565 case DK_ASCII:
1566 return parseDirectiveAscii(IDVal, false);
1567 case DK_ASCIZ:
1568 case DK_STRING:
1569 return parseDirectiveAscii(IDVal, true);
1570 case DK_BYTE:
1571 return parseDirectiveValue(1);
1572 case DK_SHORT:
1573 case DK_VALUE:
1574 case DK_2BYTE:
1575 return parseDirectiveValue(2);
1576 case DK_LONG:
1577 case DK_INT:
1578 case DK_4BYTE:
1579 return parseDirectiveValue(4);
1580 case DK_QUAD:
1581 case DK_8BYTE:
1582 return parseDirectiveValue(8);
David Woodhoused6de0d92014-02-01 16:20:59 +00001583 case DK_OCTA:
1584 return parseDirectiveOctaValue();
Jim Grosbach4b905842013-09-20 23:08:21 +00001585 case DK_SINGLE:
1586 case DK_FLOAT:
1587 return parseDirectiveRealValue(APFloat::IEEEsingle);
1588 case DK_DOUBLE:
1589 return parseDirectiveRealValue(APFloat::IEEEdouble);
1590 case DK_ALIGN: {
1591 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1592 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1593 }
1594 case DK_ALIGN32: {
1595 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1596 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1597 }
1598 case DK_BALIGN:
1599 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1600 case DK_BALIGNW:
1601 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1602 case DK_BALIGNL:
1603 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1604 case DK_P2ALIGN:
1605 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1606 case DK_P2ALIGNW:
1607 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1608 case DK_P2ALIGNL:
1609 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1610 case DK_ORG:
1611 return parseDirectiveOrg();
1612 case DK_FILL:
1613 return parseDirectiveFill();
1614 case DK_ZERO:
1615 return parseDirectiveZero();
1616 case DK_EXTERN:
1617 eatToEndOfStatement(); // .extern is the default, ignore it.
1618 return false;
1619 case DK_GLOBL:
1620 case DK_GLOBAL:
1621 return parseDirectiveSymbolAttribute(MCSA_Global);
1622 case DK_LAZY_REFERENCE:
1623 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1624 case DK_NO_DEAD_STRIP:
1625 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1626 case DK_SYMBOL_RESOLVER:
1627 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1628 case DK_PRIVATE_EXTERN:
1629 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1630 case DK_REFERENCE:
1631 return parseDirectiveSymbolAttribute(MCSA_Reference);
1632 case DK_WEAK_DEFINITION:
1633 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1634 case DK_WEAK_REFERENCE:
1635 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1636 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1637 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1638 case DK_COMM:
1639 case DK_COMMON:
1640 return parseDirectiveComm(/*IsLocal=*/false);
1641 case DK_LCOMM:
1642 return parseDirectiveComm(/*IsLocal=*/true);
1643 case DK_ABORT:
1644 return parseDirectiveAbort();
1645 case DK_INCLUDE:
1646 return parseDirectiveInclude();
1647 case DK_INCBIN:
1648 return parseDirectiveIncbin();
1649 case DK_CODE16:
1650 case DK_CODE16GCC:
1651 return TokError(Twine(IDVal) + " not supported yet");
1652 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001653 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001654 case DK_IRP:
1655 return parseDirectiveIrp(IDLoc);
1656 case DK_IRPC:
1657 return parseDirectiveIrpc(IDLoc);
1658 case DK_ENDR:
1659 return parseDirectiveEndr(IDLoc);
1660 case DK_BUNDLE_ALIGN_MODE:
1661 return parseDirectiveBundleAlignMode();
1662 case DK_BUNDLE_LOCK:
1663 return parseDirectiveBundleLock();
1664 case DK_BUNDLE_UNLOCK:
1665 return parseDirectiveBundleUnlock();
1666 case DK_SLEB128:
1667 return parseDirectiveLEB128(true);
1668 case DK_ULEB128:
1669 return parseDirectiveLEB128(false);
1670 case DK_SPACE:
1671 case DK_SKIP:
1672 return parseDirectiveSpace(IDVal);
1673 case DK_FILE:
1674 return parseDirectiveFile(IDLoc);
1675 case DK_LINE:
1676 return parseDirectiveLine();
1677 case DK_LOC:
1678 return parseDirectiveLoc();
1679 case DK_STABS:
1680 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001681 case DK_CV_FILE:
1682 return parseDirectiveCVFile();
1683 case DK_CV_LOC:
1684 return parseDirectiveCVLoc();
1685 case DK_CV_LINETABLE:
1686 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00001687 case DK_CV_INLINE_LINETABLE:
1688 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00001689 case DK_CV_DEF_RANGE:
1690 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001691 case DK_CV_STRINGTABLE:
1692 return parseDirectiveCVStringTable();
1693 case DK_CV_FILECHECKSUMS:
1694 return parseDirectiveCVFileChecksums();
Jim Grosbach4b905842013-09-20 23:08:21 +00001695 case DK_CFI_SECTIONS:
1696 return parseDirectiveCFISections();
1697 case DK_CFI_STARTPROC:
1698 return parseDirectiveCFIStartProc();
1699 case DK_CFI_ENDPROC:
1700 return parseDirectiveCFIEndProc();
1701 case DK_CFI_DEF_CFA:
1702 return parseDirectiveCFIDefCfa(IDLoc);
1703 case DK_CFI_DEF_CFA_OFFSET:
1704 return parseDirectiveCFIDefCfaOffset();
1705 case DK_CFI_ADJUST_CFA_OFFSET:
1706 return parseDirectiveCFIAdjustCfaOffset();
1707 case DK_CFI_DEF_CFA_REGISTER:
1708 return parseDirectiveCFIDefCfaRegister(IDLoc);
1709 case DK_CFI_OFFSET:
1710 return parseDirectiveCFIOffset(IDLoc);
1711 case DK_CFI_REL_OFFSET:
1712 return parseDirectiveCFIRelOffset(IDLoc);
1713 case DK_CFI_PERSONALITY:
1714 return parseDirectiveCFIPersonalityOrLsda(true);
1715 case DK_CFI_LSDA:
1716 return parseDirectiveCFIPersonalityOrLsda(false);
1717 case DK_CFI_REMEMBER_STATE:
1718 return parseDirectiveCFIRememberState();
1719 case DK_CFI_RESTORE_STATE:
1720 return parseDirectiveCFIRestoreState();
1721 case DK_CFI_SAME_VALUE:
1722 return parseDirectiveCFISameValue(IDLoc);
1723 case DK_CFI_RESTORE:
1724 return parseDirectiveCFIRestore(IDLoc);
1725 case DK_CFI_ESCAPE:
1726 return parseDirectiveCFIEscape();
1727 case DK_CFI_SIGNAL_FRAME:
1728 return parseDirectiveCFISignalFrame();
1729 case DK_CFI_UNDEFINED:
1730 return parseDirectiveCFIUndefined(IDLoc);
1731 case DK_CFI_REGISTER:
1732 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00001733 case DK_CFI_WINDOW_SAVE:
1734 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00001735 case DK_MACROS_ON:
1736 case DK_MACROS_OFF:
1737 return parseDirectiveMacrosOnOff(IDVal);
1738 case DK_MACRO:
1739 return parseDirectiveMacro(IDLoc);
Nico Weber155dccd12014-07-24 17:08:39 +00001740 case DK_EXITM:
1741 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001742 case DK_ENDM:
1743 case DK_ENDMACRO:
1744 return parseDirectiveEndMacro(IDVal);
1745 case DK_PURGEM:
1746 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00001747 case DK_END:
1748 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00001749 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00001750 return parseDirectiveError(IDLoc, false);
1751 case DK_ERROR:
1752 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00001753 case DK_WARNING:
1754 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00001755 case DK_RELOC:
1756 return parseDirectiveReloc(IDLoc);
Eli Friedman20b02642010-07-19 04:17:25 +00001757 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00001758
Jim Grosbach758e0cc2012-05-01 18:38:27 +00001759 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00001760 }
Chris Lattner36e02122009-06-21 20:54:55 +00001761
Chad Rosierc7f552c2013-02-12 21:33:51 +00001762 // __asm _emit or __asm __emit
1763 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1764 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001765 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00001766
1767 // __asm align
1768 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001769 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00001770
Michael Zuckerman02ecd432015-12-13 17:07:23 +00001771 if (ParsingInlineAsm && (IDVal == "even"))
1772 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001773 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00001774
Chris Lattner7cbfa442010-05-19 23:34:33 +00001775 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00001776 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00001777 ParseInstructionInfo IInfo(Info.AsmRewrites);
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001778 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001779 Info.ParsedOperands);
Chad Rosier149e8e02012-12-12 22:45:52 +00001780 Info.ParseError = HadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00001781
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001782 // Dump the parsed representation, if requested.
1783 if (getShowParsedOperands()) {
1784 SmallString<256> Str;
1785 raw_svector_ostream OS(Str);
1786 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001787 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001788 if (i != 0)
1789 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001790 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001791 }
1792 OS << "]";
1793
Jim Grosbach4b905842013-09-20 23:08:21 +00001794 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001795 }
1796
Oliver Stannard8b273082014-06-19 15:52:37 +00001797 // If we are generating dwarf for the current section then generate a .loc
1798 // directive for the instruction.
Kevin Enderby6469fc22011-11-01 22:27:22 +00001799 if (!HadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00001800 getContext().getGenDwarfSectionSyms().count(
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00001801 getStreamer().getCurrentSection().first)) {
1802 unsigned Line;
1803 if (ActiveMacros.empty())
1804 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1805 else
Frederic Riss16238d92015-06-25 21:57:33 +00001806 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
1807 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001808
Eli Bendersky88024712013-01-16 19:32:36 +00001809 // If we previously parsed a cpp hash file line comment then make sure the
1810 // current Dwarf File is for the CppHashFilename if not then emit the
1811 // Dwarf File table for it and adjust the line number for the .loc.
Tim Northoverc0bef992016-04-13 19:46:54 +00001812 if (CppHashInfo.Filename.size()) {
David Blaikiec714ef42014-03-17 01:52:11 +00001813 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00001814 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00001815 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001816
Jim Grosbach4b905842013-09-20 23:08:21 +00001817 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1818 // cache with the different Loc from the call above we save the last
1819 // info we queried here with SrcMgr.FindLineNumber().
1820 unsigned CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00001821 if (LastQueryIDLoc == CppHashInfo.Loc &&
1822 LastQueryBuffer == CppHashInfo.Buf)
Jim Grosbach4b905842013-09-20 23:08:21 +00001823 CppHashLocLineNo = LastQueryLine;
1824 else {
Tim Northoverc0bef992016-04-13 19:46:54 +00001825 CppHashLocLineNo =
1826 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Jim Grosbach4b905842013-09-20 23:08:21 +00001827 LastQueryLine = CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00001828 LastQueryIDLoc = CppHashInfo.Loc;
1829 LastQueryBuffer = CppHashInfo.Buf;
Jim Grosbach4b905842013-09-20 23:08:21 +00001830 }
Tim Northoverc0bef992016-04-13 19:46:54 +00001831 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00001832 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001833
Jim Grosbach4b905842013-09-20 23:08:21 +00001834 getStreamer().EmitDwarfLocDirective(
1835 getContext().getGenDwarfFileNumber(), Line, 0,
1836 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1837 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00001838 }
1839
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00001840 // If parsing succeeded, match the instruction.
Chad Rosier49963552012-10-13 00:26:04 +00001841 if (!HadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00001842 uint64_t ErrorInfo;
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001843 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1844 Info.ParsedOperands, Out,
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00001845 ErrorInfo, ParsingInlineAsm);
Chad Rosier49963552012-10-13 00:26:04 +00001846 }
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001847
Chris Lattnera2a9d162010-09-11 16:18:25 +00001848 // Don't skip the rest of the line, the instruction parser is responsible for
1849 // that.
1850 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00001851}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00001852
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00001853// Parse and erase curly braces marking block start/end
1854bool
1855AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
1856 // Identify curly brace marking block start/end
1857 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
1858 return false;
1859
1860 SMLoc StartLoc = Lexer.getLoc();
1861 Lex(); // Eat the brace
1862 if (Lexer.is(AsmToken::EndOfStatement))
1863 Lex(); // Eat EndOfStatement following the brace
1864
1865 // Erase the block start/end brace from the output asm string
1866 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
1867 StartLoc.getPointer());
1868 return true;
1869}
1870
Jim Grosbach4b905842013-09-20 23:08:21 +00001871/// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
Kevin Enderby72553612011-09-13 23:45:18 +00001872/// since they may not be able to be tokenized to get to the end of line token.
Jim Grosbach4b905842013-09-20 23:08:21 +00001873void AsmParser::eatToEndOfLine() {
Rafael Espindolae0d09082011-10-19 18:48:52 +00001874 if (!Lexer.is(AsmToken::EndOfStatement))
1875 Lexer.LexUntilEndOfLine();
Jim Grosbach4b905842013-09-20 23:08:21 +00001876 // Eat EOL.
1877 Lex();
Kevin Enderby72553612011-09-13 23:45:18 +00001878}
1879
Jim Grosbach4b905842013-09-20 23:08:21 +00001880/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00001881/// ::= # number "filename"
1882/// or just as a full line comment if it doesn't have a number and a string.
Craig Topper3c76c522015-09-20 23:35:59 +00001883bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00001884 Lex(); // Eat the hash token.
1885
1886 if (getLexer().isNot(AsmToken::Integer)) {
1887 // Consume the line since in cases it is not a well-formed line directive,
1888 // as if were simply a full line comment.
Jim Grosbach4b905842013-09-20 23:08:21 +00001889 eatToEndOfLine();
Kevin Enderby72553612011-09-13 23:45:18 +00001890 return false;
1891 }
1892
1893 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00001894 Lex();
1895
1896 if (getLexer().isNot(AsmToken::String)) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001897 eatToEndOfLine();
Kevin Enderby72553612011-09-13 23:45:18 +00001898 return false;
1899 }
1900
1901 StringRef Filename = getTok().getString();
1902 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00001903 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00001904
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001905 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00001906 CppHashInfo.Loc = L;
1907 CppHashInfo.Filename = Filename;
1908 CppHashInfo.LineNumber = LineNumber;
1909 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00001910
1911 // Ignore any trailing characters, they're just comment.
Jim Grosbach4b905842013-09-20 23:08:21 +00001912 eatToEndOfLine();
Kevin Enderby72553612011-09-13 23:45:18 +00001913 return false;
1914}
1915
Jim Grosbach4b905842013-09-20 23:08:21 +00001916/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001917/// for the Filename and LineNo if any in the diagnostic.
1918void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001919 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001920 raw_ostream &OS = errs();
1921
1922 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00001923 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00001924 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1925 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00001926 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001927
Jim Grosbach4b905842013-09-20 23:08:21 +00001928 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001929 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00001930 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1931 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1932 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001933 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1934 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001935 }
1936
Eric Christophera7c32732012-12-18 00:30:54 +00001937 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001938 // manager changed or buffer changed (like in a nested include) then just
1939 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00001940 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001941 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00001942 if (Parser->SavedDiagHandler)
1943 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1944 else
Craig Topper353eda42014-04-24 06:44:33 +00001945 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001946 return;
1947 }
1948
Eric Christophera7c32732012-12-18 00:30:54 +00001949 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00001950 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
1951 // for the diagnostic.
1952 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001953
1954 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1955 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00001956 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00001957 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00001958 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001959
Jim Grosbach4b905842013-09-20 23:08:21 +00001960 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1961 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00001962 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001963
Benjamin Kramer47f5e302011-10-16 10:48:29 +00001964 if (Parser->SavedDiagHandler)
1965 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1966 else
Craig Topper353eda42014-04-24 06:44:33 +00001967 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001968}
1969
Rafael Espindola2c064482012-08-21 18:29:30 +00001970// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1971// difference being that that function accepts '@' as part of identifiers and
1972// we can't do that. AsmLexer.cpp should probably be changed to handle
1973// '@' as a special case when needed.
1974static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001975 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1976 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00001977}
1978
Rafael Espindola34b9c512012-06-03 23:57:14 +00001979bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00001980 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00001981 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00001982 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00001983 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00001984 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00001985 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00001986 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001987
Preston Gurd05500642012-09-19 20:36:12 +00001988 // A macro without parameters is handled differently on Darwin:
1989 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001990 while (!Body.empty()) {
1991 // Scan for the next substitution.
1992 std::size_t End = Body.size(), Pos = 0;
1993 for (; Pos != End; ++Pos) {
1994 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00001995 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00001996 // This macro has no parameters, look for $0, $1, etc.
1997 if (Body[Pos] != '$' || Pos + 1 == End)
1998 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001999
Rafael Espindola1134ab232011-06-05 02:43:45 +00002000 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002001 if (Next == '$' || Next == 'n' ||
2002 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002003 break;
2004 } else {
2005 // This macro has parameters, look for \foo, \bar, etc.
2006 if (Body[Pos] == '\\' && Pos + 1 != End)
2007 break;
2008 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002009 }
2010
2011 // Add the prefix.
2012 OS << Body.slice(0, Pos);
2013
2014 // Check if we reached the end.
2015 if (Pos == End)
2016 break;
2017
Benjamin Kramer513e7442014-02-20 13:36:32 +00002018 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002019 switch (Body[Pos + 1]) {
2020 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002021 case '$':
2022 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002023 break;
2024
Jim Grosbach4b905842013-09-20 23:08:21 +00002025 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002026 case 'n':
2027 OS << A.size();
2028 break;
2029
Jim Grosbach4b905842013-09-20 23:08:21 +00002030 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002031 default: {
2032 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002033 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002034 if (Index >= A.size())
2035 break;
2036
2037 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002038 for (const AsmToken &Token : A[Index])
2039 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002040 break;
2041 }
2042 }
2043 Pos += 2;
2044 } else {
2045 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002046
2047 // Check for the \@ pseudo-variable.
2048 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002049 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002050 else
2051 while (isIdentifierChar(Body[I]) && I + 1 != End)
2052 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002053
Jim Grosbach4b905842013-09-20 23:08:21 +00002054 const char *Begin = Body.data() + Pos + 1;
2055 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002056 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002057
Toma Tabacu217116e2015-04-27 10:50:29 +00002058 if (Argument == "@") {
2059 OS << NumOfMacroInstantiations;
2060 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002061 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002062 for (; Index < NParameters; ++Index)
2063 if (Parameters[Index].Name == Argument)
2064 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002065
Toma Tabacu217116e2015-04-27 10:50:29 +00002066 if (Index == NParameters) {
2067 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2068 Pos += 3;
2069 else {
2070 OS << '\\' << Argument;
2071 Pos = I;
2072 }
2073 } else {
2074 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002075 for (const AsmToken &Token : A[Index])
Toma Tabacu217116e2015-04-27 10:50:29 +00002076 // We expect no quotes around the string's contents when
2077 // parsing for varargs.
Craig Topper84008482015-10-10 05:38:14 +00002078 if (Token.getKind() != AsmToken::String || VarargParameter)
2079 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002080 else
Craig Topper84008482015-10-10 05:38:14 +00002081 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002082
2083 Pos += 1 + Argument.size();
2084 }
Preston Gurd05500642012-09-19 20:36:12 +00002085 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002086 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002087 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002088 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002089 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002090
Rafael Espindola1134ab232011-06-05 02:43:45 +00002091 return false;
2092}
Daniel Dunbar43235712010-07-18 18:54:11 +00002093
Nico Weber2a8f9222014-07-24 16:29:04 +00002094MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002095 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002096 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002097 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002098
Jim Grosbach4b905842013-09-20 23:08:21 +00002099static bool isOperator(AsmToken::TokenKind kind) {
2100 switch (kind) {
2101 default:
2102 return false;
2103 case AsmToken::Plus:
2104 case AsmToken::Minus:
2105 case AsmToken::Tilde:
2106 case AsmToken::Slash:
2107 case AsmToken::Star:
2108 case AsmToken::Dot:
2109 case AsmToken::Equal:
2110 case AsmToken::EqualEqual:
2111 case AsmToken::Pipe:
2112 case AsmToken::PipePipe:
2113 case AsmToken::Caret:
2114 case AsmToken::Amp:
2115 case AsmToken::AmpAmp:
2116 case AsmToken::Exclaim:
2117 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002118 case AsmToken::Less:
2119 case AsmToken::LessEqual:
2120 case AsmToken::LessLess:
2121 case AsmToken::LessGreater:
2122 case AsmToken::Greater:
2123 case AsmToken::GreaterEqual:
2124 case AsmToken::GreaterGreater:
2125 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002126 }
2127}
2128
David Majnemer16252452014-01-29 00:07:39 +00002129namespace {
2130class AsmLexerSkipSpaceRAII {
2131public:
2132 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2133 Lexer.setSkipSpace(SkipSpace);
2134 }
2135
2136 ~AsmLexerSkipSpaceRAII() {
2137 Lexer.setSkipSpace(true);
2138 }
2139
2140private:
2141 AsmLexer &Lexer;
2142};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00002143}
David Majnemer16252452014-01-29 00:07:39 +00002144
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002145bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2146
2147 if (Vararg) {
2148 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2149 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002150 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002151 }
2152 return false;
2153 }
2154
Rafael Espindola768b41c2012-06-15 14:02:34 +00002155 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002156
David Majnemer16252452014-01-29 00:07:39 +00002157 // Darwin doesn't use spaces to delmit arguments.
2158 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002159
Scott Egertona1fa68a2016-02-11 13:48:49 +00002160 bool SpaceEaten;
2161
Rafael Espindola768b41c2012-06-15 14:02:34 +00002162 for (;;) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002163 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002164 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002165 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002166
Scott Egertona1fa68a2016-02-11 13:48:49 +00002167 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002168
Scott Egertona1fa68a2016-02-11 13:48:49 +00002169 if (Lexer.is(AsmToken::Comma))
2170 break;
2171
2172 if (Lexer.is(AsmToken::Space)) {
2173 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002174 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002175 }
Preston Gurd05500642012-09-19 20:36:12 +00002176
2177 // Spaces can delimit parameters, but could also be part an expression.
2178 // If the token after a space is an operator, add the token and the next
2179 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002180 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002181 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002182 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002183 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002184
Scott Egertona1fa68a2016-02-11 13:48:49 +00002185 // Whitespace after an operator can be ignored.
2186 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002187 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002188
2189 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002190 }
2191 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002192 if (SpaceEaten)
2193 break;
Preston Gurd05500642012-09-19 20:36:12 +00002194 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002195
Jim Grosbach4b905842013-09-20 23:08:21 +00002196 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002197 // to be able to fill in the remaining default parameter values
2198 if (Lexer.is(AsmToken::EndOfStatement))
2199 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002200
2201 // Adjust the current parentheses level.
2202 if (Lexer.is(AsmToken::LParen))
2203 ++ParenLevel;
2204 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2205 --ParenLevel;
2206
2207 // Append the token to the current argument list.
2208 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002209 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002210 }
Preston Gurd05500642012-09-19 20:36:12 +00002211
Rafael Espindola768b41c2012-06-15 14:02:34 +00002212 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002213 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002214 return false;
2215}
2216
2217// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002218bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002219 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002220 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002221 bool NamedParametersFound = false;
2222 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002223
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002224 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002225 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002226
Rafael Espindola768b41c2012-06-15 14:02:34 +00002227 // Parse two kinds of macro invocations:
2228 // - macros defined without any parameters accept an arbitrary number of them
2229 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002230 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002231 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2232 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002233 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002234 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002235
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002236 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002237 if (parseIdentifier(FA.Name)) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002238 Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002239 eatToEndOfStatement();
2240 return true;
2241 }
2242
2243 if (!Lexer.is(AsmToken::Equal)) {
2244 TokError("expected '=' after formal parameter identifier");
2245 eatToEndOfStatement();
2246 return true;
2247 }
2248 Lex();
2249
2250 NamedParametersFound = true;
2251 }
2252
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002253 if (NamedParametersFound && FA.Name.empty()) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002254 Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002255 eatToEndOfStatement();
2256 return true;
2257 }
2258
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002259 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2260 if (parseMacroArgument(FA.Value, Vararg))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002261 return true;
2262
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002263 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002264 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002265 unsigned FAI = 0;
2266 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002267 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002268 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002269
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002270 if (FAI >= NParameters) {
Oliver Stannard8b273082014-06-19 15:52:37 +00002271 assert(M && "expected macro to be defined");
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002272 Error(IDLoc,
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002273 "parameter named '" + FA.Name + "' does not exist for macro '" +
Saleem Abdulrasool3f44cd72014-03-17 17:13:57 +00002274 M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002275 return true;
2276 }
2277 PI = FAI;
2278 }
2279
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002280 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002281 if (A.size() <= PI)
2282 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002283 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002284
2285 if (FALocs.size() <= PI)
2286 FALocs.resize(PI + 1);
2287
2288 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002289 }
Jim Grosbach206661622012-07-30 22:44:17 +00002290
Preston Gurd242ed3152012-09-19 20:29:04 +00002291 // At the end of the statement, fill in remaining arguments that have
2292 // default values. If there aren't any, then the next argument is
2293 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002294 if (Lexer.is(AsmToken::EndOfStatement)) {
2295 bool Failure = false;
2296 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2297 if (A[FAI].empty()) {
2298 if (M->Parameters[FAI].Required) {
2299 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2300 "missing value for required parameter "
2301 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2302 Failure = true;
2303 }
2304
2305 if (!M->Parameters[FAI].Value.empty())
2306 A[FAI] = M->Parameters[FAI].Value;
2307 }
2308 }
2309 return Failure;
2310 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002311
2312 if (Lexer.is(AsmToken::Comma))
2313 Lex();
2314 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002315
2316 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002317}
2318
Jim Grosbach4b905842013-09-20 23:08:21 +00002319const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002320 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2321 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002322}
2323
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002324void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2325 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002326}
2327
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002328void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002329
Jim Grosbach4b905842013-09-20 23:08:21 +00002330bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbar43235712010-07-18 18:54:11 +00002331 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2332 // this, although we should protect against infinite loops.
2333 if (ActiveMacros.size() == 20)
2334 return TokError("macros cannot be nested more than 20 levels deep");
2335
Eli Bendersky38274122013-01-14 23:22:36 +00002336 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002337 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002338 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002339
Rafael Espindola1134ab232011-06-05 02:43:45 +00002340 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2341 // to hold the macro body with substitutions.
2342 SmallString<256> Buf;
2343 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002344 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002345
Toma Tabacu217116e2015-04-27 10:50:29 +00002346 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002347 return true;
2348
Eli Bendersky38274122013-01-14 23:22:36 +00002349 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002350 // instantiation.
2351 OS << ".endmacro\n";
2352
Rafael Espindola3560ff22014-08-27 20:03:13 +00002353 std::unique_ptr<MemoryBuffer> Instantiation =
2354 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002355
Daniel Dunbar43235712010-07-18 18:54:11 +00002356 // Create the macro instantiation object and add to the current macro
2357 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002358 MacroInstantiation *MI = new MacroInstantiation(
2359 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002360 ActiveMacros.push_back(MI);
2361
Toma Tabacu217116e2015-04-27 10:50:29 +00002362 ++NumOfMacroInstantiations;
2363
Daniel Dunbar43235712010-07-18 18:54:11 +00002364 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002365 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002366 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002367 Lex();
2368
2369 return false;
2370}
2371
Jim Grosbach4b905842013-09-20 23:08:21 +00002372void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002373 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002374 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002375 Lex();
2376
2377 // Pop the instantiation entry.
2378 delete ActiveMacros.back();
2379 ActiveMacros.pop_back();
2380}
2381
Jim Grosbach4b905842013-09-20 23:08:21 +00002382bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002383 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002384 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002385 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002386 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2387 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002388 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002389
Pete Cooper80d21cb2015-06-22 19:35:57 +00002390 if (!Sym) {
2391 // In the case where we parse an expression starting with a '.', we will
2392 // not generate an error, nor will we create a symbol. In this case we
2393 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002394 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002395 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002396
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002397 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002398 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002399 if (NoDeadStrip)
2400 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2401
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002402 return false;
2403}
2404
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002405/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002406/// ::= identifier
2407/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002408bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002409 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002410 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2411 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002412 // handle this as a context dependent token, instead we detect adjacent tokens
2413 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002414 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2415 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002416
Hans Wennborgce69d772013-10-18 20:46:28 +00002417 // Consume the prefix character, and check for a following identifier.
Nirav Dave1180e6892016-06-02 17:15:05 +00002418 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002419 if (Lexer.isNot(AsmToken::Identifier))
2420 return true;
2421
Hans Wennborgce69d772013-10-18 20:46:28 +00002422 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2423 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002424 return true;
2425
2426 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002427 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002428 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Dave1180e6892016-06-02 17:15:05 +00002429 Lexer.Lex(); // Lexer's Lex guarantees consecutive token
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002430 return false;
2431 }
2432
Jim Grosbach4b905842013-09-20 23:08:21 +00002433 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002434 return true;
2435
Sean Callanan936b0d32010-01-19 21:44:56 +00002436 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002437
Sean Callanan686ed8d2010-01-19 20:22:31 +00002438 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002439
2440 return false;
2441}
2442
Jim Grosbach4b905842013-09-20 23:08:21 +00002443/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002444/// ::= .equ identifier ',' expression
2445/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002446/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002447bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002448 StringRef Name;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002449
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002450 if (parseIdentifier(Name))
Roman Divacky41e6ceb2010-10-28 16:57:58 +00002451 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencer530ce852010-10-09 11:00:50 +00002452
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002453 if (getLexer().isNot(AsmToken::Comma))
Roman Divacky41e6ceb2010-10-28 16:57:58 +00002454 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002455 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002456
Jim Grosbach4b905842013-09-20 23:08:21 +00002457 return parseAssignment(Name, allow_redef, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002458}
2459
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002460bool AsmParser::parseEscapedString(std::string &Data) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002461 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbaref668c12009-08-14 18:19:52 +00002462
2463 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002464 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002465 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2466 if (Str[i] != '\\') {
2467 Data += Str[i];
2468 continue;
2469 }
2470
2471 // Recognize escaped characters. Note that this escape semantics currently
2472 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2473 ++i;
2474 if (i == e)
2475 return TokError("unexpected backslash at end of string");
2476
2477 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002478 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002479 // Consume up to three octal characters.
2480 unsigned Value = Str[i] - '0';
2481
Jim Grosbach4b905842013-09-20 23:08:21 +00002482 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002483 ++i;
2484 Value = Value * 8 + (Str[i] - '0');
2485
Jim Grosbach4b905842013-09-20 23:08:21 +00002486 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002487 ++i;
2488 Value = Value * 8 + (Str[i] - '0');
2489 }
2490 }
2491
2492 if (Value > 255)
2493 return TokError("invalid octal escape sequence (out of range)");
2494
Jim Grosbach4b905842013-09-20 23:08:21 +00002495 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002496 continue;
2497 }
2498
2499 // Otherwise recognize individual escapes.
2500 switch (Str[i]) {
2501 default:
2502 // Just reject invalid escape sequences for now.
2503 return TokError("invalid escape sequence (unrecognized character)");
2504
2505 case 'b': Data += '\b'; break;
2506 case 'f': Data += '\f'; break;
2507 case 'n': Data += '\n'; break;
2508 case 'r': Data += '\r'; break;
2509 case 't': Data += '\t'; break;
2510 case '"': Data += '"'; break;
2511 case '\\': Data += '\\'; break;
2512 }
2513 }
2514
2515 return false;
2516}
2517
Jim Grosbach4b905842013-09-20 23:08:21 +00002518/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002519/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002520bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002521 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002522 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002523
Daniel Dunbara10e5192009-06-24 23:30:00 +00002524 for (;;) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002525 if (getLexer().isNot(AsmToken::String))
Rafael Espindola63760ba2010-10-28 20:02:27 +00002526 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002527
Daniel Dunbaref668c12009-08-14 18:19:52 +00002528 std::string Data;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002529 if (parseEscapedString(Data))
Daniel Dunbaref668c12009-08-14 18:19:52 +00002530 return true;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002531
Rafael Espindola64e1af82013-07-02 15:49:13 +00002532 getStreamer().EmitBytes(Data);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002533 if (ZeroTerminated)
Rafael Espindola64e1af82013-07-02 15:49:13 +00002534 getStreamer().EmitBytes(StringRef("\0", 1));
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002535
Sean Callanan686ed8d2010-01-19 20:22:31 +00002536 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002537
2538 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002539 break;
2540
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002541 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola63760ba2010-10-28 20:02:27 +00002542 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002543 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002544 }
2545 }
2546
Sean Callanan686ed8d2010-01-19 20:22:31 +00002547 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002548 return false;
2549}
2550
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002551/// parseDirectiveReloc
2552/// ::= .reloc expression , identifier [ , expression ]
2553bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2554 const MCExpr *Offset;
2555 const MCExpr *Expr = nullptr;
2556
2557 SMLoc OffsetLoc = Lexer.getTok().getLoc();
2558 if (parseExpression(Offset))
2559 return true;
2560
2561 // We can only deal with constant expressions at the moment.
2562 int64_t OffsetValue;
2563 if (!Offset->evaluateAsAbsolute(OffsetValue))
2564 return Error(OffsetLoc, "expression is not a constant value");
2565
David Majnemerce108422016-01-19 23:05:27 +00002566 if (OffsetValue < 0)
2567 return Error(OffsetLoc, "expression is negative");
2568
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002569 if (Lexer.isNot(AsmToken::Comma))
2570 return TokError("expected comma");
2571 Lexer.Lex();
2572
2573 if (Lexer.isNot(AsmToken::Identifier))
2574 return TokError("expected relocation name");
2575 SMLoc NameLoc = Lexer.getTok().getLoc();
2576 StringRef Name = Lexer.getTok().getIdentifier();
2577 Lexer.Lex();
2578
2579 if (Lexer.is(AsmToken::Comma)) {
2580 Lexer.Lex();
2581 SMLoc ExprLoc = Lexer.getLoc();
2582 if (parseExpression(Expr))
2583 return true;
2584
2585 MCValue Value;
2586 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2587 return Error(ExprLoc, "expression must be relocatable");
2588 }
2589
2590 if (Lexer.isNot(AsmToken::EndOfStatement))
2591 return TokError("unexpected token in .reloc directive");
2592
2593 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2594 return Error(NameLoc, "unknown relocation name");
2595
2596 return false;
2597}
2598
Jim Grosbach4b905842013-09-20 23:08:21 +00002599/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002600/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002601bool AsmParser::parseDirectiveValue(unsigned Size) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002602 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002603 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002604
Daniel Dunbara10e5192009-06-24 23:30:00 +00002605 for (;;) {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002606 const MCExpr *Value;
Jim Grosbach76346c32011-06-29 16:05:14 +00002607 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002608 if (parseExpression(Value))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002609 return true;
2610
Daniel Dunbar6738a2e2010-05-23 18:36:38 +00002611 // Special case constant expressions to match code generator.
Jim Grosbach76346c32011-06-29 16:05:14 +00002612 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2613 assert(Size <= 8 && "Invalid size");
2614 uint64_t IntValue = MCE->getValue();
2615 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2616 return Error(ExprLoc, "literal value out of range for directive");
Rafael Espindola64e1af82013-07-02 15:49:13 +00002617 getStreamer().EmitIntValue(IntValue, Size);
Jim Grosbach76346c32011-06-29 16:05:14 +00002618 } else
Kevin Enderby96918bc2014-04-22 17:27:29 +00002619 getStreamer().EmitValue(Value, Size, ExprLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002620
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002621 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002622 break;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002623
Daniel Dunbara10e5192009-06-24 23:30:00 +00002624 // FIXME: Improve diagnostic.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002625 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002626 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002627 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002628 }
2629 }
2630
Sean Callanan686ed8d2010-01-19 20:22:31 +00002631 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002632 return false;
2633}
2634
David Woodhoused6de0d92014-02-01 16:20:59 +00002635/// ParseDirectiveOctaValue
2636/// ::= .octa [ hexconstant (, hexconstant)* ]
2637bool AsmParser::parseDirectiveOctaValue() {
2638 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2639 checkForValidSection();
2640
2641 for (;;) {
2642 if (Lexer.getKind() == AsmToken::Error)
2643 return true;
2644 if (Lexer.getKind() != AsmToken::Integer &&
2645 Lexer.getKind() != AsmToken::BigNum)
2646 return TokError("unknown token in expression");
2647
2648 SMLoc ExprLoc = getLexer().getLoc();
2649 APInt IntValue = getTok().getAPIntVal();
2650 Lex();
2651
2652 uint64_t hi, lo;
2653 if (IntValue.isIntN(64)) {
2654 hi = 0;
2655 lo = IntValue.getZExtValue();
2656 } else if (IntValue.isIntN(128)) {
David Woodhouse6c9a6f92014-02-01 16:52:33 +00002657 // It might actually have more than 128 bits, but the top ones are zero.
2658 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002659 lo = IntValue.getLoBits(64).getZExtValue();
2660 } else
2661 return Error(ExprLoc, "literal value out of range for directive");
2662
2663 if (MAI.isLittleEndian()) {
2664 getStreamer().EmitIntValue(lo, 8);
2665 getStreamer().EmitIntValue(hi, 8);
2666 } else {
2667 getStreamer().EmitIntValue(hi, 8);
2668 getStreamer().EmitIntValue(lo, 8);
2669 }
2670
2671 if (getLexer().is(AsmToken::EndOfStatement))
2672 break;
2673
2674 // FIXME: Improve diagnostic.
2675 if (getLexer().isNot(AsmToken::Comma))
2676 return TokError("unexpected token in directive");
2677 Lex();
2678 }
2679 }
2680
2681 Lex();
2682 return false;
2683}
2684
Jim Grosbach4b905842013-09-20 23:08:21 +00002685/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00002686/// ::= (.single | .double) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002687bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
Daniel Dunbar2af16532010-09-24 01:59:56 +00002688 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002689 checkForValidSection();
Daniel Dunbar2af16532010-09-24 01:59:56 +00002690
2691 for (;;) {
2692 // We don't truly support arithmetic on floating point expressions, so we
2693 // have to manually parse unary prefixes.
2694 bool IsNeg = false;
2695 if (getLexer().is(AsmToken::Minus)) {
Nirav Dave1180e6892016-06-02 17:15:05 +00002696 Lexer.Lex();
Daniel Dunbar2af16532010-09-24 01:59:56 +00002697 IsNeg = true;
2698 } else if (getLexer().is(AsmToken::Plus))
Nirav Dave1180e6892016-06-02 17:15:05 +00002699 Lexer.Lex();
Daniel Dunbar2af16532010-09-24 01:59:56 +00002700
Nirav Dave1180e6892016-06-02 17:15:05 +00002701 if (Lexer.is(AsmToken::Error))
2702 return TokError(Lexer.getErr());
2703 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
2704 Lexer.isNot(AsmToken::Identifier))
Daniel Dunbar2af16532010-09-24 01:59:56 +00002705 return TokError("unexpected token in directive");
2706
2707 // Convert to an APFloat.
2708 APFloat Value(Semantics);
Kevin Enderby5bbe9572011-03-29 21:11:52 +00002709 StringRef IDVal = getTok().getString();
2710 if (getLexer().is(AsmToken::Identifier)) {
2711 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2712 Value = APFloat::getInf(Semantics);
2713 else if (!IDVal.compare_lower("nan"))
2714 Value = APFloat::getNaN(Semantics, false, ~0);
2715 else
2716 return TokError("invalid floating point literal");
2717 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Jim Grosbach4b905842013-09-20 23:08:21 +00002718 APFloat::opInvalidOp)
Daniel Dunbar2af16532010-09-24 01:59:56 +00002719 return TokError("invalid floating point literal");
2720 if (IsNeg)
2721 Value.changeSign();
2722
2723 // Consume the numeric token.
2724 Lex();
2725
2726 // Emit the value as an integer.
2727 APInt AsInt = Value.bitcastToAPInt();
2728 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
Rafael Espindola64e1af82013-07-02 15:49:13 +00002729 AsInt.getBitWidth() / 8);
Daniel Dunbar2af16532010-09-24 01:59:56 +00002730
Nirav Dave1180e6892016-06-02 17:15:05 +00002731 if (Lexer.is(AsmToken::EndOfStatement))
Daniel Dunbar2af16532010-09-24 01:59:56 +00002732 break;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002733
Nirav Dave1180e6892016-06-02 17:15:05 +00002734 if (Lexer.isNot(AsmToken::Comma))
Daniel Dunbar2af16532010-09-24 01:59:56 +00002735 return TokError("unexpected token in directive");
2736 Lex();
2737 }
2738 }
2739
2740 Lex();
2741 return false;
2742}
2743
Jim Grosbach4b905842013-09-20 23:08:21 +00002744/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00002745/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002746bool AsmParser::parseDirectiveZero() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002747 checkForValidSection();
Rafael Espindola922e3f42010-09-16 15:03:59 +00002748
Petr Hosek67a94a72016-05-28 05:57:48 +00002749 SMLoc NumBytesLoc = Lexer.getLoc();
2750 const MCExpr *NumBytes;
2751 if (parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00002752 return true;
2753
Rafael Espindolab91bac62010-10-05 19:42:57 +00002754 int64_t Val = 0;
2755 if (getLexer().is(AsmToken::Comma)) {
2756 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002757 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00002758 return true;
2759 }
2760
Rafael Espindola922e3f42010-09-16 15:03:59 +00002761 if (getLexer().isNot(AsmToken::EndOfStatement))
2762 return TokError("unexpected token in '.zero' directive");
2763
2764 Lex();
2765
Petr Hosek67a94a72016-05-28 05:57:48 +00002766 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00002767
2768 return false;
2769}
2770
Jim Grosbach4b905842013-09-20 23:08:21 +00002771/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00002772/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002773bool AsmParser::parseDirectiveFill() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002774 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002775
Petr Hosek67a94a72016-05-28 05:57:48 +00002776 SMLoc NumValuesLoc = Lexer.getLoc();
2777 const MCExpr *NumValues;
2778 if (parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002779 return true;
2780
Roman Divackye33098f2013-09-24 17:44:41 +00002781 int64_t FillSize = 1;
2782 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002783
David Majnemer522d3db2014-02-01 07:19:38 +00002784 SMLoc SizeLoc, ExprLoc;
Roman Divackye33098f2013-09-24 17:44:41 +00002785 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2786 if (getLexer().isNot(AsmToken::Comma))
2787 return TokError("unexpected token in '.fill' directive");
2788 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002789
David Majnemer522d3db2014-02-01 07:19:38 +00002790 SizeLoc = getLexer().getLoc();
Roman Divackye33098f2013-09-24 17:44:41 +00002791 if (parseAbsoluteExpression(FillSize))
2792 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002793
Roman Divackye33098f2013-09-24 17:44:41 +00002794 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2795 if (getLexer().isNot(AsmToken::Comma))
2796 return TokError("unexpected token in '.fill' directive");
2797 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002798
David Majnemer522d3db2014-02-01 07:19:38 +00002799 ExprLoc = getLexer().getLoc();
Roman Divackye33098f2013-09-24 17:44:41 +00002800 if (parseAbsoluteExpression(FillExpr))
2801 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002802
Roman Divackye33098f2013-09-24 17:44:41 +00002803 if (getLexer().isNot(AsmToken::EndOfStatement))
2804 return TokError("unexpected token in '.fill' directive");
2805
2806 Lex();
2807 }
2808 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002809
David Majnemer522d3db2014-02-01 07:19:38 +00002810 if (FillSize < 0) {
2811 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00002812 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00002813 }
2814 if (FillSize > 8) {
2815 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2816 FillSize = 8;
2817 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002818
David Majnemer522d3db2014-02-01 07:19:38 +00002819 if (!isUInt<32>(FillExpr) && FillSize > 4)
2820 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2821
Petr Hosek67a94a72016-05-28 05:57:48 +00002822 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002823
2824 return false;
2825}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002826
Jim Grosbach4b905842013-09-20 23:08:21 +00002827/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002828/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002829bool AsmParser::parseDirectiveOrg() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002830 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002831
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002832 const MCExpr *Offset;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002833 if (parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002834 return true;
2835
2836 // Parse optional fill expression.
2837 int64_t FillExpr = 0;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002838 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2839 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002840 return TokError("unexpected token in '.org' directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002841 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00002842
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002843 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002844 return true;
2845
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002846 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002847 return TokError("unexpected token in '.org' directive");
2848 }
2849
Sean Callanan686ed8d2010-01-19 20:22:31 +00002850 Lex();
Rafael Espindola7ae65d82015-11-04 23:59:18 +00002851 getStreamer().emitValueToOffset(Offset, FillExpr);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002852 return false;
2853}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002854
Jim Grosbach4b905842013-09-20 23:08:21 +00002855/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002856/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00002857bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002858 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002859
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002860 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002861 int64_t Alignment;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002862 if (parseAbsoluteExpression(Alignment))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002863 return true;
2864
2865 SMLoc MaxBytesLoc;
2866 bool HasFillExpr = false;
2867 int64_t FillExpr = 0;
2868 int64_t MaxBytesToFill = 0;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002869 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2870 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002871 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002872 Lex();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002873
2874 // The fill expression can be omitted while specifying a maximum number of
2875 // alignment bytes, e.g:
2876 // .align 3,,4
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002877 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002878 HasFillExpr = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002879 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002880 return true;
2881 }
2882
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002883 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2884 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002885 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002886 Lex();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002887
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002888 MaxBytesLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002889 if (parseAbsoluteExpression(MaxBytesToFill))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002890 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002891
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002892 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002893 return TokError("unexpected token in directive");
2894 }
2895 }
2896
Sean Callanan686ed8d2010-01-19 20:22:31 +00002897 Lex();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002898
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002899 if (!HasFillExpr)
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002900 FillExpr = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002901
2902 // Compute alignment in bytes.
2903 if (IsPow2) {
2904 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002905 if (Alignment >= 32) {
2906 Error(AlignmentLoc, "invalid alignment value");
2907 Alignment = 31;
2908 }
2909
Benjamin Kramer63951ad2009-09-06 09:35:10 +00002910 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00002911 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00002912 // Reject alignments that aren't either a power of two or zero,
2913 // for gas compatibility. Alignment of zero is silently rounded
2914 // up to one.
2915 if (Alignment == 0)
2916 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00002917 if (!isPowerOf2_64(Alignment))
2918 Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002919 }
2920
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002921 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002922 if (MaxBytesLoc.isValid()) {
2923 if (MaxBytesToFill < 1) {
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002924 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00002925 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00002926 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002927 }
2928
2929 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00002930 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00002931 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002932 MaxBytesToFill = 0;
2933 }
2934 }
2935
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002936 // Check whether we should use optimal code alignment for this .align
2937 // directive.
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00002938 const MCSection *Section = getStreamer().getCurrentSection().first;
2939 assert(Section && "must have section to emit alignment");
2940 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002941 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2942 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002943 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002944 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00002945 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00002946 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2947 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002948 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002949
2950 return false;
2951}
2952
Jim Grosbach4b905842013-09-20 23:08:21 +00002953/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00002954/// ::= .file [number] filename
2955/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00002956bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00002957 // FIXME: I'm not sure what this is.
2958 int64_t FileNumber = -1;
2959 SMLoc FileNumberLoc = getLexer().getLoc();
2960 if (getLexer().is(AsmToken::Integer)) {
2961 FileNumber = getTok().getIntVal();
2962 Lex();
2963
2964 if (FileNumber < 1)
2965 return TokError("file number less than one");
2966 }
2967
2968 if (getLexer().isNot(AsmToken::String))
2969 return TokError("unexpected token in '.file' directive");
2970
2971 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002972 // Allow the strings to have escaped octal character sequence.
2973 std::string Path = getTok().getString();
2974 if (parseEscapedString(Path))
2975 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00002976 Lex();
2977
2978 StringRef Directory;
2979 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002980 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00002981 if (getLexer().is(AsmToken::String)) {
2982 if (FileNumber == -1)
2983 return TokError("explicit path specified, but no file number");
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002984 if (parseEscapedString(FilenameData))
2985 return true;
2986 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00002987 Directory = Path;
2988 Lex();
2989 } else {
2990 Filename = Path;
2991 }
2992
2993 if (getLexer().isNot(AsmToken::EndOfStatement))
2994 return TokError("unexpected token in '.file' directive");
2995
2996 if (FileNumber == -1)
2997 getStreamer().EmitFileDirective(Filename);
2998 else {
David Blaikie22748082016-05-26 00:22:26 +00002999 // If there is -g option as well as debug info from directive file,
3000 // we turn off -g option, directly use the existing debug info instead.
David Blaikiedc3f01e2015-03-09 01:57:13 +00003001 if (getContext().getGenDwarfForAssembly())
David Blaikie22748082016-05-26 00:22:26 +00003002 getContext().setGenDwarfForAssembly(false);
3003 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
David Blaikiec714ef42014-03-17 01:52:11 +00003004 0)
Eli Bendersky17233942013-01-15 22:59:42 +00003005 Error(FileNumberLoc, "file number already allocated");
3006 }
3007
3008 return false;
3009}
3010
Jim Grosbach4b905842013-09-20 23:08:21 +00003011/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003012/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003013bool AsmParser::parseDirectiveLine() {
Eli Bendersky17233942013-01-15 22:59:42 +00003014 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3015 if (getLexer().isNot(AsmToken::Integer))
3016 return TokError("unexpected token in '.line' directive");
3017
3018 int64_t LineNumber = getTok().getIntVal();
Jim Grosbach4b905842013-09-20 23:08:21 +00003019 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003020 Lex();
3021
3022 // FIXME: Do something with the .line.
3023 }
3024
3025 if (getLexer().isNot(AsmToken::EndOfStatement))
3026 return TokError("unexpected token in '.line' directive");
3027
3028 return false;
3029}
3030
Jim Grosbach4b905842013-09-20 23:08:21 +00003031/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003032/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3033/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3034/// The first number is a file number, must have been previously assigned with
3035/// a .file directive, the second number is the line number and optionally the
3036/// third number is a column position (zero if not specified). The remaining
3037/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003038bool AsmParser::parseDirectiveLoc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003039 if (getLexer().isNot(AsmToken::Integer))
3040 return TokError("unexpected token in '.loc' directive");
3041 int64_t FileNumber = getTok().getIntVal();
3042 if (FileNumber < 1)
3043 return TokError("file number less than one in '.loc' directive");
3044 if (!getContext().isValidDwarfFileNumber(FileNumber))
3045 return TokError("unassigned file number in '.loc' directive");
3046 Lex();
3047
3048 int64_t LineNumber = 0;
3049 if (getLexer().is(AsmToken::Integer)) {
3050 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003051 if (LineNumber < 0)
3052 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003053 Lex();
3054 }
3055
3056 int64_t ColumnPos = 0;
3057 if (getLexer().is(AsmToken::Integer)) {
3058 ColumnPos = getTok().getIntVal();
3059 if (ColumnPos < 0)
3060 return TokError("column position less than zero in '.loc' directive");
3061 Lex();
3062 }
3063
3064 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3065 unsigned Isa = 0;
3066 int64_t Discriminator = 0;
3067 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3068 for (;;) {
3069 if (getLexer().is(AsmToken::EndOfStatement))
3070 break;
3071
3072 StringRef Name;
3073 SMLoc Loc = getTok().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003074 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003075 return TokError("unexpected token in '.loc' directive");
3076
3077 if (Name == "basic_block")
3078 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3079 else if (Name == "prologue_end")
3080 Flags |= DWARF2_FLAG_PROLOGUE_END;
3081 else if (Name == "epilogue_begin")
3082 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3083 else if (Name == "is_stmt") {
3084 Loc = getTok().getLoc();
3085 const MCExpr *Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003086 if (parseExpression(Value))
Eli Bendersky17233942013-01-15 22:59:42 +00003087 return true;
3088 // The expression must be the constant 0 or 1.
3089 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3090 int Value = MCE->getValue();
3091 if (Value == 0)
3092 Flags &= ~DWARF2_FLAG_IS_STMT;
3093 else if (Value == 1)
3094 Flags |= DWARF2_FLAG_IS_STMT;
3095 else
3096 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003097 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003098 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3099 }
Craig Topperf15655b2013-04-22 04:22:40 +00003100 } else if (Name == "isa") {
Eli Bendersky17233942013-01-15 22:59:42 +00003101 Loc = getTok().getLoc();
3102 const MCExpr *Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003103 if (parseExpression(Value))
Eli Bendersky17233942013-01-15 22:59:42 +00003104 return true;
3105 // The expression must be a constant greater or equal to 0.
3106 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3107 int Value = MCE->getValue();
3108 if (Value < 0)
3109 return Error(Loc, "isa number less than zero");
3110 Isa = Value;
Craig Topperf15655b2013-04-22 04:22:40 +00003111 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003112 return Error(Loc, "isa number not a constant value");
3113 }
Craig Topperf15655b2013-04-22 04:22:40 +00003114 } else if (Name == "discriminator") {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003115 if (parseAbsoluteExpression(Discriminator))
Eli Bendersky17233942013-01-15 22:59:42 +00003116 return true;
Craig Topperf15655b2013-04-22 04:22:40 +00003117 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003118 return Error(Loc, "unknown sub-directive in '.loc' directive");
3119 }
3120
3121 if (getLexer().is(AsmToken::EndOfStatement))
3122 break;
3123 }
3124 }
3125
3126 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3127 Isa, Discriminator, StringRef());
3128
3129 return false;
3130}
3131
Jim Grosbach4b905842013-09-20 23:08:21 +00003132/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003133/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003134bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003135 return TokError("unsupported directive '.stabs'");
3136}
3137
Reid Kleckner2214ed82016-01-29 00:49:42 +00003138/// parseDirectiveCVFile
3139/// ::= .cv_file number filename
3140bool AsmParser::parseDirectiveCVFile() {
3141 SMLoc FileNumberLoc = getLexer().getLoc();
3142 if (getLexer().isNot(AsmToken::Integer))
3143 return TokError("expected file number in '.cv_file' directive");
3144
3145 int64_t FileNumber = getTok().getIntVal();
3146 Lex();
3147
3148 if (FileNumber < 1)
3149 return TokError("file number less than one");
3150
3151 if (getLexer().isNot(AsmToken::String))
3152 return TokError("unexpected token in '.cv_file' directive");
3153
3154 // Usually the directory and filename together, otherwise just the directory.
3155 // Allow the strings to have escaped octal character sequence.
3156 std::string Filename;
3157 if (parseEscapedString(Filename))
3158 return true;
3159 Lex();
3160
3161 if (getLexer().isNot(AsmToken::EndOfStatement))
3162 return TokError("unexpected token in '.cv_file' directive");
3163
3164 if (getStreamer().EmitCVFileDirective(FileNumber, Filename) == 0)
3165 Error(FileNumberLoc, "file number already allocated");
3166
3167 return false;
3168}
3169
3170/// parseDirectiveCVLoc
3171/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3172/// [is_stmt VALUE]
3173/// The first number is a file number, must have been previously assigned with
3174/// a .file directive, the second number is the line number and optionally the
3175/// third number is a column position (zero if not specified). The remaining
3176/// optional items are .loc sub-directives.
3177bool AsmParser::parseDirectiveCVLoc() {
3178 if (getLexer().isNot(AsmToken::Integer))
3179 return TokError("unexpected token in '.cv_loc' directive");
3180
3181 int64_t FunctionId = getTok().getIntVal();
3182 if (FunctionId < 0)
3183 return TokError("function id less than zero in '.cv_loc' directive");
3184 Lex();
3185
3186 int64_t FileNumber = getTok().getIntVal();
3187 if (FileNumber < 1)
3188 return TokError("file number less than one in '.cv_loc' directive");
3189 if (!getContext().isValidCVFileNumber(FileNumber))
3190 return TokError("unassigned file number in '.cv_loc' directive");
3191 Lex();
3192
3193 int64_t LineNumber = 0;
3194 if (getLexer().is(AsmToken::Integer)) {
3195 LineNumber = getTok().getIntVal();
3196 if (LineNumber < 0)
3197 return TokError("line number less than zero in '.cv_loc' directive");
3198 Lex();
3199 }
3200
3201 int64_t ColumnPos = 0;
3202 if (getLexer().is(AsmToken::Integer)) {
3203 ColumnPos = getTok().getIntVal();
3204 if (ColumnPos < 0)
3205 return TokError("column position less than zero in '.cv_loc' directive");
3206 Lex();
3207 }
3208
3209 bool PrologueEnd = false;
3210 uint64_t IsStmt = 0;
3211 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3212 StringRef Name;
3213 SMLoc Loc = getTok().getLoc();
3214 if (parseIdentifier(Name))
3215 return TokError("unexpected token in '.cv_loc' directive");
3216
3217 if (Name == "prologue_end")
3218 PrologueEnd = true;
3219 else if (Name == "is_stmt") {
3220 Loc = getTok().getLoc();
3221 const MCExpr *Value;
3222 if (parseExpression(Value))
3223 return true;
3224 // The expression must be the constant 0 or 1.
3225 IsStmt = ~0ULL;
3226 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3227 IsStmt = MCE->getValue();
3228
3229 if (IsStmt > 1)
3230 return Error(Loc, "is_stmt value not 0 or 1");
3231 } else {
3232 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3233 }
3234 }
3235
3236 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
3237 ColumnPos, PrologueEnd, IsStmt, StringRef());
3238 return false;
3239}
3240
3241/// parseDirectiveCVLinetable
3242/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3243bool AsmParser::parseDirectiveCVLinetable() {
3244 int64_t FunctionId = getTok().getIntVal();
3245 if (FunctionId < 0)
3246 return TokError("function id less than zero in '.cv_linetable' directive");
3247 Lex();
3248
3249 if (Lexer.isNot(AsmToken::Comma))
3250 return TokError("unexpected token in '.cv_linetable' directive");
3251 Lex();
3252
3253 SMLoc Loc = getLexer().getLoc();
3254 StringRef FnStartName;
3255 if (parseIdentifier(FnStartName))
3256 return Error(Loc, "expected identifier in directive");
3257
3258 if (Lexer.isNot(AsmToken::Comma))
3259 return TokError("unexpected token in '.cv_linetable' directive");
3260 Lex();
3261
3262 Loc = getLexer().getLoc();
3263 StringRef FnEndName;
3264 if (parseIdentifier(FnEndName))
3265 return Error(Loc, "expected identifier in directive");
3266
3267 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3268 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3269
3270 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3271 return false;
3272}
3273
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003274/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003275/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003276/// ("contains" SecondaryFunctionId+)?
3277bool AsmParser::parseDirectiveCVInlineLinetable() {
3278 int64_t PrimaryFunctionId = getTok().getIntVal();
3279 if (PrimaryFunctionId < 0)
3280 return TokError(
3281 "function id less than zero in '.cv_inline_linetable' directive");
3282 Lex();
3283
3284 int64_t SourceFileId = getTok().getIntVal();
3285 if (SourceFileId <= 0)
3286 return TokError(
3287 "File id less than zero in '.cv_inline_linetable' directive");
3288 Lex();
3289
3290 int64_t SourceLineNum = getTok().getIntVal();
3291 if (SourceLineNum < 0)
3292 return TokError(
3293 "Line number less than zero in '.cv_inline_linetable' directive");
3294 Lex();
3295
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003296 SMLoc Loc = getLexer().getLoc();
3297 StringRef FnStartName;
3298 if (parseIdentifier(FnStartName))
3299 return Error(Loc, "expected identifier in directive");
3300 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3301
David Majnemerc9911f22016-02-02 19:22:34 +00003302 Loc = getLexer().getLoc();
3303 StringRef FnEndName;
3304 if (parseIdentifier(FnEndName))
3305 return Error(Loc, "expected identifier in directive");
3306 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3307
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003308 SmallVector<unsigned, 8> SecondaryFunctionIds;
3309 if (getLexer().is(AsmToken::Identifier)) {
3310 if (getTok().getIdentifier() != "contains")
3311 return TokError(
3312 "unexpected identifier in '.cv_inline_linetable' directive");
3313 Lex();
3314
3315 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3316 int64_t SecondaryFunctionId = getTok().getIntVal();
3317 if (SecondaryFunctionId < 0)
3318 return TokError(
3319 "function id less than zero in '.cv_inline_linetable' directive");
3320 Lex();
3321
3322 SecondaryFunctionIds.push_back(SecondaryFunctionId);
3323 }
3324 }
3325
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003326 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3327 SourceLineNum, FnStartSym,
David Majnemerc9911f22016-02-02 19:22:34 +00003328 FnEndSym, SecondaryFunctionIds);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003329 return false;
3330}
3331
David Majnemer408b5e62016-02-05 01:55:49 +00003332/// parseDirectiveCVDefRange
3333/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3334bool AsmParser::parseDirectiveCVDefRange() {
3335 SMLoc Loc;
3336 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3337 while (getLexer().is(AsmToken::Identifier)) {
3338 Loc = getLexer().getLoc();
3339 StringRef GapStartName;
3340 if (parseIdentifier(GapStartName))
3341 return Error(Loc, "expected identifier in directive");
3342 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3343
3344 Loc = getLexer().getLoc();
3345 StringRef GapEndName;
3346 if (parseIdentifier(GapEndName))
3347 return Error(Loc, "expected identifier in directive");
3348 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3349
3350 Ranges.push_back({GapStartSym, GapEndSym});
3351 }
3352
3353 if (getLexer().isNot(AsmToken::Comma))
3354 return TokError("unexpected token in directive");
3355 Lex();
3356
3357 std::string FixedSizePortion;
3358 if (parseEscapedString(FixedSizePortion))
3359 return true;
3360 Lex();
3361
3362 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3363 return false;
3364}
3365
Reid Kleckner2214ed82016-01-29 00:49:42 +00003366/// parseDirectiveCVStringTable
3367/// ::= .cv_stringtable
3368bool AsmParser::parseDirectiveCVStringTable() {
3369 getStreamer().EmitCVStringTableDirective();
3370 return false;
3371}
3372
3373/// parseDirectiveCVFileChecksums
3374/// ::= .cv_filechecksums
3375bool AsmParser::parseDirectiveCVFileChecksums() {
3376 getStreamer().EmitCVFileChecksumsDirective();
3377 return false;
3378}
3379
Jim Grosbach4b905842013-09-20 23:08:21 +00003380/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003381/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003382bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003383 StringRef Name;
3384 bool EH = false;
3385 bool Debug = false;
3386
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003387 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003388 return TokError("Expected an identifier");
3389
3390 if (Name == ".eh_frame")
3391 EH = true;
3392 else if (Name == ".debug_frame")
3393 Debug = true;
3394
3395 if (getLexer().is(AsmToken::Comma)) {
3396 Lex();
3397
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003398 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003399 return TokError("Expected an identifier");
3400
3401 if (Name == ".eh_frame")
3402 EH = true;
3403 else if (Name == ".debug_frame")
3404 Debug = true;
3405 }
3406
3407 getStreamer().EmitCFISections(EH, Debug);
3408 return false;
3409}
3410
Jim Grosbach4b905842013-09-20 23:08:21 +00003411/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003412/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003413bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003414 StringRef Simple;
3415 if (getLexer().isNot(AsmToken::EndOfStatement))
3416 if (parseIdentifier(Simple) || Simple != "simple")
3417 return TokError("unexpected token in .cfi_startproc directive");
3418
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003419 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003420 return false;
3421}
3422
Jim Grosbach4b905842013-09-20 23:08:21 +00003423/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003424/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003425bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003426 getStreamer().EmitCFIEndProc();
3427 return false;
3428}
3429
Jim Grosbach4b905842013-09-20 23:08:21 +00003430/// \brief parse register name or number.
3431bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003432 SMLoc DirectiveLoc) {
3433 unsigned RegNo;
3434
3435 if (getLexer().isNot(AsmToken::Integer)) {
3436 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3437 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003438 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003439 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003440 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003441
3442 return false;
3443}
3444
Jim Grosbach4b905842013-09-20 23:08:21 +00003445/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003446/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003447bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003448 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003449 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003450 return true;
3451
3452 if (getLexer().isNot(AsmToken::Comma))
3453 return TokError("unexpected token in directive");
3454 Lex();
3455
3456 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003457 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003458 return true;
3459
3460 getStreamer().EmitCFIDefCfa(Register, Offset);
3461 return false;
3462}
3463
Jim Grosbach4b905842013-09-20 23:08:21 +00003464/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003465/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003466bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003467 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003468 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003469 return true;
3470
3471 getStreamer().EmitCFIDefCfaOffset(Offset);
3472 return false;
3473}
3474
Jim Grosbach4b905842013-09-20 23:08:21 +00003475/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003476/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003477bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003478 int64_t Register1 = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003479 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003480 return true;
3481
3482 if (getLexer().isNot(AsmToken::Comma))
3483 return TokError("unexpected token in directive");
3484 Lex();
3485
3486 int64_t Register2 = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003487 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003488 return true;
3489
3490 getStreamer().EmitCFIRegister(Register1, Register2);
3491 return false;
3492}
3493
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003494/// parseDirectiveCFIWindowSave
3495/// ::= .cfi_window_save
3496bool AsmParser::parseDirectiveCFIWindowSave() {
3497 getStreamer().EmitCFIWindowSave();
3498 return false;
3499}
3500
Jim Grosbach4b905842013-09-20 23:08:21 +00003501/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003502/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003503bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003504 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003505 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003506 return true;
3507
3508 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3509 return false;
3510}
3511
Jim Grosbach4b905842013-09-20 23:08:21 +00003512/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003513/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003514bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003515 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003516 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003517 return true;
3518
3519 getStreamer().EmitCFIDefCfaRegister(Register);
3520 return false;
3521}
3522
Jim Grosbach4b905842013-09-20 23:08:21 +00003523/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003524/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003525bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003526 int64_t Register = 0;
3527 int64_t Offset = 0;
3528
Jim Grosbach4b905842013-09-20 23:08:21 +00003529 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003530 return true;
3531
3532 if (getLexer().isNot(AsmToken::Comma))
3533 return TokError("unexpected token in directive");
3534 Lex();
3535
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003536 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003537 return true;
3538
3539 getStreamer().EmitCFIOffset(Register, Offset);
3540 return false;
3541}
3542
Jim Grosbach4b905842013-09-20 23:08:21 +00003543/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003544/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003545bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003546 int64_t Register = 0;
3547
Jim Grosbach4b905842013-09-20 23:08:21 +00003548 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003549 return true;
3550
3551 if (getLexer().isNot(AsmToken::Comma))
3552 return TokError("unexpected token in directive");
3553 Lex();
3554
3555 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003556 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003557 return true;
3558
3559 getStreamer().EmitCFIRelOffset(Register, Offset);
3560 return false;
3561}
3562
3563static bool isValidEncoding(int64_t Encoding) {
3564 if (Encoding & ~0xff)
3565 return false;
3566
3567 if (Encoding == dwarf::DW_EH_PE_omit)
3568 return true;
3569
3570 const unsigned Format = Encoding & 0xf;
3571 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3572 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3573 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3574 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3575 return false;
3576
3577 const unsigned Application = Encoding & 0x70;
3578 if (Application != dwarf::DW_EH_PE_absptr &&
3579 Application != dwarf::DW_EH_PE_pcrel)
3580 return false;
3581
3582 return true;
3583}
3584
Jim Grosbach4b905842013-09-20 23:08:21 +00003585/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003586/// IsPersonality true for cfi_personality, false for cfi_lsda
3587/// ::= .cfi_personality encoding, [symbol_name]
3588/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003589bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003590 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003591 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003592 return true;
3593 if (Encoding == dwarf::DW_EH_PE_omit)
3594 return false;
3595
3596 if (!isValidEncoding(Encoding))
3597 return TokError("unsupported encoding.");
3598
3599 if (getLexer().isNot(AsmToken::Comma))
3600 return TokError("unexpected token in directive");
3601 Lex();
3602
3603 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003604 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003605 return TokError("expected identifier in directive");
3606
Jim Grosbach6f482002015-05-18 18:43:14 +00003607 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003608
3609 if (IsPersonality)
3610 getStreamer().EmitCFIPersonality(Sym, Encoding);
3611 else
3612 getStreamer().EmitCFILsda(Sym, Encoding);
3613 return false;
3614}
3615
Jim Grosbach4b905842013-09-20 23:08:21 +00003616/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00003617/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003618bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003619 getStreamer().EmitCFIRememberState();
3620 return false;
3621}
3622
Jim Grosbach4b905842013-09-20 23:08:21 +00003623/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00003624/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003625bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003626 getStreamer().EmitCFIRestoreState();
3627 return false;
3628}
3629
Jim Grosbach4b905842013-09-20 23:08:21 +00003630/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00003631/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00003632bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003633 int64_t Register = 0;
3634
Jim Grosbach4b905842013-09-20 23:08:21 +00003635 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003636 return true;
3637
3638 getStreamer().EmitCFISameValue(Register);
3639 return false;
3640}
3641
Jim Grosbach4b905842013-09-20 23:08:21 +00003642/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00003643/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00003644bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003645 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003646 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003647 return true;
3648
3649 getStreamer().EmitCFIRestore(Register);
3650 return false;
3651}
3652
Jim Grosbach4b905842013-09-20 23:08:21 +00003653/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00003654/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003655bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00003656 std::string Values;
3657 int64_t CurrValue;
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 while (getLexer().is(AsmToken::Comma)) {
3664 Lex();
3665
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003666 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003667 return true;
3668
3669 Values.push_back((uint8_t)CurrValue);
3670 }
3671
3672 getStreamer().EmitCFIEscape(Values);
3673 return false;
3674}
3675
Jim Grosbach4b905842013-09-20 23:08:21 +00003676/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00003677/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00003678bool AsmParser::parseDirectiveCFISignalFrame() {
Eli Bendersky17233942013-01-15 22:59:42 +00003679 if (getLexer().isNot(AsmToken::EndOfStatement))
3680 return Error(getLexer().getLoc(),
3681 "unexpected token in '.cfi_signal_frame'");
3682
3683 getStreamer().EmitCFISignalFrame();
3684 return false;
3685}
3686
Jim Grosbach4b905842013-09-20 23:08:21 +00003687/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00003688/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00003689bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003690 int64_t Register = 0;
3691
Jim Grosbach4b905842013-09-20 23:08:21 +00003692 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003693 return true;
3694
3695 getStreamer().EmitCFIUndefined(Register);
3696 return false;
3697}
3698
Jim Grosbach4b905842013-09-20 23:08:21 +00003699/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00003700/// ::= .macros_on
3701/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00003702bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00003703 if (getLexer().isNot(AsmToken::EndOfStatement))
3704 return Error(getLexer().getLoc(),
3705 "unexpected token in '" + Directive + "' directive");
3706
Jim Grosbach4b905842013-09-20 23:08:21 +00003707 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00003708 return false;
3709}
3710
Jim Grosbach4b905842013-09-20 23:08:21 +00003711/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003712/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00003713bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003714 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003715 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003716 return TokError("expected identifier in '.macro' directive");
3717
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003718 if (getLexer().is(AsmToken::Comma))
3719 Lex();
3720
Eli Bendersky17233942013-01-15 22:59:42 +00003721 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00003722 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003723
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003724 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003725 return Error(Lexer.getLoc(),
3726 "Vararg parameter '" + Parameters.back().Name +
3727 "' should be last one in the list of parameters.");
3728
David Majnemer91fc4c22014-01-29 18:57:46 +00003729 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003730 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00003731 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003732
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003733 if (Lexer.is(AsmToken::Colon)) {
3734 Lex(); // consume ':'
3735
3736 SMLoc QualLoc;
3737 StringRef Qualifier;
3738
3739 QualLoc = Lexer.getLoc();
3740 if (parseIdentifier(Qualifier))
3741 return Error(QualLoc, "missing parameter qualifier for "
3742 "'" + Parameter.Name + "' in macro '" + Name + "'");
3743
3744 if (Qualifier == "req")
3745 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00003746 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003747 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003748 else
3749 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3750 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3751 }
3752
David Majnemer91fc4c22014-01-29 18:57:46 +00003753 if (getLexer().is(AsmToken::Equal)) {
3754 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003755
3756 SMLoc ParamLoc;
3757
3758 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003759 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00003760 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003761
3762 if (Parameter.Required)
3763 Warning(ParamLoc, "pointless default value for required parameter "
3764 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00003765 }
David Majnemer91fc4c22014-01-29 18:57:46 +00003766
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003767 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00003768
3769 if (getLexer().is(AsmToken::Comma))
3770 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003771 }
3772
Nirav Dave1180e6892016-06-02 17:15:05 +00003773 // Eat just the end of statement.
3774 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003775
Nirav Dave1180e6892016-06-02 17:15:05 +00003776 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00003777 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003778 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003779 // Lex the macro definition.
3780 for (;;) {
Nirav Dave1180e6892016-06-02 17:15:05 +00003781 // Ignore Lexing errors in macros.
3782 while (Lexer.is(AsmToken::Error)) {
3783 Lexer.Lex();
3784 }
3785
Eli Bendersky17233942013-01-15 22:59:42 +00003786 // Check whether we have reached the end of the file.
3787 if (getLexer().is(AsmToken::Eof))
3788 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3789
3790 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003791 if (getLexer().is(AsmToken::Identifier)) {
3792 if (getTok().getIdentifier() == ".endm" ||
3793 getTok().getIdentifier() == ".endmacro") {
3794 if (MacroDepth == 0) { // Outermost macro.
3795 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00003796 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003797 if (getLexer().isNot(AsmToken::EndOfStatement))
3798 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3799 "' directive");
3800 break;
3801 } else {
3802 // Otherwise we just found the end of an inner macro.
3803 --MacroDepth;
3804 }
3805 } else if (getTok().getIdentifier() == ".macro") {
3806 // We allow nested macros. Those aren't instantiated until the outermost
3807 // macro is expanded so just ignore them for now.
3808 ++MacroDepth;
3809 }
Eli Bendersky17233942013-01-15 22:59:42 +00003810 }
3811
3812 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003813 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00003814 }
3815
Jim Grosbach4b905842013-09-20 23:08:21 +00003816 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00003817 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3818 }
3819
3820 const char *BodyStart = StartToken.getLoc().getPointer();
3821 const char *BodyEnd = EndToken.getLoc().getPointer();
3822 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00003823 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003824 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00003825 return false;
3826}
3827
Jim Grosbach4b905842013-09-20 23:08:21 +00003828/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00003829///
3830/// With the support added for named parameters there may be code out there that
3831/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00003832/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00003833/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00003834/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00003835/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3836/// warning that the positional parameter found in body which have no effect.
3837/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00003838/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00003839/// intended or change the macro to use the named parameters. It is possible
3840/// this warning will trigger when the none of the named parameters are used
3841/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00003842void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00003843 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00003844 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00003845 // If this macro is not defined with named parameters the warning we are
3846 // checking for here doesn't apply.
3847 unsigned NParameters = Parameters.size();
3848 if (NParameters == 0)
3849 return;
3850
3851 bool NamedParametersFound = false;
3852 bool PositionalParametersFound = false;
3853
3854 // Look at the body of the macro for use of both the named parameters and what
3855 // are likely to be positional parameters. This is what expandMacro() is
3856 // doing when it finds the parameters in the body.
3857 while (!Body.empty()) {
3858 // Scan for the next possible parameter.
3859 std::size_t End = Body.size(), Pos = 0;
3860 for (; Pos != End; ++Pos) {
3861 // Check for a substitution or escape.
3862 // This macro is defined with parameters, look for \foo, \bar, etc.
3863 if (Body[Pos] == '\\' && Pos + 1 != End)
3864 break;
3865
3866 // This macro should have parameters, but look for $0, $1, ..., $n too.
3867 if (Body[Pos] != '$' || Pos + 1 == End)
3868 continue;
3869 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00003870 if (Next == '$' || Next == 'n' ||
3871 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00003872 break;
3873 }
3874
3875 // Check if we reached the end.
3876 if (Pos == End)
3877 break;
3878
3879 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00003880 switch (Body[Pos + 1]) {
3881 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00003882 case '$':
3883 break;
3884
Jim Grosbach4b905842013-09-20 23:08:21 +00003885 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00003886 case 'n':
3887 PositionalParametersFound = true;
3888 break;
3889
Jim Grosbach4b905842013-09-20 23:08:21 +00003890 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00003891 default: {
3892 PositionalParametersFound = true;
3893 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00003894 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00003895 }
3896 Pos += 2;
3897 } else {
3898 unsigned I = Pos + 1;
3899 while (isIdentifierChar(Body[I]) && I + 1 != End)
3900 ++I;
3901
Jim Grosbach4b905842013-09-20 23:08:21 +00003902 const char *Begin = Body.data() + Pos + 1;
3903 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00003904 unsigned Index = 0;
3905 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003906 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00003907 break;
3908
3909 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00003910 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3911 Pos += 3;
3912 else {
3913 Pos = I;
3914 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00003915 } else {
3916 NamedParametersFound = true;
3917 Pos += 1 + Argument.size();
3918 }
3919 }
3920 // Update the scan point.
3921 Body = Body.substr(Pos);
3922 }
3923
3924 if (!NamedParametersFound && PositionalParametersFound)
3925 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3926 "used in macro body, possible positional parameter "
3927 "found in body which will have no effect");
3928}
3929
Nico Weber155dccd12014-07-24 17:08:39 +00003930/// parseDirectiveExitMacro
3931/// ::= .exitm
3932bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3933 if (getLexer().isNot(AsmToken::EndOfStatement))
3934 return TokError("unexpected token in '" + Directive + "' directive");
3935
3936 if (!isInsideMacroInstantiation())
3937 return TokError("unexpected '" + Directive + "' in file, "
3938 "no current macro definition");
3939
3940 // Exit all conditionals that are active in the current macro.
3941 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3942 TheCondState = TheCondStack.back();
3943 TheCondStack.pop_back();
3944 }
3945
3946 handleMacroExit();
3947 return false;
3948}
3949
Jim Grosbach4b905842013-09-20 23:08:21 +00003950/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00003951/// ::= .endm
3952/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00003953bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00003954 if (getLexer().isNot(AsmToken::EndOfStatement))
3955 return TokError("unexpected token in '" + Directive + "' directive");
3956
3957 // If we are inside a macro instantiation, terminate the current
3958 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00003959 if (isInsideMacroInstantiation()) {
3960 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00003961 return false;
3962 }
3963
3964 // Otherwise, this .endmacro is a stray entry in the file; well formed
3965 // .endmacro directives are handled during the macro definition parsing.
3966 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00003967 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00003968}
3969
Jim Grosbach4b905842013-09-20 23:08:21 +00003970/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00003971/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00003972bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003973 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003974 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003975 return TokError("expected identifier in '.purgem' directive");
3976
3977 if (getLexer().isNot(AsmToken::EndOfStatement))
3978 return TokError("unexpected token in '.purgem' directive");
3979
Jim Grosbach4b905842013-09-20 23:08:21 +00003980 if (!lookupMacro(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003981 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3982
Jim Grosbach4b905842013-09-20 23:08:21 +00003983 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003984 return false;
3985}
Eli Benderskyf483ff92012-12-20 19:05:53 +00003986
Jim Grosbach4b905842013-09-20 23:08:21 +00003987/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00003988/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003989bool AsmParser::parseDirectiveBundleAlignMode() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003990 checkForValidSection();
Eli Benderskyf483ff92012-12-20 19:05:53 +00003991
3992 // Expect a single argument: an expression that evaluates to a constant
3993 // in the inclusive range 0-30.
3994 SMLoc ExprLoc = getLexer().getLoc();
3995 int64_t AlignSizePow2;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003996 if (parseAbsoluteExpression(AlignSizePow2))
Eli Benderskyf483ff92012-12-20 19:05:53 +00003997 return true;
3998 else if (getLexer().isNot(AsmToken::EndOfStatement))
3999 return TokError("unexpected token after expression in"
4000 " '.bundle_align_mode' directive");
4001 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
4002 return Error(ExprLoc,
4003 "invalid bundle alignment size (expected between 0 and 30)");
4004
4005 Lex();
4006
4007 // Because of AlignSizePow2's verified range we can safely truncate it to
4008 // unsigned.
4009 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4010 return false;
4011}
4012
Jim Grosbach4b905842013-09-20 23:08:21 +00004013/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004014/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004015bool AsmParser::parseDirectiveBundleLock() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004016 checkForValidSection();
Eli Bendersky802b6282013-01-07 21:51:08 +00004017 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004018
Eli Bendersky802b6282013-01-07 21:51:08 +00004019 if (getLexer().isNot(AsmToken::EndOfStatement)) {
4020 StringRef Option;
4021 SMLoc Loc = getTok().getLoc();
4022 const char *kInvalidOptionError =
Jim Grosbach4b905842013-09-20 23:08:21 +00004023 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004024
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004025 if (parseIdentifier(Option))
Eli Bendersky802b6282013-01-07 21:51:08 +00004026 return Error(Loc, kInvalidOptionError);
4027
4028 if (Option != "align_to_end")
4029 return Error(Loc, kInvalidOptionError);
4030 else if (getLexer().isNot(AsmToken::EndOfStatement))
4031 return Error(Loc,
4032 "unexpected token after '.bundle_lock' directive option");
4033 AlignToEnd = true;
4034 }
4035
Eli Benderskyf483ff92012-12-20 19:05:53 +00004036 Lex();
4037
Eli Bendersky802b6282013-01-07 21:51:08 +00004038 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004039 return false;
4040}
4041
Jim Grosbach4b905842013-09-20 23:08:21 +00004042/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004043/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004044bool AsmParser::parseDirectiveBundleUnlock() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004045 checkForValidSection();
Eli Benderskyf483ff92012-12-20 19:05:53 +00004046
4047 if (getLexer().isNot(AsmToken::EndOfStatement))
4048 return TokError("unexpected token in '.bundle_unlock' directive");
4049 Lex();
4050
4051 getStreamer().EmitBundleUnlock();
4052 return false;
4053}
4054
Jim Grosbach4b905842013-09-20 23:08:21 +00004055/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004056/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004057bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004058 checkForValidSection();
Eli Bendersky17233942013-01-15 22:59:42 +00004059
Petr Hosek67a94a72016-05-28 05:57:48 +00004060 SMLoc NumBytesLoc = Lexer.getLoc();
4061 const MCExpr *NumBytes;
4062 if (parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004063 return true;
4064
4065 int64_t FillExpr = 0;
4066 if (getLexer().isNot(AsmToken::EndOfStatement)) {
4067 if (getLexer().isNot(AsmToken::Comma))
4068 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
4069 Lex();
4070
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004071 if (parseAbsoluteExpression(FillExpr))
Eli Bendersky17233942013-01-15 22:59:42 +00004072 return true;
4073
4074 if (getLexer().isNot(AsmToken::EndOfStatement))
4075 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
4076 }
4077
4078 Lex();
4079
Eli Bendersky17233942013-01-15 22:59:42 +00004080 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004081 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004082
4083 return false;
4084}
4085
Jim Grosbach4b905842013-09-20 23:08:21 +00004086/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004087/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004088bool AsmParser::parseDirectiveLEB128(bool Signed) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004089 checkForValidSection();
Eli Bendersky17233942013-01-15 22:59:42 +00004090 const MCExpr *Value;
4091
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004092 for (;;) {
4093 if (parseExpression(Value))
4094 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004095
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004096 if (Signed)
4097 getStreamer().EmitSLEB128Value(Value);
4098 else
4099 getStreamer().EmitULEB128Value(Value);
Eli Bendersky17233942013-01-15 22:59:42 +00004100
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004101 if (getLexer().is(AsmToken::EndOfStatement))
4102 break;
4103
4104 if (getLexer().isNot(AsmToken::Comma))
4105 return TokError("unexpected token in directive");
4106 Lex();
4107 }
Eli Bendersky17233942013-01-15 22:59:42 +00004108
4109 return false;
4110}
4111
Jim Grosbach4b905842013-09-20 23:08:21 +00004112/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004113/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004114bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004115 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbara5508c82009-06-30 00:33:19 +00004116 for (;;) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004117 StringRef Name;
Jim Grosbachebdf32f2011-09-15 17:56:49 +00004118 SMLoc Loc = getTok().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004119
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004120 if (parseIdentifier(Name))
Jim Grosbachebdf32f2011-09-15 17:56:49 +00004121 return Error(Loc, "expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004122
Jim Grosbach6f482002015-05-18 18:43:14 +00004123 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbara5508c82009-06-30 00:33:19 +00004124
Jim Grosbachebdf32f2011-09-15 17:56:49 +00004125 // Assembler local symbols don't make any sense here. Complain loudly.
4126 if (Sym->isTemporary())
4127 return Error(Loc, "non-local symbol required in directive");
4128
Saleem Abdulrasool4208b612013-08-09 01:52:03 +00004129 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4130 return Error(Loc, "unable to emit symbol attribute");
Daniel Dunbara5508c82009-06-30 00:33:19 +00004131
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004132 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara5508c82009-06-30 00:33:19 +00004133 break;
4134
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004135 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara5508c82009-06-30 00:33:19 +00004136 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004137 Lex();
Daniel Dunbara5508c82009-06-30 00:33:19 +00004138 }
4139 }
4140
Sean Callanan686ed8d2010-01-19 20:22:31 +00004141 Lex();
Jan Wen Voungc7682872010-09-30 01:09:20 +00004142 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004143}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004144
Jim Grosbach4b905842013-09-20 23:08:21 +00004145/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004146/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004147bool AsmParser::parseDirectiveComm(bool IsLocal) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004148 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00004149
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004150 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004151 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004152 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004153 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004154
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004155 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004156 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004157
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004158 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004159 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004160 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004161
4162 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004163 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004164 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004165 return true;
4166
4167 int64_t Pow2Alignment = 0;
4168 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004169 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004170 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004171 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004172 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004173 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004174
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004175 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4176 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004177 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4178
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004179 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004180 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4181 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004182 if (!isPowerOf2_64(Pow2Alignment))
4183 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4184 Pow2Alignment = Log2_64(Pow2Alignment);
4185 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004186 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004187
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004188 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner28ad7542009-07-09 17:25:12 +00004189 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004190
Sean Callanan686ed8d2010-01-19 20:22:31 +00004191 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004192
Chris Lattner28ad7542009-07-09 17:25:12 +00004193 // NOTE: a size of zero for a .comm should create a undefined symbol
4194 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004195 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004196 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004197 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004198
Eric Christopherbc818852010-05-14 01:38:54 +00004199 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004200 // may internally end up wanting an alignment in bytes.
4201 // FIXME: Diagnose overflow.
4202 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004203 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004204 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004205
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004206 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004207 return Error(IDLoc, "invalid symbol redefinition");
4208
Chris Lattner28ad7542009-07-09 17:25:12 +00004209 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004210 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004211 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004212 return false;
4213 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004214
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004215 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004216 return false;
4217}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004218
Jim Grosbach4b905842013-09-20 23:08:21 +00004219/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004220/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004221bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004222 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004223 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004224
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004225 StringRef Str = parseStringToEndOfStatement();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004226 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby56523ce2009-07-13 23:15:14 +00004227 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004228
Sean Callanan686ed8d2010-01-19 20:22:31 +00004229 Lex();
Kevin Enderby56523ce2009-07-13 23:15:14 +00004230
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004231 if (Str.empty())
4232 Error(Loc, ".abort detected. Assembly stopping.");
4233 else
4234 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004235 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004236
4237 return false;
4238}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004239
Jim Grosbach4b905842013-09-20 23:08:21 +00004240/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004241/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004242bool AsmParser::parseDirectiveInclude() {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004243 if (getLexer().isNot(AsmToken::String))
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004244 return TokError("expected string in '.include' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004245
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004246 // Allow the strings to have escaped octal character sequence.
4247 std::string Filename;
4248 if (parseEscapedString(Filename))
4249 return true;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004250 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00004251 Lex();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004252
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004253 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004254 return TokError("unexpected token in '.include' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004255
Chris Lattner693fbb82009-07-16 06:14:39 +00004256 // Attempt to switch the lexer to the included file before consuming the end
4257 // of statement to avoid losing it when we switch.
Jim Grosbach4b905842013-09-20 23:08:21 +00004258 if (enterIncludeFile(Filename)) {
Daniel Dunbard8a18452010-07-18 18:31:45 +00004259 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner693fbb82009-07-16 06:14:39 +00004260 return true;
4261 }
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004262
4263 return false;
4264}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004265
Jim Grosbach4b905842013-09-20 23:08:21 +00004266/// parseDirectiveIncbin
Kevin Enderby109f25c2011-12-14 21:47:48 +00004267/// ::= .incbin "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004268bool AsmParser::parseDirectiveIncbin() {
Kevin Enderby109f25c2011-12-14 21:47:48 +00004269 if (getLexer().isNot(AsmToken::String))
4270 return TokError("expected string in '.incbin' directive");
4271
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004272 // Allow the strings to have escaped octal character sequence.
4273 std::string Filename;
4274 if (parseEscapedString(Filename))
4275 return true;
Kevin Enderby109f25c2011-12-14 21:47:48 +00004276 SMLoc IncbinLoc = getLexer().getLoc();
4277 Lex();
4278
4279 if (getLexer().isNot(AsmToken::EndOfStatement))
4280 return TokError("unexpected token in '.incbin' directive");
4281
Kevin Enderby109f25c2011-12-14 21:47:48 +00004282 // Attempt to process the included file.
Jim Grosbach4b905842013-09-20 23:08:21 +00004283 if (processIncbinFile(Filename)) {
Kevin Enderby109f25c2011-12-14 21:47:48 +00004284 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
4285 return true;
4286 }
4287
4288 return false;
4289}
4290
Jim Grosbach4b905842013-09-20 23:08:21 +00004291/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004292/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4293bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004294 TheCondStack.push_back(TheCondState);
4295 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004296 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004297 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004298 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004299 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004300 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004301 return true;
4302
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004303 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004304 return TokError("unexpected token in '.if' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004305
Sean Callanan686ed8d2010-01-19 20:22:31 +00004306 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004307
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004308 switch (DirKind) {
4309 default:
4310 llvm_unreachable("unsupported directive");
4311 case DK_IF:
4312 case DK_IFNE:
4313 break;
4314 case DK_IFEQ:
4315 ExprValue = ExprValue == 0;
4316 break;
4317 case DK_IFGE:
4318 ExprValue = ExprValue >= 0;
4319 break;
4320 case DK_IFGT:
4321 ExprValue = ExprValue > 0;
4322 break;
4323 case DK_IFLE:
4324 ExprValue = ExprValue <= 0;
4325 break;
4326 case DK_IFLT:
4327 ExprValue = ExprValue < 0;
4328 break;
4329 }
4330
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004331 TheCondState.CondMet = ExprValue;
4332 TheCondState.Ignore = !TheCondState.CondMet;
4333 }
4334
4335 return false;
4336}
4337
Jim Grosbach4b905842013-09-20 23:08:21 +00004338/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004339/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004340bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004341 TheCondStack.push_back(TheCondState);
4342 TheCondState.TheCond = AsmCond::IfCond;
4343
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004344 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004345 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004346 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004347 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004348
4349 if (getLexer().isNot(AsmToken::EndOfStatement))
4350 return TokError("unexpected token in '.ifb' directive");
4351
4352 Lex();
4353
4354 TheCondState.CondMet = ExpectBlank == Str.empty();
4355 TheCondState.Ignore = !TheCondState.CondMet;
4356 }
4357
4358 return false;
4359}
4360
Jim Grosbach4b905842013-09-20 23:08:21 +00004361/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004362/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004363/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004364bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004365 TheCondStack.push_back(TheCondState);
4366 TheCondState.TheCond = AsmCond::IfCond;
4367
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004368 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004369 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004370 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004371 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004372
4373 if (getLexer().isNot(AsmToken::Comma))
4374 return TokError("unexpected token in '.ifc' directive");
4375
4376 Lex();
4377
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004378 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004379
4380 if (getLexer().isNot(AsmToken::EndOfStatement))
4381 return TokError("unexpected token in '.ifc' directive");
4382
4383 Lex();
4384
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004385 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004386 TheCondState.Ignore = !TheCondState.CondMet;
4387 }
4388
4389 return false;
4390}
4391
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004392/// parseDirectiveIfeqs
4393/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004394bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004395 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004396 if (ExpectEqual)
4397 TokError("expected string parameter for '.ifeqs' directive");
4398 else
4399 TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004400 eatToEndOfStatement();
4401 return true;
4402 }
4403
4404 StringRef String1 = getTok().getStringContents();
4405 Lex();
4406
4407 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004408 if (ExpectEqual)
4409 TokError("expected comma after first string for '.ifeqs' directive");
4410 else
4411 TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004412 eatToEndOfStatement();
4413 return true;
4414 }
4415
4416 Lex();
4417
4418 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004419 if (ExpectEqual)
4420 TokError("expected string parameter for '.ifeqs' directive");
4421 else
4422 TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004423 eatToEndOfStatement();
4424 return true;
4425 }
4426
4427 StringRef String2 = getTok().getStringContents();
4428 Lex();
4429
4430 TheCondStack.push_back(TheCondState);
4431 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004432 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004433 TheCondState.Ignore = !TheCondState.CondMet;
4434
4435 return false;
4436}
4437
Jim Grosbach4b905842013-09-20 23:08:21 +00004438/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004439/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004440bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004441 StringRef Name;
4442 TheCondStack.push_back(TheCondState);
4443 TheCondState.TheCond = AsmCond::IfCond;
4444
4445 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004446 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004447 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004448 if (parseIdentifier(Name))
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004449 return TokError("expected identifier after '.ifdef'");
4450
4451 Lex();
4452
Jim Grosbach6f482002015-05-18 18:43:14 +00004453 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004454
4455 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004456 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004457 else
Craig Topper353eda42014-04-24 06:44:33 +00004458 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004459 TheCondState.Ignore = !TheCondState.CondMet;
4460 }
4461
4462 return false;
4463}
4464
Jim Grosbach4b905842013-09-20 23:08:21 +00004465/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004466/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004467bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004468 if (TheCondState.TheCond != AsmCond::IfCond &&
4469 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper2172ad62013-04-22 04:24:02 +00004470 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4471 " an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004472 TheCondState.TheCond = AsmCond::ElseIfCond;
4473
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004474 bool LastIgnoreState = false;
4475 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004476 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004477 if (LastIgnoreState || TheCondState.CondMet) {
4478 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004479 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004480 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004481 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004482 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004483 return true;
4484
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004485 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004486 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004487
Sean Callanan686ed8d2010-01-19 20:22:31 +00004488 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004489 TheCondState.CondMet = ExprValue;
4490 TheCondState.Ignore = !TheCondState.CondMet;
4491 }
4492
4493 return false;
4494}
4495
Jim Grosbach4b905842013-09-20 23:08:21 +00004496/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004497/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004498bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004499 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004500 return TokError("unexpected token in '.else' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004501
Sean Callanan686ed8d2010-01-19 20:22:31 +00004502 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004503
4504 if (TheCondState.TheCond != AsmCond::IfCond &&
4505 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper2172ad62013-04-22 04:24:02 +00004506 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4507 ".elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004508 TheCondState.TheCond = AsmCond::ElseCond;
4509 bool LastIgnoreState = false;
4510 if (!TheCondStack.empty())
4511 LastIgnoreState = TheCondStack.back().Ignore;
4512 if (LastIgnoreState || TheCondState.CondMet)
4513 TheCondState.Ignore = true;
4514 else
4515 TheCondState.Ignore = false;
4516
4517 return false;
4518}
4519
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004520/// parseDirectiveEnd
4521/// ::= .end
4522bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4523 if (getLexer().isNot(AsmToken::EndOfStatement))
4524 return TokError("unexpected token in '.end' directive");
4525
4526 Lex();
4527
4528 while (Lexer.isNot(AsmToken::Eof))
4529 Lex();
4530
4531 return false;
4532}
4533
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004534/// parseDirectiveError
4535/// ::= .err
4536/// ::= .error [string]
4537bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4538 if (!TheCondStack.empty()) {
4539 if (TheCondStack.back().Ignore) {
4540 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004541 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004542 }
4543 }
4544
4545 if (!WithMessage)
4546 return Error(L, ".err encountered");
4547
4548 StringRef Message = ".error directive invoked in source file";
4549 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4550 if (Lexer.isNot(AsmToken::String)) {
4551 TokError(".error argument must be a string");
4552 eatToEndOfStatement();
4553 return true;
4554 }
4555
4556 Message = getTok().getStringContents();
4557 Lex();
4558 }
4559
4560 Error(L, Message);
4561 return true;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004562}
4563
Nico Weber404012b2014-07-24 16:26:06 +00004564/// parseDirectiveWarning
4565/// ::= .warning [string]
4566bool AsmParser::parseDirectiveWarning(SMLoc L) {
4567 if (!TheCondStack.empty()) {
4568 if (TheCondStack.back().Ignore) {
4569 eatToEndOfStatement();
4570 return false;
4571 }
4572 }
4573
4574 StringRef Message = ".warning directive invoked in source file";
4575 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4576 if (Lexer.isNot(AsmToken::String)) {
4577 TokError(".warning argument must be a string");
4578 eatToEndOfStatement();
4579 return true;
4580 }
4581
4582 Message = getTok().getStringContents();
4583 Lex();
4584 }
4585
4586 Warning(L, Message);
4587 return false;
4588}
4589
Jim Grosbach4b905842013-09-20 23:08:21 +00004590/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004591/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00004592bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004593 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004594 return TokError("unexpected token in '.endif' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004595
Sean Callanan686ed8d2010-01-19 20:22:31 +00004596 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004597
Jim Grosbach4b905842013-09-20 23:08:21 +00004598 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004599 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4600 ".else");
4601 if (!TheCondStack.empty()) {
4602 TheCondState = TheCondStack.back();
4603 TheCondStack.pop_back();
4604 }
4605
4606 return false;
4607}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00004608
Eli Bendersky17233942013-01-15 22:59:42 +00004609void AsmParser::initializeDirectiveKindMap() {
4610 DirectiveKindMap[".set"] = DK_SET;
4611 DirectiveKindMap[".equ"] = DK_EQU;
4612 DirectiveKindMap[".equiv"] = DK_EQUIV;
4613 DirectiveKindMap[".ascii"] = DK_ASCII;
4614 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4615 DirectiveKindMap[".string"] = DK_STRING;
4616 DirectiveKindMap[".byte"] = DK_BYTE;
4617 DirectiveKindMap[".short"] = DK_SHORT;
4618 DirectiveKindMap[".value"] = DK_VALUE;
4619 DirectiveKindMap[".2byte"] = DK_2BYTE;
4620 DirectiveKindMap[".long"] = DK_LONG;
4621 DirectiveKindMap[".int"] = DK_INT;
4622 DirectiveKindMap[".4byte"] = DK_4BYTE;
4623 DirectiveKindMap[".quad"] = DK_QUAD;
4624 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00004625 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00004626 DirectiveKindMap[".single"] = DK_SINGLE;
4627 DirectiveKindMap[".float"] = DK_FLOAT;
4628 DirectiveKindMap[".double"] = DK_DOUBLE;
4629 DirectiveKindMap[".align"] = DK_ALIGN;
4630 DirectiveKindMap[".align32"] = DK_ALIGN32;
4631 DirectiveKindMap[".balign"] = DK_BALIGN;
4632 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4633 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4634 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4635 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4636 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4637 DirectiveKindMap[".org"] = DK_ORG;
4638 DirectiveKindMap[".fill"] = DK_FILL;
4639 DirectiveKindMap[".zero"] = DK_ZERO;
4640 DirectiveKindMap[".extern"] = DK_EXTERN;
4641 DirectiveKindMap[".globl"] = DK_GLOBL;
4642 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00004643 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4644 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4645 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4646 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4647 DirectiveKindMap[".reference"] = DK_REFERENCE;
4648 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4649 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4650 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4651 DirectiveKindMap[".comm"] = DK_COMM;
4652 DirectiveKindMap[".common"] = DK_COMMON;
4653 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4654 DirectiveKindMap[".abort"] = DK_ABORT;
4655 DirectiveKindMap[".include"] = DK_INCLUDE;
4656 DirectiveKindMap[".incbin"] = DK_INCBIN;
4657 DirectiveKindMap[".code16"] = DK_CODE16;
4658 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4659 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004660 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00004661 DirectiveKindMap[".irp"] = DK_IRP;
4662 DirectiveKindMap[".irpc"] = DK_IRPC;
4663 DirectiveKindMap[".endr"] = DK_ENDR;
4664 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4665 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4666 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4667 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004668 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4669 DirectiveKindMap[".ifge"] = DK_IFGE;
4670 DirectiveKindMap[".ifgt"] = DK_IFGT;
4671 DirectiveKindMap[".ifle"] = DK_IFLE;
4672 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00004673 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00004674 DirectiveKindMap[".ifb"] = DK_IFB;
4675 DirectiveKindMap[".ifnb"] = DK_IFNB;
4676 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004677 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00004678 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00004679 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00004680 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4681 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4682 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4683 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4684 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004685 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00004686 DirectiveKindMap[".endif"] = DK_ENDIF;
4687 DirectiveKindMap[".skip"] = DK_SKIP;
4688 DirectiveKindMap[".space"] = DK_SPACE;
4689 DirectiveKindMap[".file"] = DK_FILE;
4690 DirectiveKindMap[".line"] = DK_LINE;
4691 DirectiveKindMap[".loc"] = DK_LOC;
4692 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004693 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
4694 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
4695 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00004696 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
David Majnemer408b5e62016-02-05 01:55:49 +00004697 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004698 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
4699 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Eli Bendersky17233942013-01-15 22:59:42 +00004700 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4701 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4702 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4703 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4704 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4705 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4706 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4707 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4708 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4709 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4710 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4711 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4712 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4713 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4714 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4715 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4716 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4717 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4718 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4719 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4720 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00004721 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00004722 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4723 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4724 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00004725 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00004726 DirectiveKindMap[".endm"] = DK_ENDM;
4727 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4728 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004729 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004730 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00004731 DirectiveKindMap[".warning"] = DK_WARNING;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00004732 DirectiveKindMap[".reloc"] = DK_RELOC;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00004733}
4734
Jim Grosbach4b905842013-09-20 23:08:21 +00004735MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004736 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004737
Rafael Espindola34b9c512012-06-03 23:57:14 +00004738 unsigned NestLevel = 0;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004739 for (;;) {
4740 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00004741 if (getLexer().is(AsmToken::Eof)) {
4742 Error(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00004743 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004744 }
4745
Rafael Espindola34b9c512012-06-03 23:57:14 +00004746 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00004747 (getTok().getIdentifier() == ".rept" ||
4748 getTok().getIdentifier() == ".irp" ||
4749 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004750 ++NestLevel;
4751 }
4752
4753 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00004754 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004755 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004756 EndToken = getTok();
4757 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004758 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4759 TokError("unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00004760 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004761 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004762 break;
4763 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004764 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004765 }
4766
Rafael Espindola34b9c512012-06-03 23:57:14 +00004767 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004768 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004769 }
4770
4771 const char *BodyStart = StartToken.getLoc().getPointer();
4772 const char *BodyEnd = EndToken.getLoc().getPointer();
4773 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4774
Rafael Espindola34b9c512012-06-03 23:57:14 +00004775 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004776 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00004777 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004778}
4779
Jim Grosbach4b905842013-09-20 23:08:21 +00004780void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00004781 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004782 OS << ".endr\n";
4783
Rafael Espindola3560ff22014-08-27 20:03:13 +00004784 std::unique_ptr<MemoryBuffer> Instantiation =
4785 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004786
Rafael Espindola34b9c512012-06-03 23:57:14 +00004787 // Create the macro instantiation object and add to the current macro
4788 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00004789 MacroInstantiation *MI = new MacroInstantiation(
4790 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00004791 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004792
Rafael Espindola34b9c512012-06-03 23:57:14 +00004793 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00004794 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00004795 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00004796 Lex();
4797}
4798
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004799/// parseDirectiveRept
4800/// ::= .rep | .rept count
4801bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004802 const MCExpr *CountExpr;
4803 SMLoc CountLoc = getTok().getLoc();
4804 if (parseExpression(CountExpr))
4805 return true;
4806
Rafael Espindola34b9c512012-06-03 23:57:14 +00004807 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00004808 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004809 eatToEndOfStatement();
4810 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4811 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004812
4813 if (Count < 0)
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004814 return Error(CountLoc, "Count is negative");
Rafael Espindola34b9c512012-06-03 23:57:14 +00004815
4816 if (Lexer.isNot(AsmToken::EndOfStatement))
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004817 return TokError("unexpected token in '" + Dir + "' directive");
Rafael Espindola34b9c512012-06-03 23:57:14 +00004818
4819 // Eat the end of statement.
4820 Lex();
4821
4822 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004823 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00004824 if (!M)
4825 return true;
4826
4827 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4828 // to hold the macro body with substitutions.
4829 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004830 raw_svector_ostream OS(Buf);
4831 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00004832 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4833 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00004834 return true;
4835 }
Jim Grosbach4b905842013-09-20 23:08:21 +00004836 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004837
4838 return false;
4839}
4840
Jim Grosbach4b905842013-09-20 23:08:21 +00004841/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00004842/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00004843bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00004844 MCAsmMacroParameter Parameter;
Rafael Espindola768b41c2012-06-15 14:02:34 +00004845
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004846 if (parseIdentifier(Parameter.Name))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004847 return TokError("expected identifier in '.irp' directive");
4848
Rafael Espindola768b41c2012-06-15 14:02:34 +00004849 if (Lexer.isNot(AsmToken::Comma))
4850 return TokError("expected comma in '.irp' directive");
4851
4852 Lex();
4853
Eli Bendersky38274122013-01-14 23:22:36 +00004854 MCAsmMacroArguments A;
Craig Topper353eda42014-04-24 06:44:33 +00004855 if (parseMacroArguments(nullptr, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004856 return true;
4857
4858 // Eat the end of statement.
4859 Lex();
4860
4861 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004862 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00004863 if (!M)
4864 return true;
4865
4866 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4867 // to hold the macro body with substitutions.
4868 SmallString<256> Buf;
4869 raw_svector_ostream OS(Buf);
4870
Craig Topper84008482015-10-10 05:38:14 +00004871 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00004872 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4873 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00004874 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004875 return true;
4876 }
4877
Jim Grosbach4b905842013-09-20 23:08:21 +00004878 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00004879
4880 return false;
4881}
4882
Jim Grosbach4b905842013-09-20 23:08:21 +00004883/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004884/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00004885bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00004886 MCAsmMacroParameter Parameter;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004887
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004888 if (parseIdentifier(Parameter.Name))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004889 return TokError("expected identifier in '.irpc' directive");
4890
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004891 if (Lexer.isNot(AsmToken::Comma))
4892 return TokError("expected comma in '.irpc' directive");
4893
4894 Lex();
4895
Eli Bendersky38274122013-01-14 23:22:36 +00004896 MCAsmMacroArguments A;
Craig Topper353eda42014-04-24 06:44:33 +00004897 if (parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004898 return true;
4899
4900 if (A.size() != 1 || A.front().size() != 1)
4901 return TokError("unexpected token in '.irpc' directive");
4902
4903 // Eat the end of statement.
4904 Lex();
4905
4906 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004907 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004908 if (!M)
4909 return true;
4910
4911 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4912 // to hold the macro body with substitutions.
4913 SmallString<256> Buf;
4914 raw_svector_ostream OS(Buf);
4915
4916 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004917 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00004918 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004919 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004920
Toma Tabacu217116e2015-04-27 10:50:29 +00004921 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
4922 // This is undocumented, but GAS seems to support it.
4923 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004924 return true;
4925 }
4926
Jim Grosbach4b905842013-09-20 23:08:21 +00004927 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004928
4929 return false;
4930}
4931
Jim Grosbach4b905842013-09-20 23:08:21 +00004932bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004933 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00004934 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004935
4936 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00004937 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004938 assert(getLexer().is(AsmToken::EndOfStatement));
4939
Jim Grosbach4b905842013-09-20 23:08:21 +00004940 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004941 return false;
4942}
Rafael Espindola12d73d12010-09-11 16:45:15 +00004943
Jim Grosbach4b905842013-09-20 23:08:21 +00004944bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00004945 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00004946 const MCExpr *Value;
4947 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004948 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00004949 return true;
4950 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4951 if (!MCE)
4952 return Error(ExprLoc, "unexpected expression in _emit");
4953 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00004954 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00004955 return Error(ExprLoc, "literal value out of range for directive");
4956
Craig Topper7d5b2312015-10-10 05:25:02 +00004957 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00004958 return false;
4959}
4960
Jim Grosbach4b905842013-09-20 23:08:21 +00004961bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00004962 const MCExpr *Value;
4963 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004964 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00004965 return true;
4966 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4967 if (!MCE)
4968 return Error(ExprLoc, "unexpected expression in align");
4969 uint64_t IntValue = MCE->getValue();
4970 if (!isPowerOf2_64(IntValue))
4971 return Error(ExprLoc, "literal value not a power of two greater then zero");
4972
Craig Topper7d5b2312015-10-10 05:25:02 +00004973 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00004974 return false;
4975}
4976
Chad Rosierf43fcf52013-02-13 21:27:17 +00004977// We are comparing pointers, but the pointers are relative to a single string.
4978// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00004979static int rewritesSort(const AsmRewrite *AsmRewriteA,
4980 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00004981 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4982 return -1;
4983 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4984 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004985
Chad Rosierfce4fab2013-04-08 17:43:47 +00004986 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4987 // rewrite to the same location. Make sure the SizeDirective rewrite is
4988 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4989 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00004990 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4991 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004992 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00004993
Jim Grosbach4b905842013-09-20 23:08:21 +00004994 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4995 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004996 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00004997 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00004998}
4999
Jim Grosbach4b905842013-09-20 23:08:21 +00005000bool AsmParser::parseMSInlineAsm(
5001 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
5002 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
5003 SmallVectorImpl<std::string> &Constraints,
5004 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5005 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005006 SmallVector<void *, 4> InputDecls;
5007 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005008 SmallVector<bool, 4> InputDeclsAddressOf;
5009 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005010 SmallVector<std::string, 4> InputConstraints;
5011 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005012 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005013
Benjamin Kramer1a136112013-02-15 20:37:21 +00005014 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005015
5016 // Prime the lexer.
5017 Lex();
5018
5019 // While we have input, parse each statement.
5020 unsigned InputIdx = 0;
5021 unsigned OutputIdx = 0;
5022 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005023 // Parse curly braces marking block start/end
5024 if (parseCurlyBlockScope(AsmStrRewrites))
5025 continue;
5026
Eli Friedman0f4871d2012-10-22 23:58:19 +00005027 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005028 if (parseStatement(Info, &SI))
Chad Rosierf1f6a722012-10-19 22:57:33 +00005029 return true;
Chad Rosier8bce6642012-10-18 15:49:34 +00005030
Chad Rosier149e8e02012-12-12 22:45:52 +00005031 if (Info.ParseError)
5032 return true;
5033
Benjamin Kramer1a136112013-02-15 20:37:21 +00005034 if (Info.Opcode == ~0U)
5035 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005036
Benjamin Kramer1a136112013-02-15 20:37:21 +00005037 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005038
Benjamin Kramer1a136112013-02-15 20:37:21 +00005039 // Build the list of clobbers, outputs and inputs.
5040 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005041 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005042
Benjamin Kramer1a136112013-02-15 20:37:21 +00005043 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005044 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005045 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005046
Benjamin Kramer1a136112013-02-15 20:37:21 +00005047 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005048 if (Operand.isReg() && !Operand.needAddressOf() &&
5049 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005050 unsigned NumDefs = Desc.getNumDefs();
5051 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005052 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5053 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005054 continue;
5055 }
5056
5057 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005058 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005059 if (SymName.empty())
5060 continue;
5061
David Blaikie960ea3f2014-06-08 16:18:35 +00005062 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005063 if (!OpDecl)
5064 continue;
5065
5066 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005067 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005068 if (isOutput) {
5069 ++InputIdx;
5070 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005071 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005072 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005073 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005074 } else {
5075 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005076 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5077 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005078 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005079 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005080 }
Reid Kleckneree088972013-12-10 18:27:32 +00005081
5082 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005083 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5084 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005085 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005086 }
5087
5088 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005089 NumOutputs = OutputDecls.size();
5090 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005091
5092 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005093 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5094 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5095 ClobberRegs.end());
5096 Clobbers.assign(ClobberRegs.size(), std::string());
5097 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5098 raw_string_ostream OS(Clobbers[I]);
5099 IP->printRegName(OS, ClobberRegs[I]);
5100 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005101
5102 // Merge the various outputs and inputs. Output are expected first.
5103 if (NumOutputs || NumInputs) {
5104 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005105 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005106 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005107 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005108 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005109 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005110 }
5111 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005112 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005113 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005114 }
5115 }
5116
5117 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005118 std::string AsmStringIR;
5119 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005120 StringRef ASMString =
5121 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5122 const char *AsmStart = ASMString.begin();
5123 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005124 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005125 for (const AsmRewrite &AR : AsmStrRewrites) {
5126 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005127 if (Kind == AOK_Delete)
5128 continue;
5129
David Majnemer8114c1a2014-06-23 02:17:16 +00005130 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005131 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005132
Chad Rosier120eefd2013-03-19 17:32:17 +00005133 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005134 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005135 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005136
Chad Rosier37e755c2012-10-23 17:43:43 +00005137 // Skip the original expression.
5138 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005139 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005140 continue;
5141 }
5142
Chad Rosierff10ed12013-04-12 16:26:42 +00005143 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005144 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005145 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005146 default:
5147 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005148 case AOK_Imm:
David Majnemer8114c1a2014-06-23 02:17:16 +00005149 OS << "$$" << AR.Val;
Chad Rosier11c42f22012-10-26 18:04:20 +00005150 break;
5151 case AOK_ImmPrefix:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005152 OS << "$$";
Chad Rosier8bce6642012-10-18 15:49:34 +00005153 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005154 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005155 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005156 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005157 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005158 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005159 break;
5160 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005161 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005162 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005163 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005164 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005165 default: break;
5166 case 8: OS << "byte ptr "; break;
5167 case 16: OS << "word ptr "; break;
5168 case 32: OS << "dword ptr "; break;
5169 case 64: OS << "qword ptr "; break;
5170 case 80: OS << "xword ptr "; break;
5171 case 128: OS << "xmmword ptr "; break;
5172 case 256: OS << "ymmword ptr "; break;
5173 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005174 break;
5175 case AOK_Emit:
5176 OS << ".byte";
5177 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005178 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005179 // MS alignment directives are measured in bytes. If the native assembler
5180 // measures alignment in bytes, we can pass it straight through.
5181 OS << ".align";
5182 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5183 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005184
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005185 // Alignment is in log2 form, so print that instead and skip the original
5186 // immediate.
5187 unsigned Val = AR.Val;
5188 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005189 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005190 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5191 break;
5192 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005193 case AOK_EVEN:
5194 OS << ".even";
5195 break;
Chad Rosierf0e87202012-10-25 20:41:34 +00005196 case AOK_DotOperator:
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005197 // Insert the dot if the user omitted it.
Alp Tokere69170a2014-06-26 22:52:05 +00005198 OS.flush();
5199 if (AsmStringIR.back() != '.')
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005200 OS << '.';
David Majnemer8114c1a2014-06-23 02:17:16 +00005201 OS << AR.Val;
Chad Rosierf0e87202012-10-25 20:41:34 +00005202 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005203 case AOK_EndOfStatement:
5204 OS << "\n\t";
5205 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005206 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005207
Chad Rosier8bce6642012-10-18 15:49:34 +00005208 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005209 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005210 }
5211
5212 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005213 if (AsmStart != AsmEnd)
5214 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005215
5216 AsmString = OS.str();
5217 return false;
5218}
5219
Pete Cooper80d21cb2015-06-22 19:35:57 +00005220namespace llvm {
5221namespace MCParserUtils {
5222
5223/// Returns whether the given symbol is used anywhere in the given expression,
5224/// or subexpressions.
5225static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5226 switch (Value->getKind()) {
5227 case MCExpr::Binary: {
5228 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5229 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5230 isSymbolUsedInExpression(Sym, BE->getRHS());
5231 }
5232 case MCExpr::Target:
5233 case MCExpr::Constant:
5234 return false;
5235 case MCExpr::SymbolRef: {
5236 const MCSymbol &S =
5237 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5238 if (S.isVariable())
5239 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5240 return &S == Sym;
5241 }
5242 case MCExpr::Unary:
5243 return isSymbolUsedInExpression(
5244 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5245 }
5246
5247 llvm_unreachable("Unknown expr kind!");
5248}
5249
5250bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5251 MCAsmParser &Parser, MCSymbol *&Sym,
5252 const MCExpr *&Value) {
5253 MCAsmLexer &Lexer = Parser.getLexer();
5254
5255 // FIXME: Use better location, we should use proper tokens.
5256 SMLoc EqualLoc = Lexer.getLoc();
5257
5258 if (Parser.parseExpression(Value)) {
5259 Parser.TokError("missing expression");
5260 Parser.eatToEndOfStatement();
5261 return true;
5262 }
5263
5264 // Note: we don't count b as used in "a = b". This is to allow
5265 // a = b
5266 // b = c
5267
5268 if (Lexer.isNot(AsmToken::EndOfStatement))
5269 return Parser.TokError("unexpected token in assignment");
5270
5271 // Eat the end of statement marker.
5272 Parser.Lex();
5273
5274 // Validate that the LHS is allowed to be a variable (either it has not been
5275 // used as a symbol, or it is an absolute symbol).
5276 Sym = Parser.getContext().lookupSymbol(Name);
5277 if (Sym) {
5278 // Diagnose assignment to a label.
5279 //
5280 // FIXME: Diagnostics. Note the location of the definition as a label.
5281 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5282 if (isSymbolUsedInExpression(Sym, Value))
5283 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005284 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5285 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005286 ; // Allow redefinitions of undefined symbols only used in directives.
5287 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5288 ; // Allow redefinitions of variables that haven't yet been used.
5289 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5290 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5291 else if (!Sym->isVariable())
5292 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5293 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5294 return Parser.Error(EqualLoc,
5295 "invalid reassignment of non-absolute variable '" +
5296 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005297 } else if (Name == ".") {
Rafael Espindola7ae65d82015-11-04 23:59:18 +00005298 Parser.getStreamer().emitValueToOffset(Value, 0);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005299 return false;
5300 } else
5301 Sym = Parser.getContext().getOrCreateSymbol(Name);
5302
5303 Sym->setRedefinable(allow_redef);
5304
5305 return false;
5306}
5307
5308} // namespace MCParserUtils
5309} // namespace llvm
5310
Daniel Dunbar01e36072010-07-17 02:26:10 +00005311/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005312MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
5313 MCStreamer &Out, const MCAsmInfo &MAI) {
Jim Grosbach345768c2011-08-16 18:33:49 +00005314 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005315}