blob: c4f0d441f1dda1e509124fcfb491a9d81b226585 [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"
Evan Cheng76792992011-07-20 05:58:47 +000031#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000032#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000033#include "llvm/MC/MCStreamer.h"
Daniel Dunbarae7ac012009-06-29 23:43:14 +000034#include "llvm/MC/MCSymbol.h"
Evan Cheng11424442011-07-26 00:24:13 +000035#include "llvm/MC/MCTargetAsmParser.h"
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +000036#include "llvm/Support/CommandLine.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 <set>
45#include <string>
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000046#include <vector>
Chris Lattnerb0133452009-06-21 20:16:42 +000047using namespace llvm;
48
Eric Christophera7c32732012-12-18 00:30:54 +000049MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
Nick Lewyckyac612272012-10-19 07:00:09 +000050
Daniel Dunbar86033402010-07-12 17:54:38 +000051namespace {
Eli Benderskya313ae62013-01-16 18:56:50 +000052/// \brief Helper types for tracking macro definitions.
53typedef std::vector<AsmToken> MCAsmMacroArgument;
54typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000055
56struct MCAsmMacroParameter {
57 StringRef Name;
58 MCAsmMacroArgument Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000059 bool Required;
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +000060 bool Vararg;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000061
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +000062 MCAsmMacroParameter() : Required(false), Vararg(false) {}
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000063};
64
Eli Benderskya313ae62013-01-16 18:56:50 +000065typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
66
67struct MCAsmMacro {
68 StringRef Name;
69 StringRef Body;
70 MCAsmMacroParameters Parameters;
71
72public:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +000073 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
74 : Name(N), Body(B), Parameters(std::move(P)) {}
Eli Benderskya313ae62013-01-16 18:56:50 +000075};
76
Daniel Dunbar43235712010-07-18 18:54:11 +000077/// \brief Helper class for storing information about an active macro
78/// instantiation.
79struct MacroInstantiation {
Daniel Dunbar43235712010-07-18 18:54:11 +000080 /// The location of the instantiation.
81 SMLoc InstantiationLoc;
82
Daniel Dunbar40f1d852012-12-01 01:38:48 +000083 /// The buffer where parsing should resume upon instantiation completion.
84 int ExitBuffer;
85
Daniel Dunbar43235712010-07-18 18:54:11 +000086 /// The location where parsing should resume upon instantiation completion.
87 SMLoc ExitLoc;
88
Nico Weber155dccd12014-07-24 17:08:39 +000089 /// The depth of TheCondStack at the start of the instantiation.
90 size_t CondStackDepth;
91
Daniel Dunbar43235712010-07-18 18:54:11 +000092public:
Rafael Espindola9eef18c2014-08-27 19:49:03 +000093 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
Daniel Dunbar43235712010-07-18 18:54:11 +000094};
95
Eli Friedman0f4871d2012-10-22 23:58:19 +000096struct ParseStatementInfo {
Jim Grosbach4b905842013-09-20 23:08:21 +000097 /// \brief The parsed operands from the last parsed statement.
David Blaikie960ea3f2014-06-08 16:18:35 +000098 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
Eli Friedman0f4871d2012-10-22 23:58:19 +000099
Jim Grosbach4b905842013-09-20 23:08:21 +0000100 /// \brief The opcode from the last parsed instruction.
Eli Friedman0f4871d2012-10-22 23:58:19 +0000101 unsigned Opcode;
102
Jim Grosbach4b905842013-09-20 23:08:21 +0000103 /// \brief Was there an error parsing the inline assembly?
Chad Rosier149e8e02012-12-12 22:45:52 +0000104 bool ParseError;
105
Eli Friedman0f4871d2012-10-22 23:58:19 +0000106 SmallVectorImpl<AsmRewrite> *AsmRewrites;
107
Craig Topper353eda42014-04-24 06:44:33 +0000108 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000109 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier149e8e02012-12-12 22:45:52 +0000110 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000111};
112
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000113/// \brief The concrete assembly parser instance.
114class AsmParser : public MCAsmParser {
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000115 AsmParser(const AsmParser &) = delete;
116 void operator=(const AsmParser &) = delete;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000117private:
118 AsmLexer Lexer;
119 MCContext &Ctx;
120 MCStreamer &Out;
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000121 const MCAsmInfo &MAI;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000122 SourceMgr &SrcMgr;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000123 SourceMgr::DiagHandlerTy SavedDiagHandler;
124 void *SavedDiagContext;
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000125 std::unique_ptr<MCAsmParserExtension> PlatformParser;
Rafael Espindola82065cb2011-04-11 21:49:50 +0000126
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000127 /// This is the current buffer index we're lexing from as managed by the
128 /// SourceMgr object.
Alp Tokera55b95b2014-07-06 10:33:31 +0000129 unsigned CurBuffer;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000130
131 AsmCond TheCondState;
132 std::vector<AsmCond> TheCondStack;
133
Jim Grosbach4b905842013-09-20 23:08:21 +0000134 /// \brief maps directive names to handler methods in parser
Eli Bendersky17233942013-01-15 22:59:42 +0000135 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000136 /// addDirectiveHandler.
Eli Bendersky17233942013-01-15 22:59:42 +0000137 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000138
Jim Grosbach4b905842013-09-20 23:08:21 +0000139 /// \brief Map of currently defined macros.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000140 StringMap<MCAsmMacro> MacroMap;
Daniel Dunbarc1f58ec2010-07-18 18:47:21 +0000141
Jim Grosbach4b905842013-09-20 23:08:21 +0000142 /// \brief Stack of active macro instantiations.
Daniel Dunbar43235712010-07-18 18:54:11 +0000143 std::vector<MacroInstantiation*> ActiveMacros;
144
Jim Grosbach4b905842013-09-20 23:08:21 +0000145 /// \brief List of bodies of anonymous macros.
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +0000146 std::deque<MCAsmMacro> MacroLikeBodies;
147
Daniel Dunbar828984f2010-07-18 18:38:02 +0000148 /// Boolean tracking whether macro substitution is enabled.
Eli Benderskyc2f6f922013-01-14 18:08:41 +0000149 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000150
Toma Tabacu217116e2015-04-27 10:50:29 +0000151 /// \brief Keeps track of how many .macro's have been instantiated.
152 unsigned NumOfMacroInstantiations;
153
Daniel Dunbar43325c42010-09-09 22:42:56 +0000154 /// Flag tracking whether any errors have been encountered.
155 unsigned HadError : 1;
156
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000157 /// The values from the last parsed cpp hash file line comment if any.
158 StringRef CppHashFilename;
159 int64_t CppHashLineNumber;
160 SMLoc CppHashLoc;
Alp Tokera55b95b2014-07-06 10:33:31 +0000161 unsigned CppHashBuf;
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000162 /// When generating dwarf for assembly source files we need to calculate the
163 /// logical line number based on the last parsed cpp hash file line comment
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000164 /// and current line. Since this is slow and messes up the SourceMgr's
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000165 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
166 SMLoc LastQueryIDLoc;
Alp Tokera55b95b2014-07-06 10:33:31 +0000167 unsigned LastQueryBuffer;
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000168 unsigned LastQueryLine;
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000169
Devang Patela173ee52012-01-31 18:14:05 +0000170 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
171 unsigned AssemblerDialect;
172
Jim Grosbach4b905842013-09-20 23:08:21 +0000173 /// \brief is Darwin compatibility enabled?
Preston Gurd05500642012-09-19 20:36:12 +0000174 bool IsDarwin;
175
Jim Grosbach4b905842013-09-20 23:08:21 +0000176 /// \brief Are we parsing ms-style inline assembly?
Chad Rosier49963552012-10-13 00:26:04 +0000177 bool ParsingInlineAsm;
178
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000179public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000180 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000181 const MCAsmInfo &MAI);
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000182 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000183
Craig Topper59be68f2014-03-08 07:14:16 +0000184 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000185
Craig Topper59be68f2014-03-08 07:14:16 +0000186 void addDirectiveHandler(StringRef Directive,
187 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000188 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000189 }
190
Toma Tabacu11e14a92015-04-21 11:50:52 +0000191 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
192 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
193 }
194
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000195public:
196 /// @name MCAsmParser Interface
197 /// {
198
Craig Topper59be68f2014-03-08 07:14:16 +0000199 SourceMgr &getSourceManager() override { return SrcMgr; }
200 MCAsmLexer &getLexer() override { return Lexer; }
201 MCContext &getContext() override { return Ctx; }
202 MCStreamer &getStreamer() override { return Out; }
203 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000204 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000205 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000206 else
207 return AssemblerDialect;
208 }
Craig Topper59be68f2014-03-08 07:14:16 +0000209 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000210 AssemblerDialect = i;
211 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000212
Craig Topper59be68f2014-03-08 07:14:16 +0000213 void Note(SMLoc L, const Twine &Msg,
214 ArrayRef<SMRange> Ranges = None) override;
215 bool Warning(SMLoc L, const Twine &Msg,
216 ArrayRef<SMRange> Ranges = None) override;
217 bool Error(SMLoc L, const Twine &Msg,
218 ArrayRef<SMRange> Ranges = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000219
Craig Topper59be68f2014-03-08 07:14:16 +0000220 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000221
Craig Topper59be68f2014-03-08 07:14:16 +0000222 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
223 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000224
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000225 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000226 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier37e755c2012-10-23 17:43:43 +0000227 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000228 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000229 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000230 const MCInstrInfo *MII, const MCInstPrinter *IP,
231 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000232
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000233 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000234 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
235 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
236 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
237 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000238
Jim Grosbach4b905842013-09-20 23:08:21 +0000239 /// \brief Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000240 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000241 bool parseIdentifier(StringRef &Res) override;
242 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000243
Craig Topper59be68f2014-03-08 07:14:16 +0000244 void checkForValidSection() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000245 /// }
246
247private:
Daniel Dunbare5444a82010-09-09 22:42:59 +0000248
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000249 bool parseStatement(ParseStatementInfo &Info,
250 MCAsmParserSemaCallback *SI);
Jim Grosbach4b905842013-09-20 23:08:21 +0000251 void eatToEndOfLine();
252 bool parseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000253
Jim Grosbach4b905842013-09-20 23:08:21 +0000254 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000255 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000256 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000257 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000258 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Rafael Espindola1134ab232011-06-05 02:43:45 +0000259 const SMLoc &L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000260
Eli Benderskya313ae62013-01-16 18:56:50 +0000261 /// \brief Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000262 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000263
264 /// \brief Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000265 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000266
267 /// \brief Lookup a previously defined macro.
268 /// \param Name Macro name.
269 /// \returns Pointer to macro. NULL if no such macro was defined.
Jim Grosbach4b905842013-09-20 23:08:21 +0000270 const MCAsmMacro* lookupMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000271
272 /// \brief Define a new macro with the given name and information.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000273 void defineMacro(StringRef Name, MCAsmMacro Macro);
Eli Benderskya313ae62013-01-16 18:56:50 +0000274
275 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
Jim Grosbach4b905842013-09-20 23:08:21 +0000276 void undefineMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000277
278 /// \brief Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000279 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000280
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000281 /// \brief Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000282 ///
283 /// \param M The macro.
284 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000285 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000286
287 /// \brief Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000288 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000289
David Majnemer91fc4c22014-01-29 18:57:46 +0000290 /// \brief Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000291 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000292
293 /// \brief Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000294 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000295
Jim Grosbach4b905842013-09-20 23:08:21 +0000296 void printMacroInstantiations();
297 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Dmitri Gribenko3238fb72013-05-05 00:40:33 +0000298 ArrayRef<SMRange> Ranges = None) const {
Chris Lattner72845262011-10-16 05:47:55 +0000299 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000300 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000301 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000302
Jim Grosbach4b905842013-09-20 23:08:21 +0000303 /// \brief Enter the specified file. This returns true on failure.
304 bool enterIncludeFile(const std::string &Filename);
305
306 /// \brief Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000307 /// This returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000308 bool processIncbinFile(const std::string &Filename);
Daniel Dunbar43235712010-07-18 18:54:11 +0000309
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000310 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000311 /// current token is not set; clients should ensure Lex() is called
312 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000313 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000314 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000315 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000316 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000317
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000318 /// \brief Parse up to the end of statement and a return the contents from the
319 /// current token until the end of the statement; the current token on exit
320 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000321 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000322
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000323 /// \brief Parse until the end of a statement or a comma is encountered,
324 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000325 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000326
Jim Grosbach4b905842013-09-20 23:08:21 +0000327 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +0000328 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000329
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000330 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
331 MCBinaryExpr::Opcode &Kind);
332
Jim Grosbach4b905842013-09-20 23:08:21 +0000333 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
334 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
335 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000336
Jim Grosbach4b905842013-09-20 23:08:21 +0000337 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000338
Eli Bendersky17233942013-01-15 22:59:42 +0000339 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000340 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000341 DK_NO_DIRECTIVE, // Placeholder
342 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
David Woodhoused6de0d92014-02-01 16:20:59 +0000343 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
344 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky96522722013-01-11 22:55:28 +0000345 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000346 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
Kevin Enderby3aeada22013-08-28 17:50:59 +0000347 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000348 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
349 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
350 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
351 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000352 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
Sid Manning51c35602015-03-18 14:20:54 +0000353 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
354 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
Eli Bendersky17233942013-01-15 22:59:42 +0000355 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
356 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
357 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
358 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
359 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
360 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000361 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
Nico Weber155dccd12014-07-24 17:08:39 +0000362 DK_MACROS_ON, DK_MACROS_OFF,
363 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000364 DK_SLEB128, DK_ULEB128,
Nico Weber404012b2014-07-24 16:26:06 +0000365 DK_ERR, DK_ERROR, DK_WARNING,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000366 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000367 };
368
Jim Grosbach4b905842013-09-20 23:08:21 +0000369 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000370 /// directives parsed by this class.
371 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000372
373 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000374 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
375 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
David Woodhoused6de0d92014-02-01 16:20:59 +0000376 bool parseDirectiveOctaValue(); // ".octa"
Jim Grosbach4b905842013-09-20 23:08:21 +0000377 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
378 bool parseDirectiveFill(); // ".fill"
379 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000380 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000381 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
382 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000383 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000384 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000385
Eli Bendersky17233942013-01-15 22:59:42 +0000386 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000387 bool parseDirectiveFile(SMLoc DirectiveLoc);
388 bool parseDirectiveLine();
389 bool parseDirectiveLoc();
390 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000391
392 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000393 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000394 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000395 bool parseDirectiveCFISections();
396 bool parseDirectiveCFIStartProc();
397 bool parseDirectiveCFIEndProc();
398 bool parseDirectiveCFIDefCfaOffset();
399 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
400 bool parseDirectiveCFIAdjustCfaOffset();
401 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
402 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
403 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
404 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
405 bool parseDirectiveCFIRememberState();
406 bool parseDirectiveCFIRestoreState();
407 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
408 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
409 bool parseDirectiveCFIEscape();
410 bool parseDirectiveCFISignalFrame();
411 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000412
413 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000414 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000415 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000416 bool parseDirectiveEndMacro(StringRef Directive);
417 bool parseDirectiveMacro(SMLoc DirectiveLoc);
418 bool parseDirectiveMacrosOnOff(StringRef Directive);
Eli Bendersky17233942013-01-15 22:59:42 +0000419
Eli Benderskyf483ff92012-12-20 19:05:53 +0000420 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000421 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000422 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000423 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000424 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000425 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000426
Eli Bendersky17233942013-01-15 22:59:42 +0000427 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000428 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000429
430 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000431 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000432
Jim Grosbach4b905842013-09-20 23:08:21 +0000433 /// \brief Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000434 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000435 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000436
Jim Grosbach4b905842013-09-20 23:08:21 +0000437 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000438
Jim Grosbach4b905842013-09-20 23:08:21 +0000439 bool parseDirectiveAbort(); // ".abort"
440 bool parseDirectiveInclude(); // ".include"
441 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000442
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000443 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
444 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000445 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000446 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000447 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000448 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000449 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
450 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000451 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000452 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
453 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
454 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
455 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000456 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000457
Jim Grosbach4b905842013-09-20 23:08:21 +0000458 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000459 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000460
Rafael Espindola34b9c512012-06-03 23:57:14 +0000461 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000462 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
463 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000464 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000465 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000466 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
467 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
468 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000469
Chad Rosierc7f552c2013-02-12 21:33:51 +0000470 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000471 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000472 size_t Len);
473
474 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000475 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000476
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000477 // "end"
478 bool parseDirectiveEnd(SMLoc DirectiveLoc);
479
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000480 // ".err" or ".error"
481 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000482
Nico Weber404012b2014-07-24 16:26:06 +0000483 // ".warning"
484 bool parseDirectiveWarning(SMLoc DirectiveLoc);
485
Eli Bendersky17233942013-01-15 22:59:42 +0000486 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000487};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000488}
Daniel Dunbar86033402010-07-12 17:54:38 +0000489
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000490namespace llvm {
491
492extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000493extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000494extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000495
496}
497
Chris Lattnerc35681b2010-01-19 19:46:13 +0000498enum { DEFAULT_ADDRSPACE = 0 };
499
David Blaikie9f380a32015-03-16 18:06:57 +0000500AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
501 const MCAsmInfo &MAI)
502 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
503 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
Alp Tokera55b95b2014-07-06 10:33:31 +0000504 MacrosEnabledFlag(true), HadError(false), CppHashLineNumber(0),
Oliver Stannardcf6bfb12014-11-03 12:19:03 +0000505 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000506 // Save the old handler.
507 SavedDiagHandler = SrcMgr.getDiagHandler();
508 SavedDiagContext = SrcMgr.getDiagContext();
509 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000510 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000511 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000512
Daniel Dunbarc5011082010-07-12 18:12:02 +0000513 // Initialize the platform / file format parser.
David Blaikie9f380a32015-03-16 18:06:57 +0000514 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
Rafael Espindolae28610d2013-12-09 20:26:40 +0000515 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000516 PlatformParser.reset(createCOFFAsmParser());
517 break;
Rafael Espindolae28610d2013-12-09 20:26:40 +0000518 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000519 PlatformParser.reset(createDarwinAsmParser());
520 IsDarwin = true;
521 break;
Rafael Espindolae28610d2013-12-09 20:26:40 +0000522 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000523 PlatformParser.reset(createELFAsmParser());
524 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000525 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000526
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000527 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000528 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000529
530 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000531}
532
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000533AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000534 assert((HadError || ActiveMacros.empty()) &&
535 "Unexpected active macro instantiation!");
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000536}
537
Jim Grosbach4b905842013-09-20 23:08:21 +0000538void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000539 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000540 for (std::vector<MacroInstantiation *>::const_reverse_iterator
541 it = ActiveMacros.rbegin(),
542 ie = ActiveMacros.rend();
543 it != ie; ++it)
544 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000545 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000546}
547
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000548void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
549 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
550 printMacroInstantiations();
551}
552
Chris Lattnera3a06812011-10-16 04:47:35 +0000553bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000554 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Chris Lattnera3a06812011-10-16 04:47:35 +0000555 return Error(L, Msg, Ranges);
Jim Grosbach4b905842013-09-20 23:08:21 +0000556 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
557 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000558 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000559}
560
Chris Lattnera3a06812011-10-16 04:47:35 +0000561bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000562 HadError = true;
Jim Grosbach4b905842013-09-20 23:08:21 +0000563 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
564 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000565 return true;
566}
567
Jim Grosbach4b905842013-09-20 23:08:21 +0000568bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000569 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000570 unsigned NewBuf =
571 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
572 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000573 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000574
Sean Callanan7a77eae2010-01-21 00:19:58 +0000575 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000576 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000577 return false;
578}
Daniel Dunbar43235712010-07-18 18:54:11 +0000579
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000580/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000581/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000582/// returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000583bool AsmParser::processIncbinFile(const std::string &Filename) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000584 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000585 unsigned NewBuf =
586 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
587 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000588 return true;
589
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000590 // Pick up the bytes from the file and emit them.
Rafael Espindola64e1af82013-07-02 15:49:13 +0000591 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
Kevin Enderby109f25c2011-12-14 21:47:48 +0000592 return false;
593}
594
Alp Tokera55b95b2014-07-06 10:33:31 +0000595void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
596 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000597 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
598 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000599}
600
Sean Callanan7a77eae2010-01-21 00:19:58 +0000601const AsmToken &AsmParser::Lex() {
602 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000603
Sean Callanan7a77eae2010-01-21 00:19:58 +0000604 if (tok->is(AsmToken::Eof)) {
605 // If this is the end of an included file, pop the parent file off the
606 // include stack.
607 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
608 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000609 jumpToLoc(ParentIncludeLoc);
Sean Callanan7a77eae2010-01-21 00:19:58 +0000610 tok = &Lexer.Lex();
611 }
612 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000613
Sean Callanan7a77eae2010-01-21 00:19:58 +0000614 if (tok->is(AsmToken::Error))
Daniel Dunbard8a18452010-07-18 18:31:45 +0000615 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencer530ce852010-10-09 11:00:50 +0000616
Sean Callanan7a77eae2010-01-21 00:19:58 +0000617 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000618}
619
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000620bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000621 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000622 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000623 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000624
Chris Lattner36e02122009-06-21 20:54:55 +0000625 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000626 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000627
628 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000629 AsmCond StartingCondState = TheCondState;
630
Kevin Enderby6469fc22011-11-01 22:27:22 +0000631 // If we are generating dwarf for assembly source files save the initial text
632 // section and generate a .file directive.
633 if (getContext().getGenDwarfForAssembly()) {
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000634 MCSection *Sec = getStreamer().getCurrentSection().first;
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000635 if (!Sec->getBeginSymbol()) {
636 MCSymbol *SectionStartSym = getContext().createTempSymbol();
637 getStreamer().EmitLabel(SectionStartSym);
638 Sec->setBeginSymbol(SectionStartSym);
639 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000640 bool InsertResult = getContext().addGenDwarfSection(Sec);
641 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000642 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000643 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
644 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000645 }
646
Chris Lattner73f36112009-07-02 21:53:43 +0000647 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000648 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman0f4871d2012-10-22 23:58:19 +0000649 ParseStatementInfo Info;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000650 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000651 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000652
Daniel Dunbar43325c42010-09-09 22:42:56 +0000653 // We had an error, validate that one was emitted and recover by skipping to
654 // the next line.
655 assert(HadError && "Parse statement returned an error, but none emitted!");
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000656 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000657 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000658
659 if (TheCondState.TheCond != StartingCondState.TheCond ||
660 TheCondState.Ignore != StartingCondState.Ignore)
661 return TokError("unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000662
663 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000664 const auto &LineTables = getContext().getMCDwarfLineTables();
665 if (!LineTables.empty()) {
666 unsigned Index = 0;
667 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
668 if (File.Name.empty() && Index != 0)
669 TokError("unassigned file number: " + Twine(Index) +
670 " for .file directives");
671 ++Index;
672 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000673 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000674
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000675 // Check to see that all assembler local symbols were actually defined.
676 // Targets that don't do subsections via symbols may not want this, though,
677 // so conservatively exclude them. Only do this if we're finalizing, though,
678 // as otherwise we won't necessarilly have seen everything yet.
679 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
680 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
681 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
Jim Grosbach4b905842013-09-20 23:08:21 +0000682 e = Symbols.end();
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000683 i != e; ++i) {
684 MCSymbol *Sym = i->getValue();
685 // Variable symbols may not be marked as defined, so check those
686 // explicitly. If we know it's a variable, we have a definition for
687 // the purposes of this check.
688 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
689 // FIXME: We would really like to refer back to where the symbol was
690 // first referenced for a source location. We need to add something
691 // to track that. Currently, we just point to the end of the file.
Jim Grosbach4b905842013-09-20 23:08:21 +0000692 printMessage(
693 getLexer().getLoc(), SourceMgr::DK_Error,
694 "assembler local symbol '" + Sym->getName() + "' not defined");
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000695 }
696 }
697
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000698 // Finalize the output stream if there are no errors and if the client wants
699 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000700 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000701 Out.Finish();
702
Chris Lattner73f36112009-07-02 21:53:43 +0000703 return HadError;
Chris Lattner36e02122009-06-21 20:54:55 +0000704}
705
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000706void AsmParser::checkForValidSection() {
Peter Collingbourne2f495b92013-04-17 21:18:16 +0000707 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
Daniel Dunbare5444a82010-09-09 22:42:59 +0000708 TokError("expected section directive before assembly directive");
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000709 Out.InitSections(false);
Daniel Dunbare5444a82010-09-09 22:42:59 +0000710 }
711}
712
Jim Grosbach4b905842013-09-20 23:08:21 +0000713/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000714void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000715 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Sean Callanan686ed8d2010-01-19 20:22:31 +0000716 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000717
Chris Lattnere5074c42009-06-22 01:29:09 +0000718 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000719 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan686ed8d2010-01-19 20:22:31 +0000720 Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000721}
722
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000723StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000724 const char *Start = getTok().getLoc().getPointer();
725
Jim Grosbach4b905842013-09-20 23:08:21 +0000726 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000727 Lex();
728
729 const char *End = getTok().getLoc().getPointer();
730 return StringRef(Start, End - Start);
731}
Chris Lattner78db3622009-06-22 05:51:26 +0000732
Jim Grosbach4b905842013-09-20 23:08:21 +0000733StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000734 const char *Start = getTok().getLoc().getPointer();
735
736 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000737 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000738 Lex();
739
740 const char *End = getTok().getLoc().getPointer();
741 return StringRef(Start, End - Start);
742}
743
Jim Grosbach4b905842013-09-20 23:08:21 +0000744/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000745/// NOTE: This assumes the leading '(' has already been consumed.
746///
747/// parenexpr ::= expr)
748///
Jim Grosbach4b905842013-09-20 23:08:21 +0000749bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
750 if (parseExpression(Res))
751 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000752 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +0000753 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000754 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000755 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +0000756 return false;
757}
Chris Lattner78db3622009-06-22 05:51:26 +0000758
Jim Grosbach4b905842013-09-20 23:08:21 +0000759/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000760/// NOTE: This assumes the leading '[' has already been consumed.
761///
762/// bracketexpr ::= expr]
763///
Jim Grosbach4b905842013-09-20 23:08:21 +0000764bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
765 if (parseExpression(Res))
766 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000767 if (Lexer.isNot(AsmToken::RBrac))
768 return TokError("expected ']' in brackets expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000769 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000770 Lex();
771 return false;
772}
773
Jim Grosbach4b905842013-09-20 23:08:21 +0000774/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000775/// primaryexpr ::= (parenexpr
776/// primaryexpr ::= symbol
777/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +0000778/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +0000779/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +0000780bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000781 SMLoc FirstTokenLoc = getLexer().getLoc();
782 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
783 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +0000784 default:
785 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +0000786 // If we have an error assume that we've already handled it.
787 case AsmToken::Error:
788 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000789 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000790 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000791 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000792 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000793 Res = MCUnaryExpr::createLNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000794 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +0000795 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +0000796 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +0000797 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +0000798 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +0000799 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000800 if (parseIdentifier(Identifier)) {
David Majnemer0c58bc62013-09-25 10:47:21 +0000801 if (FirstTokenKind == AsmToken::Dollar) {
802 if (Lexer.getMAI().getDollarIsPC()) {
803 // This is a '$' reference, which references the current PC. Emit a
804 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000805 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +0000806 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000807 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +0000808 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +0000809 EndLoc = FirstTokenLoc;
810 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +0000811 }
812 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +0000813 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000814 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000815 // Parse symbol variant
816 std::pair<StringRef, StringRef> Split;
817 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +0000818 if (FirstTokenKind == AsmToken::String) {
819 if (Lexer.is(AsmToken::At)) {
820 Lexer.Lex(); // eat @
821 SMLoc AtLoc = getLexer().getLoc();
822 StringRef VName;
823 if (parseIdentifier(VName))
824 return Error(AtLoc, "expected symbol variant after '@'");
825
826 Split = std::make_pair(Identifier, VName);
827 }
828 } else {
829 Split = Identifier.split('@');
830 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000831 } else if (Lexer.is(AsmToken::LParen)) {
832 Lexer.Lex(); // eat (
833 StringRef VName;
834 parseIdentifier(VName);
835 if (Lexer.isNot(AsmToken::RParen)) {
836 return Error(Lexer.getTok().getLoc(),
837 "unexpected token in variant, expected ')'");
838 }
839 Lexer.Lex(); // eat )
840 Split = std::make_pair(Identifier, VName);
841 }
Daniel Dunbar24764322010-08-24 19:13:42 +0000842
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000843 EndLoc = SMLoc::getFromPointer(Identifier.end());
844
Daniel Dunbard20cda02009-10-16 01:34:54 +0000845 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +0000846 StringRef SymbolName = Identifier;
847 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +0000848
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000849 // Lookup the symbol variant if used.
David Peixotto8ad70b32013-12-04 22:43:20 +0000850 if (Split.second.size()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000851 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +0000852 if (Variant != MCSymbolRefExpr::VK_Invalid) {
853 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +0000854 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +0000855 Variant = MCSymbolRefExpr::VK_None;
856 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +0000857 return Error(SMLoc::getFromPointer(Split.second.begin()),
858 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000859 }
860 }
Daniel Dunbar55992562010-03-15 23:51:06 +0000861
Jim Grosbach6f482002015-05-18 18:43:14 +0000862 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +0000863
Daniel Dunbard20cda02009-10-16 01:34:54 +0000864 // If this is an absolute variable reference, substitute it now to preserve
865 // semantics in the face of reassignment.
Daniel Dunbar7a989da2010-05-05 17:41:00 +0000866 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar55992562010-03-15 23:51:06 +0000867 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +0000868 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +0000869
Daniel Dunbar7a989da2010-05-05 17:41:00 +0000870 Res = Sym->getVariableValue();
Daniel Dunbard20cda02009-10-16 01:34:54 +0000871 return false;
872 }
873
874 // Otherwise create a symbol ref.
Jim Grosbach13760bd2015-05-30 01:25:56 +0000875 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Chris Lattner78db3622009-06-22 05:51:26 +0000876 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +0000877 }
David Woodhousef42a6662014-02-01 16:20:54 +0000878 case AsmToken::BigNum:
879 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +0000880 case AsmToken::Integer: {
881 SMLoc Loc = getTok().getLoc();
882 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +0000883 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000884 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000885 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +0000886 // Look for 'b' or 'f' following an Integer as a directional label
887 if (Lexer.getKind() == AsmToken::Identifier) {
888 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +0000889 // Lookup the symbol variant if used.
890 std::pair<StringRef, StringRef> Split = IDVal.split('@');
891 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
892 if (Split.first.size() != IDVal.size()) {
893 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +0000894 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +0000895 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000896 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +0000897 }
Jim Grosbach4b905842013-09-20 23:08:21 +0000898 if (IDVal == "f" || IDVal == "b") {
899 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +0000900 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +0000901 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +0000902 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderby0510b482010-05-17 23:08:19 +0000903 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000904 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +0000905 Lex(); // Eat identifier.
906 }
907 }
Chris Lattner78db3622009-06-22 05:51:26 +0000908 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +0000909 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +0000910 case AsmToken::Real: {
911 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +0000912 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +0000913 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000914 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +0000915 Lex(); // Eat token.
916 return false;
917 }
Chris Lattner6b55cb92010-04-14 04:40:28 +0000918 case AsmToken::Dot: {
919 // This is a '.' reference, which references the current PC. Emit a
920 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000921 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +0000922 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000923 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000924 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +0000925 Lex(); // Eat identifier.
926 return false;
927 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000928 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000929 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +0000930 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000931 case AsmToken::LBrac:
932 if (!PlatformParser->HasBracketExpressions())
933 return TokError("brackets expression not supported on this target");
934 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +0000935 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000936 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000937 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000938 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000939 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000940 Res = MCUnaryExpr::createMinus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000941 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000942 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000943 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000944 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000945 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000946 Res = MCUnaryExpr::createPlus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000947 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000948 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000949 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000950 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000951 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000952 Res = MCUnaryExpr::createNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000953 return false;
Chris Lattner78db3622009-06-22 05:51:26 +0000954 }
955}
Chris Lattner7fdbce72009-06-22 06:32:03 +0000956
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000957bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +0000958 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000959 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +0000960}
961
Daniel Dunbar55f16672010-09-17 02:47:07 +0000962const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +0000963AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000964 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +0000965 // Ask the target implementation about this expression first.
966 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
967 if (NewE)
968 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000969 // Recurse over the given expression, rebuilding it to apply the given variant
970 // if there is exactly one symbol.
971 switch (E->getKind()) {
972 case MCExpr::Target:
973 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +0000974 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000975
976 case MCExpr::SymbolRef: {
977 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
978
979 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000980 TokError("invalid variant on expression '" + getTok().getIdentifier() +
981 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000982 return E;
983 }
984
Jim Grosbach13760bd2015-05-30 01:25:56 +0000985 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +0000986 }
987
988 case MCExpr::Unary: {
989 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +0000990 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +0000991 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +0000992 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000993 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +0000994 }
995
996 case MCExpr::Binary: {
997 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +0000998 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
999 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001000
1001 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001002 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001003
Jim Grosbach4b905842013-09-20 23:08:21 +00001004 if (!LHS)
1005 LHS = BE->getLHS();
1006 if (!RHS)
1007 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001008
Jim Grosbach13760bd2015-05-30 01:25:56 +00001009 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001010 }
1011 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001012
Craig Toppera2886c22012-02-07 05:05:23 +00001013 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001014}
1015
Jim Grosbach4b905842013-09-20 23:08:21 +00001016/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001017///
Jim Grosbachbd164242011-08-20 16:24:13 +00001018/// expr ::= expr &&,|| expr -> lowest.
1019/// expr ::= expr |,^,&,! expr
1020/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1021/// expr ::= expr <<,>> expr
1022/// expr ::= expr +,- expr
1023/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001024/// expr ::= primaryexpr
1025///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001026bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001027 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001028 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001029 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001030 return true;
1031
Daniel Dunbar55f16672010-09-17 02:47:07 +00001032 // As a special case, we support 'a op b @ modifier' by rewriting the
1033 // expression to include the modifier. This is inefficient, but in general we
1034 // expect users to use 'a@modifier op b'.
1035 if (Lexer.getKind() == AsmToken::At) {
1036 Lex();
1037
1038 if (Lexer.isNot(AsmToken::Identifier))
1039 return TokError("unexpected symbol modifier following '@'");
1040
1041 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001042 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001043 if (Variant == MCSymbolRefExpr::VK_Invalid)
1044 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1045
Jim Grosbach4b905842013-09-20 23:08:21 +00001046 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001047 if (!ModifiedRes) {
1048 return TokError("invalid modifier '" + getTok().getIdentifier() +
1049 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001050 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001051
Daniel Dunbar55f16672010-09-17 02:47:07 +00001052 Res = ModifiedRes;
1053 Lex();
1054 }
1055
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001056 // Try to constant fold it up front, if possible.
1057 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001058 if (Res->evaluateAsAbsolute(Value))
1059 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001060
1061 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001062}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001063
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001064bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001065 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001066 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001067}
1068
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001069bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001070 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001071
Daniel Dunbar75630b32009-06-30 02:10:03 +00001072 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001073 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001074 return true;
1075
Jim Grosbach13760bd2015-05-30 01:25:56 +00001076 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001077 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001078
1079 return false;
1080}
1081
Ahmed Bougacha457852f2015-04-28 00:17:39 +00001082unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1083 MCBinaryExpr::Opcode &Kind) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001084 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001085 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001086 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001087
Jim Grosbach4b905842013-09-20 23:08:21 +00001088 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001089 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001090 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001091 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001092 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001093 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001094 return 1;
1095
Jim Grosbach4b905842013-09-20 23:08:21 +00001096 // Low Precedence: |, &, ^
1097 //
1098 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001099 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001100 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001101 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001102 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001103 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001104 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001105 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001106 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001107 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001108
Jim Grosbach4b905842013-09-20 23:08:21 +00001109 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001110 case AsmToken::EqualEqual:
1111 Kind = MCBinaryExpr::EQ;
1112 return 3;
1113 case AsmToken::ExclaimEqual:
1114 case AsmToken::LessGreater:
1115 Kind = MCBinaryExpr::NE;
1116 return 3;
1117 case AsmToken::Less:
1118 Kind = MCBinaryExpr::LT;
1119 return 3;
1120 case AsmToken::LessEqual:
1121 Kind = MCBinaryExpr::LTE;
1122 return 3;
1123 case AsmToken::Greater:
1124 Kind = MCBinaryExpr::GT;
1125 return 3;
1126 case AsmToken::GreaterEqual:
1127 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001128 return 3;
1129
Jim Grosbach4b905842013-09-20 23:08:21 +00001130 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001131 case AsmToken::LessLess:
1132 Kind = MCBinaryExpr::Shl;
1133 return 4;
1134 case AsmToken::GreaterGreater:
Ahmed Bougacha177c1482015-04-28 00:21:32 +00001135 Kind = MAI.shouldUseLogicalShr() ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001136 return 4;
1137
Jim Grosbach4b905842013-09-20 23:08:21 +00001138 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001139 case AsmToken::Plus:
1140 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001141 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001142 case AsmToken::Minus:
1143 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001144 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001145
Jim Grosbach4b905842013-09-20 23:08:21 +00001146 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001147 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001148 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001149 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001150 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001151 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001152 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001153 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001154 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001155 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001156 }
1157}
1158
Jim Grosbach4b905842013-09-20 23:08:21 +00001159/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001160/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001161bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001162 SMLoc &EndLoc) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001163 while (1) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001164 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001165 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001166
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001167 // If the next token is lower precedence than we are allowed to eat, return
1168 // successfully with what we ate already.
1169 if (TokPrec < Precedence)
1170 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001171
Sean Callanan686ed8d2010-01-19 20:22:31 +00001172 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001173
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001174 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001175 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001176 if (parsePrimaryExpr(RHS, EndLoc))
1177 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001178
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001179 // If BinOp binds less tightly with RHS than the operator after RHS, let
1180 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001181 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001182 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001183 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1184 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001185
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001186 // Merge LHS and RHS according to operator.
Jim Grosbach13760bd2015-05-30 01:25:56 +00001187 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001188 }
1189}
1190
Chris Lattner36e02122009-06-21 20:54:55 +00001191/// ParseStatement:
1192/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001193/// ::= Label* Directive ...Operands... EndOfStatement
1194/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001195bool AsmParser::parseStatement(ParseStatementInfo &Info,
1196 MCAsmParserSemaCallback *SI) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001197 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar8271d1bb2010-05-23 18:36:34 +00001198 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001199 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001200 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001201 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001202
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001203 // Statements always start with an identifier or are a full line comment.
Sean Callanan936b0d32010-01-19 21:44:56 +00001204 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001205 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001206 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001207 int64_t LocalLabelVal = -1;
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001208 // A full line comment is a '#' as the first token.
Kevin Enderby72553612011-09-13 23:45:18 +00001209 if (Lexer.is(AsmToken::Hash))
Jim Grosbach4b905842013-09-20 23:08:21 +00001210 return parseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar3f561042011-03-25 17:47:14 +00001211
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001212 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001213 if (Lexer.is(AsmToken::Integer)) {
1214 LocalLabelVal = getTok().getIntVal();
1215 if (LocalLabelVal < 0) {
1216 if (!TheCondState.Ignore)
1217 return TokError("unexpected token at start of statement");
1218 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001219 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001220 IDVal = getTok().getString();
1221 Lex(); // Consume the integer token to be used as an identifier token.
1222 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands41b4a6b2010-07-12 08:16:59 +00001223 if (!TheCondState.Ignore)
1224 return TokError("unexpected token at start of statement");
Kevin Enderby0510b482010-05-17 23:08:19 +00001225 }
1226 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001227 } else if (Lexer.is(AsmToken::Dot)) {
1228 // Treat '.' as a valid identifier in this context.
1229 Lex();
1230 IDVal = ".";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001231 } else if (parseIdentifier(IDVal)) {
Chris Lattner926885c2010-04-17 18:14:27 +00001232 if (!TheCondState.Ignore)
1233 return TokError("unexpected token at start of statement");
1234 IDVal = "";
1235 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001236
Chris Lattner926885c2010-04-17 18:14:27 +00001237 // Handle conditional assembly here before checking for skipping. We
1238 // have to do this so that .endif isn't skipped in a ".if 0" block for
1239 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001240 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001241 DirectiveKindMap.find(IDVal);
1242 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1243 ? DK_NO_DIRECTIVE
1244 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001245 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001246 default:
1247 break;
1248 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001249 case DK_IFEQ:
1250 case DK_IFGE:
1251 case DK_IFGT:
1252 case DK_IFLE:
1253 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001254 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001255 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001256 case DK_IFB:
1257 return parseDirectiveIfb(IDLoc, true);
1258 case DK_IFNB:
1259 return parseDirectiveIfb(IDLoc, false);
1260 case DK_IFC:
1261 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001262 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001263 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001264 case DK_IFNC:
1265 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001266 case DK_IFNES:
1267 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001268 case DK_IFDEF:
1269 return parseDirectiveIfdef(IDLoc, true);
1270 case DK_IFNDEF:
1271 case DK_IFNOTDEF:
1272 return parseDirectiveIfdef(IDLoc, false);
1273 case DK_ELSEIF:
1274 return parseDirectiveElseIf(IDLoc);
1275 case DK_ELSE:
1276 return parseDirectiveElse(IDLoc);
1277 case DK_ENDIF:
1278 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001279 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001280
Eli Bendersky88024712013-01-16 19:32:36 +00001281 // Ignore the statement if in the middle of inactive conditional
1282 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001283 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001284 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001285 return false;
1286 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001287
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001288 // FIXME: Recurse on local labels?
1289
1290 // See what kind of statement we have.
1291 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001292 case AsmToken::Colon: {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001293 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00001294
Chris Lattner36e02122009-06-21 20:54:55 +00001295 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001296 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001297
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001298 // Diagnose attempt to use '.' as a label.
1299 if (IDVal == ".")
1300 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1301
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001302 // Diagnose attempt to use a variable as a label.
1303 //
1304 // FIXME: Diagnostics. Note the location of the definition as a label.
1305 // FIXME: This doesn't diagnose assignment to a symbol which has been
1306 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001307 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001308 if (LocalLabelVal == -1) {
1309 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001310 StringRef RewrittenLabel =
1311 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1312 assert(RewrittenLabel.size() &&
1313 "We should have an internal name here.");
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001314 Info.AsmRewrites->push_back(AsmRewrite(AOK_Label, IDLoc,
1315 IDVal.size(), RewrittenLabel));
1316 IDVal = RewrittenLabel;
1317 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001318 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001319 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001320 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
David Majnemer58cb80c2014-12-24 10:27:50 +00001321
1322 Sym->redefineIfPossible();
1323
Daniel Dunbardeb7ba92010-05-05 19:01:00 +00001324 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001325 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencer530ce852010-10-09 11:00:50 +00001326
Daniel Dunbare73b2672009-08-26 22:13:22 +00001327 // Emit the label.
Chad Rosierf3feab32013-01-07 20:34:12 +00001328 if (!ParsingInlineAsm)
1329 Out.EmitLabel(Sym);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001330
Kevin Enderbye7739d42011-12-09 18:09:40 +00001331 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001332 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001333 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001334 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1335 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001336
Tim Northover1744d0a2013-10-25 12:49:50 +00001337 getTargetParser().onLabelParsed(Sym);
1338
Daniel Dunbar8271d1bb2010-05-23 18:36:34 +00001339 // Consume any end of statement token, if present, to avoid spurious
1340 // AddBlankLine calls().
1341 if (Lexer.is(AsmToken::EndOfStatement)) {
1342 Lex();
1343 if (Lexer.is(AsmToken::Eof))
1344 return false;
1345 }
1346
Eli Friedman0f4871d2012-10-22 23:58:19 +00001347 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001348 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001349
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001350 case AsmToken::Equal:
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001351 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001352 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001353
Jim Grosbach4b905842013-09-20 23:08:21 +00001354 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001355
1356 default: // Normal instruction or directive.
1357 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001358 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001359
1360 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001361 if (areMacrosEnabled())
1362 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1363 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001364 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001365
Michael J. Spencer530ce852010-10-09 11:00:50 +00001366 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001367
Eli Bendersky17233942013-01-15 22:59:42 +00001368 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001369 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001370 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001371 //
Eli Bendersky17233942013-01-15 22:59:42 +00001372 // 1. The target-specific assembly parser. Some directives are target
1373 // specific or may potentially behave differently on certain targets.
1374 // 2. Asm parser extensions. For example, platform-specific parsers
1375 // (like the ELF parser) register themselves as extensions.
1376 // 3. The generic directive parser implemented by this class. These are
1377 // all the directives that behave in a target and platform independent
1378 // manner, or at least have a default behavior that's shared between
1379 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001380
Eli Bendersky17233942013-01-15 22:59:42 +00001381 // First query the target-specific parser. It will return 'true' if it
1382 // isn't interested in this directive.
Akira Hatanakad3590752012-07-05 19:09:33 +00001383 if (!getTargetParser().ParseDirective(ID))
1384 return false;
1385
Alp Tokercb402912014-01-24 17:20:08 +00001386 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001387 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001388 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1389 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001390 if (Handler.first)
1391 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1392
1393 // Finally, if no one else is interested in this directive, it must be
1394 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001395 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001396 default:
1397 break;
1398 case DK_SET:
1399 case DK_EQU:
1400 return parseDirectiveSet(IDVal, true);
1401 case DK_EQUIV:
1402 return parseDirectiveSet(IDVal, false);
1403 case DK_ASCII:
1404 return parseDirectiveAscii(IDVal, false);
1405 case DK_ASCIZ:
1406 case DK_STRING:
1407 return parseDirectiveAscii(IDVal, true);
1408 case DK_BYTE:
1409 return parseDirectiveValue(1);
1410 case DK_SHORT:
1411 case DK_VALUE:
1412 case DK_2BYTE:
1413 return parseDirectiveValue(2);
1414 case DK_LONG:
1415 case DK_INT:
1416 case DK_4BYTE:
1417 return parseDirectiveValue(4);
1418 case DK_QUAD:
1419 case DK_8BYTE:
1420 return parseDirectiveValue(8);
David Woodhoused6de0d92014-02-01 16:20:59 +00001421 case DK_OCTA:
1422 return parseDirectiveOctaValue();
Jim Grosbach4b905842013-09-20 23:08:21 +00001423 case DK_SINGLE:
1424 case DK_FLOAT:
1425 return parseDirectiveRealValue(APFloat::IEEEsingle);
1426 case DK_DOUBLE:
1427 return parseDirectiveRealValue(APFloat::IEEEdouble);
1428 case DK_ALIGN: {
1429 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1430 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1431 }
1432 case DK_ALIGN32: {
1433 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1434 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1435 }
1436 case DK_BALIGN:
1437 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1438 case DK_BALIGNW:
1439 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1440 case DK_BALIGNL:
1441 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1442 case DK_P2ALIGN:
1443 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1444 case DK_P2ALIGNW:
1445 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1446 case DK_P2ALIGNL:
1447 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1448 case DK_ORG:
1449 return parseDirectiveOrg();
1450 case DK_FILL:
1451 return parseDirectiveFill();
1452 case DK_ZERO:
1453 return parseDirectiveZero();
1454 case DK_EXTERN:
1455 eatToEndOfStatement(); // .extern is the default, ignore it.
1456 return false;
1457 case DK_GLOBL:
1458 case DK_GLOBAL:
1459 return parseDirectiveSymbolAttribute(MCSA_Global);
1460 case DK_LAZY_REFERENCE:
1461 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1462 case DK_NO_DEAD_STRIP:
1463 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1464 case DK_SYMBOL_RESOLVER:
1465 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1466 case DK_PRIVATE_EXTERN:
1467 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1468 case DK_REFERENCE:
1469 return parseDirectiveSymbolAttribute(MCSA_Reference);
1470 case DK_WEAK_DEFINITION:
1471 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1472 case DK_WEAK_REFERENCE:
1473 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1474 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1475 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1476 case DK_COMM:
1477 case DK_COMMON:
1478 return parseDirectiveComm(/*IsLocal=*/false);
1479 case DK_LCOMM:
1480 return parseDirectiveComm(/*IsLocal=*/true);
1481 case DK_ABORT:
1482 return parseDirectiveAbort();
1483 case DK_INCLUDE:
1484 return parseDirectiveInclude();
1485 case DK_INCBIN:
1486 return parseDirectiveIncbin();
1487 case DK_CODE16:
1488 case DK_CODE16GCC:
1489 return TokError(Twine(IDVal) + " not supported yet");
1490 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001491 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001492 case DK_IRP:
1493 return parseDirectiveIrp(IDLoc);
1494 case DK_IRPC:
1495 return parseDirectiveIrpc(IDLoc);
1496 case DK_ENDR:
1497 return parseDirectiveEndr(IDLoc);
1498 case DK_BUNDLE_ALIGN_MODE:
1499 return parseDirectiveBundleAlignMode();
1500 case DK_BUNDLE_LOCK:
1501 return parseDirectiveBundleLock();
1502 case DK_BUNDLE_UNLOCK:
1503 return parseDirectiveBundleUnlock();
1504 case DK_SLEB128:
1505 return parseDirectiveLEB128(true);
1506 case DK_ULEB128:
1507 return parseDirectiveLEB128(false);
1508 case DK_SPACE:
1509 case DK_SKIP:
1510 return parseDirectiveSpace(IDVal);
1511 case DK_FILE:
1512 return parseDirectiveFile(IDLoc);
1513 case DK_LINE:
1514 return parseDirectiveLine();
1515 case DK_LOC:
1516 return parseDirectiveLoc();
1517 case DK_STABS:
1518 return parseDirectiveStabs();
1519 case DK_CFI_SECTIONS:
1520 return parseDirectiveCFISections();
1521 case DK_CFI_STARTPROC:
1522 return parseDirectiveCFIStartProc();
1523 case DK_CFI_ENDPROC:
1524 return parseDirectiveCFIEndProc();
1525 case DK_CFI_DEF_CFA:
1526 return parseDirectiveCFIDefCfa(IDLoc);
1527 case DK_CFI_DEF_CFA_OFFSET:
1528 return parseDirectiveCFIDefCfaOffset();
1529 case DK_CFI_ADJUST_CFA_OFFSET:
1530 return parseDirectiveCFIAdjustCfaOffset();
1531 case DK_CFI_DEF_CFA_REGISTER:
1532 return parseDirectiveCFIDefCfaRegister(IDLoc);
1533 case DK_CFI_OFFSET:
1534 return parseDirectiveCFIOffset(IDLoc);
1535 case DK_CFI_REL_OFFSET:
1536 return parseDirectiveCFIRelOffset(IDLoc);
1537 case DK_CFI_PERSONALITY:
1538 return parseDirectiveCFIPersonalityOrLsda(true);
1539 case DK_CFI_LSDA:
1540 return parseDirectiveCFIPersonalityOrLsda(false);
1541 case DK_CFI_REMEMBER_STATE:
1542 return parseDirectiveCFIRememberState();
1543 case DK_CFI_RESTORE_STATE:
1544 return parseDirectiveCFIRestoreState();
1545 case DK_CFI_SAME_VALUE:
1546 return parseDirectiveCFISameValue(IDLoc);
1547 case DK_CFI_RESTORE:
1548 return parseDirectiveCFIRestore(IDLoc);
1549 case DK_CFI_ESCAPE:
1550 return parseDirectiveCFIEscape();
1551 case DK_CFI_SIGNAL_FRAME:
1552 return parseDirectiveCFISignalFrame();
1553 case DK_CFI_UNDEFINED:
1554 return parseDirectiveCFIUndefined(IDLoc);
1555 case DK_CFI_REGISTER:
1556 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00001557 case DK_CFI_WINDOW_SAVE:
1558 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00001559 case DK_MACROS_ON:
1560 case DK_MACROS_OFF:
1561 return parseDirectiveMacrosOnOff(IDVal);
1562 case DK_MACRO:
1563 return parseDirectiveMacro(IDLoc);
Nico Weber155dccd12014-07-24 17:08:39 +00001564 case DK_EXITM:
1565 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001566 case DK_ENDM:
1567 case DK_ENDMACRO:
1568 return parseDirectiveEndMacro(IDVal);
1569 case DK_PURGEM:
1570 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00001571 case DK_END:
1572 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00001573 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00001574 return parseDirectiveError(IDLoc, false);
1575 case DK_ERROR:
1576 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00001577 case DK_WARNING:
1578 return parseDirectiveWarning(IDLoc);
Eli Friedman20b02642010-07-19 04:17:25 +00001579 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00001580
Jim Grosbach758e0cc2012-05-01 18:38:27 +00001581 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00001582 }
Chris Lattner36e02122009-06-21 20:54:55 +00001583
Chad Rosierc7f552c2013-02-12 21:33:51 +00001584 // __asm _emit or __asm __emit
1585 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1586 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001587 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00001588
1589 // __asm align
1590 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001591 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00001592
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001593 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00001594
Chris Lattner7cbfa442010-05-19 23:34:33 +00001595 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00001596 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00001597 ParseInstructionInfo IInfo(Info.AsmRewrites);
Jim Grosbach4b905842013-09-20 23:08:21 +00001598 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, IDLoc,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001599 Info.ParsedOperands);
Chad Rosier149e8e02012-12-12 22:45:52 +00001600 Info.ParseError = HadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00001601
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001602 // Dump the parsed representation, if requested.
1603 if (getShowParsedOperands()) {
1604 SmallString<256> Str;
1605 raw_svector_ostream OS(Str);
1606 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001607 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001608 if (i != 0)
1609 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001610 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001611 }
1612 OS << "]";
1613
Jim Grosbach4b905842013-09-20 23:08:21 +00001614 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001615 }
1616
Oliver Stannard8b273082014-06-19 15:52:37 +00001617 // If we are generating dwarf for the current section then generate a .loc
1618 // directive for the instruction.
Kevin Enderby6469fc22011-11-01 22:27:22 +00001619 if (!HadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00001620 getContext().getGenDwarfSectionSyms().count(
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00001621 getStreamer().getCurrentSection().first)) {
1622 unsigned Line;
1623 if (ActiveMacros.empty())
1624 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1625 else
1626 Line = SrcMgr.FindLineNumber(ActiveMacros.back()->InstantiationLoc,
1627 ActiveMacros.back()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001628
Eli Bendersky88024712013-01-16 19:32:36 +00001629 // If we previously parsed a cpp hash file line comment then make sure the
1630 // current Dwarf File is for the CppHashFilename if not then emit the
1631 // Dwarf File table for it and adjust the line number for the .loc.
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00001632 if (CppHashFilename.size()) {
David Blaikiec714ef42014-03-17 01:52:11 +00001633 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
1634 0, StringRef(), CppHashFilename);
1635 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001636
Jim Grosbach4b905842013-09-20 23:08:21 +00001637 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1638 // cache with the different Loc from the call above we save the last
1639 // info we queried here with SrcMgr.FindLineNumber().
1640 unsigned CppHashLocLineNo;
1641 if (LastQueryIDLoc == CppHashLoc && LastQueryBuffer == CppHashBuf)
1642 CppHashLocLineNo = LastQueryLine;
1643 else {
1644 CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc, CppHashBuf);
1645 LastQueryLine = CppHashLocLineNo;
1646 LastQueryIDLoc = CppHashLoc;
1647 LastQueryBuffer = CppHashBuf;
1648 }
1649 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00001650 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001651
Jim Grosbach4b905842013-09-20 23:08:21 +00001652 getStreamer().EmitDwarfLocDirective(
1653 getContext().getGenDwarfFileNumber(), Line, 0,
1654 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
1655 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00001656 }
1657
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00001658 // If parsing succeeded, match the instruction.
Chad Rosier49963552012-10-13 00:26:04 +00001659 if (!HadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00001660 uint64_t ErrorInfo;
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001661 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1662 Info.ParsedOperands, Out,
1663 ErrorInfo, ParsingInlineAsm);
Chad Rosier49963552012-10-13 00:26:04 +00001664 }
Chris Lattnerf29c0b62010-01-14 22:21:20 +00001665
Chris Lattnera2a9d162010-09-11 16:18:25 +00001666 // Don't skip the rest of the line, the instruction parser is responsible for
1667 // that.
1668 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00001669}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00001670
Jim Grosbach4b905842013-09-20 23:08:21 +00001671/// eatToEndOfLine uses the Lexer to eat the characters to the end of the line
Kevin Enderby72553612011-09-13 23:45:18 +00001672/// since they may not be able to be tokenized to get to the end of line token.
Jim Grosbach4b905842013-09-20 23:08:21 +00001673void AsmParser::eatToEndOfLine() {
Rafael Espindolae0d09082011-10-19 18:48:52 +00001674 if (!Lexer.is(AsmToken::EndOfStatement))
1675 Lexer.LexUntilEndOfLine();
Jim Grosbach4b905842013-09-20 23:08:21 +00001676 // Eat EOL.
1677 Lex();
Kevin Enderby72553612011-09-13 23:45:18 +00001678}
1679
Jim Grosbach4b905842013-09-20 23:08:21 +00001680/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00001681/// ::= # number "filename"
1682/// or just as a full line comment if it doesn't have a number and a string.
Jim Grosbach4b905842013-09-20 23:08:21 +00001683bool AsmParser::parseCppHashLineFilenameComment(const SMLoc &L) {
Kevin Enderby72553612011-09-13 23:45:18 +00001684 Lex(); // Eat the hash token.
1685
1686 if (getLexer().isNot(AsmToken::Integer)) {
1687 // Consume the line since in cases it is not a well-formed line directive,
1688 // as if were simply a full line comment.
Jim Grosbach4b905842013-09-20 23:08:21 +00001689 eatToEndOfLine();
Kevin Enderby72553612011-09-13 23:45:18 +00001690 return false;
1691 }
1692
1693 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00001694 Lex();
1695
1696 if (getLexer().isNot(AsmToken::String)) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001697 eatToEndOfLine();
Kevin Enderby72553612011-09-13 23:45:18 +00001698 return false;
1699 }
1700
1701 StringRef Filename = getTok().getString();
1702 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00001703 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00001704
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001705 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1706 CppHashLoc = L;
1707 CppHashFilename = Filename;
1708 CppHashLineNumber = LineNumber;
Kevin Enderby27121c12012-11-05 21:55:41 +00001709 CppHashBuf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00001710
1711 // Ignore any trailing characters, they're just comment.
Jim Grosbach4b905842013-09-20 23:08:21 +00001712 eatToEndOfLine();
Kevin Enderby72553612011-09-13 23:45:18 +00001713 return false;
1714}
1715
Jim Grosbach4b905842013-09-20 23:08:21 +00001716/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001717/// for the Filename and LineNo if any in the diagnostic.
1718void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001719 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001720 raw_ostream &OS = errs();
1721
1722 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1723 const SMLoc &DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00001724 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1725 unsigned CppHashBuf =
1726 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001727
Jim Grosbach4b905842013-09-20 23:08:21 +00001728 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001729 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00001730 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1731 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
1732 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001733 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1734 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001735 }
1736
Eric Christophera7c32732012-12-18 00:30:54 +00001737 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001738 // manager changed or buffer changed (like in a nested include) then just
1739 // print the normal diagnostic using its Filename and LineNo.
Jim Grosbach4b905842013-09-20 23:08:21 +00001740 if (!Parser->CppHashLineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001741 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00001742 if (Parser->SavedDiagHandler)
1743 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1744 else
Craig Topper353eda42014-04-24 06:44:33 +00001745 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001746 return;
1747 }
1748
Eric Christophera7c32732012-12-18 00:30:54 +00001749 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001750 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1751 // the diagnostic.
Jakub Staszakec2ffa92013-09-16 22:03:38 +00001752 const std::string &Filename = Parser->CppHashFilename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001753
1754 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1755 int CppHashLocLineNo =
1756 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00001757 int LineNo =
1758 Parser->CppHashLineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001759
Jim Grosbach4b905842013-09-20 23:08:21 +00001760 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
1761 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00001762 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001763
Benjamin Kramer47f5e302011-10-16 10:48:29 +00001764 if (Parser->SavedDiagHandler)
1765 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1766 else
Craig Topper353eda42014-04-24 06:44:33 +00001767 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00001768}
1769
Rafael Espindola2c064482012-08-21 18:29:30 +00001770// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1771// difference being that that function accepts '@' as part of identifiers and
1772// we can't do that. AsmLexer.cpp should probably be changed to handle
1773// '@' as a special case when needed.
1774static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001775 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1776 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00001777}
1778
Rafael Espindola34b9c512012-06-03 23:57:14 +00001779bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00001780 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00001781 ArrayRef<MCAsmMacroArgument> A,
1782 bool EnableAtPseudoVariable, const SMLoc &L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00001783 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00001784 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00001785 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00001786 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001787
Preston Gurd05500642012-09-19 20:36:12 +00001788 // A macro without parameters is handled differently on Darwin:
1789 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001790 while (!Body.empty()) {
1791 // Scan for the next substitution.
1792 std::size_t End = Body.size(), Pos = 0;
1793 for (; Pos != End; ++Pos) {
1794 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00001795 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00001796 // This macro has no parameters, look for $0, $1, etc.
1797 if (Body[Pos] != '$' || Pos + 1 == End)
1798 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001799
Rafael Espindola1134ab232011-06-05 02:43:45 +00001800 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00001801 if (Next == '$' || Next == 'n' ||
1802 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00001803 break;
1804 } else {
1805 // This macro has parameters, look for \foo, \bar, etc.
1806 if (Body[Pos] == '\\' && Pos + 1 != End)
1807 break;
1808 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001809 }
1810
1811 // Add the prefix.
1812 OS << Body.slice(0, Pos);
1813
1814 // Check if we reached the end.
1815 if (Pos == End)
1816 break;
1817
Benjamin Kramer513e7442014-02-20 13:36:32 +00001818 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001819 switch (Body[Pos + 1]) {
1820 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00001821 case '$':
1822 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001823 break;
1824
Jim Grosbach4b905842013-09-20 23:08:21 +00001825 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00001826 case 'n':
1827 OS << A.size();
1828 break;
1829
Jim Grosbach4b905842013-09-20 23:08:21 +00001830 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00001831 default: {
1832 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00001833 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00001834 if (Index >= A.size())
1835 break;
1836
1837 // Otherwise substitute with the token values, with spaces eliminated.
Eli Benderskya7b905e2013-01-14 19:00:26 +00001838 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Jim Grosbach4b905842013-09-20 23:08:21 +00001839 ie = A[Index].end();
1840 it != ie; ++it)
Rafael Espindola1134ab232011-06-05 02:43:45 +00001841 OS << it->getString();
1842 break;
1843 }
1844 }
1845 Pos += 2;
1846 } else {
1847 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00001848
1849 // Check for the \@ pseudo-variable.
1850 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00001851 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00001852 else
1853 while (isIdentifierChar(Body[I]) && I + 1 != End)
1854 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00001855
Jim Grosbach4b905842013-09-20 23:08:21 +00001856 const char *Begin = Body.data() + Pos + 1;
1857 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00001858 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00001859
Toma Tabacu217116e2015-04-27 10:50:29 +00001860 if (Argument == "@") {
1861 OS << NumOfMacroInstantiations;
1862 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00001863 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00001864 for (; Index < NParameters; ++Index)
1865 if (Parameters[Index].Name == Argument)
1866 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00001867
Toma Tabacu217116e2015-04-27 10:50:29 +00001868 if (Index == NParameters) {
1869 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
1870 Pos += 3;
1871 else {
1872 OS << '\\' << Argument;
1873 Pos = I;
1874 }
1875 } else {
1876 bool VarargParameter = HasVararg && Index == (NParameters - 1);
1877 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
1878 ie = A[Index].end();
1879 it != ie; ++it)
1880 // We expect no quotes around the string's contents when
1881 // parsing for varargs.
1882 if (it->getKind() != AsmToken::String || VarargParameter)
1883 OS << it->getString();
1884 else
1885 OS << it->getStringContents();
1886
1887 Pos += 1 + Argument.size();
1888 }
Preston Gurd05500642012-09-19 20:36:12 +00001889 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00001890 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001891 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00001892 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00001893 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001894
Rafael Espindola1134ab232011-06-05 02:43:45 +00001895 return false;
1896}
Daniel Dunbar43235712010-07-18 18:54:11 +00001897
Nico Weber2a8f9222014-07-24 16:29:04 +00001898MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00001899 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00001900 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00001901 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00001902
Jim Grosbach4b905842013-09-20 23:08:21 +00001903static bool isOperator(AsmToken::TokenKind kind) {
1904 switch (kind) {
1905 default:
1906 return false;
1907 case AsmToken::Plus:
1908 case AsmToken::Minus:
1909 case AsmToken::Tilde:
1910 case AsmToken::Slash:
1911 case AsmToken::Star:
1912 case AsmToken::Dot:
1913 case AsmToken::Equal:
1914 case AsmToken::EqualEqual:
1915 case AsmToken::Pipe:
1916 case AsmToken::PipePipe:
1917 case AsmToken::Caret:
1918 case AsmToken::Amp:
1919 case AsmToken::AmpAmp:
1920 case AsmToken::Exclaim:
1921 case AsmToken::ExclaimEqual:
1922 case AsmToken::Percent:
1923 case AsmToken::Less:
1924 case AsmToken::LessEqual:
1925 case AsmToken::LessLess:
1926 case AsmToken::LessGreater:
1927 case AsmToken::Greater:
1928 case AsmToken::GreaterEqual:
1929 case AsmToken::GreaterGreater:
1930 return true;
Preston Gurd05500642012-09-19 20:36:12 +00001931 }
1932}
1933
David Majnemer16252452014-01-29 00:07:39 +00001934namespace {
1935class AsmLexerSkipSpaceRAII {
1936public:
1937 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
1938 Lexer.setSkipSpace(SkipSpace);
1939 }
1940
1941 ~AsmLexerSkipSpaceRAII() {
1942 Lexer.setSkipSpace(true);
1943 }
1944
1945private:
1946 AsmLexer &Lexer;
1947};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001948}
David Majnemer16252452014-01-29 00:07:39 +00001949
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00001950bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
1951
1952 if (Vararg) {
1953 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1954 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001955 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00001956 }
1957 return false;
1958 }
1959
Rafael Espindola768b41c2012-06-15 14:02:34 +00001960 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00001961 unsigned AddTokens = 0;
1962
David Majnemer16252452014-01-29 00:07:39 +00001963 // Darwin doesn't use spaces to delmit arguments.
1964 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00001965
1966 for (;;) {
David Majnemer16252452014-01-29 00:07:39 +00001967 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00001968 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00001969
David Majnemer91fc4c22014-01-29 18:57:46 +00001970 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma))
Preston Gurd05500642012-09-19 20:36:12 +00001971 break;
Preston Gurd05500642012-09-19 20:36:12 +00001972
1973 if (Lexer.is(AsmToken::Space)) {
1974 Lex(); // Eat spaces
1975
1976 // Spaces can delimit parameters, but could also be part an expression.
1977 // If the token after a space is an operator, add the token and the next
1978 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00001979 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001980 if (isOperator(Lexer.getKind())) {
Preston Gurd05500642012-09-19 20:36:12 +00001981 // Check to see whether the token is used as an operator,
1982 // or part of an identifier
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001983 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd05500642012-09-19 20:36:12 +00001984 if (*NextChar == ' ')
1985 AddTokens = 2;
1986 }
1987
1988 if (!AddTokens && ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00001989 break;
1990 }
1991 }
1992 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00001993
Jim Grosbach4b905842013-09-20 23:08:21 +00001994 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00001995 // to be able to fill in the remaining default parameter values
1996 if (Lexer.is(AsmToken::EndOfStatement))
1997 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00001998
1999 // Adjust the current parentheses level.
2000 if (Lexer.is(AsmToken::LParen))
2001 ++ParenLevel;
2002 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2003 --ParenLevel;
2004
2005 // Append the token to the current argument list.
2006 MA.push_back(getTok());
Preston Gurd05500642012-09-19 20:36:12 +00002007 if (AddTokens)
2008 AddTokens--;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002009 Lex();
2010 }
Preston Gurd05500642012-09-19 20:36:12 +00002011
Rafael Espindola768b41c2012-06-15 14:02:34 +00002012 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002013 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002014 return false;
2015}
2016
2017// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002018bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002019 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002020 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002021 bool NamedParametersFound = false;
2022 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002023
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002024 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002025 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002026
Rafael Espindola768b41c2012-06-15 14:02:34 +00002027 // Parse two kinds of macro invocations:
2028 // - macros defined without any parameters accept an arbitrary number of them
2029 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002030 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002031 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2032 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002033 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002034 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002035
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002036 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002037 if (parseIdentifier(FA.Name)) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002038 Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002039 eatToEndOfStatement();
2040 return true;
2041 }
2042
2043 if (!Lexer.is(AsmToken::Equal)) {
2044 TokError("expected '=' after formal parameter identifier");
2045 eatToEndOfStatement();
2046 return true;
2047 }
2048 Lex();
2049
2050 NamedParametersFound = true;
2051 }
2052
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002053 if (NamedParametersFound && FA.Name.empty()) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002054 Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002055 eatToEndOfStatement();
2056 return true;
2057 }
2058
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002059 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2060 if (parseMacroArgument(FA.Value, Vararg))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002061 return true;
2062
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002063 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002064 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002065 unsigned FAI = 0;
2066 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002067 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002068 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002069
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002070 if (FAI >= NParameters) {
Oliver Stannard8b273082014-06-19 15:52:37 +00002071 assert(M && "expected macro to be defined");
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002072 Error(IDLoc,
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002073 "parameter named '" + FA.Name + "' does not exist for macro '" +
Saleem Abdulrasool3f44cd72014-03-17 17:13:57 +00002074 M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002075 return true;
2076 }
2077 PI = FAI;
2078 }
2079
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002080 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002081 if (A.size() <= PI)
2082 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002083 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002084
2085 if (FALocs.size() <= PI)
2086 FALocs.resize(PI + 1);
2087
2088 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002089 }
Jim Grosbach206661622012-07-30 22:44:17 +00002090
Preston Gurd242ed3152012-09-19 20:29:04 +00002091 // At the end of the statement, fill in remaining arguments that have
2092 // default values. If there aren't any, then the next argument is
2093 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002094 if (Lexer.is(AsmToken::EndOfStatement)) {
2095 bool Failure = false;
2096 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2097 if (A[FAI].empty()) {
2098 if (M->Parameters[FAI].Required) {
2099 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2100 "missing value for required parameter "
2101 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2102 Failure = true;
2103 }
2104
2105 if (!M->Parameters[FAI].Value.empty())
2106 A[FAI] = M->Parameters[FAI].Value;
2107 }
2108 }
2109 return Failure;
2110 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002111
2112 if (Lexer.is(AsmToken::Comma))
2113 Lex();
2114 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002115
2116 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002117}
2118
Jim Grosbach4b905842013-09-20 23:08:21 +00002119const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002120 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2121 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002122}
2123
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002124void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2125 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002126}
2127
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002128void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002129
Jim Grosbach4b905842013-09-20 23:08:21 +00002130bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbar43235712010-07-18 18:54:11 +00002131 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
2132 // this, although we should protect against infinite loops.
2133 if (ActiveMacros.size() == 20)
2134 return TokError("macros cannot be nested more than 20 levels deep");
2135
Eli Bendersky38274122013-01-14 23:22:36 +00002136 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002137 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002138 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002139
Rafael Espindola1134ab232011-06-05 02:43:45 +00002140 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2141 // to hold the macro body with substitutions.
2142 SmallString<256> Buf;
2143 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002144 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002145
Toma Tabacu217116e2015-04-27 10:50:29 +00002146 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002147 return true;
2148
Eli Bendersky38274122013-01-14 23:22:36 +00002149 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002150 // instantiation.
2151 OS << ".endmacro\n";
2152
Rafael Espindola3560ff22014-08-27 20:03:13 +00002153 std::unique_ptr<MemoryBuffer> Instantiation =
2154 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002155
Daniel Dunbar43235712010-07-18 18:54:11 +00002156 // Create the macro instantiation object and add to the current macro
2157 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002158 MacroInstantiation *MI = new MacroInstantiation(
2159 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002160 ActiveMacros.push_back(MI);
2161
Toma Tabacu217116e2015-04-27 10:50:29 +00002162 ++NumOfMacroInstantiations;
2163
Daniel Dunbar43235712010-07-18 18:54:11 +00002164 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002165 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002166 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002167 Lex();
2168
2169 return false;
2170}
2171
Jim Grosbach4b905842013-09-20 23:08:21 +00002172void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002173 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002174 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002175 Lex();
2176
2177 // Pop the instantiation entry.
2178 delete ActiveMacros.back();
2179 ActiveMacros.pop_back();
2180}
2181
Jim Grosbach4b905842013-09-20 23:08:21 +00002182bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002183 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002184 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002185 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002186 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2187 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002188 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002189
Pete Cooper80d21cb2015-06-22 19:35:57 +00002190 if (!Sym) {
2191 // In the case where we parse an expression starting with a '.', we will
2192 // not generate an error, nor will we create a symbol. In this case we
2193 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002194 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002195 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002196
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002197 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002198 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002199 if (NoDeadStrip)
2200 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2201
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002202 return false;
2203}
2204
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002205/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002206/// ::= identifier
2207/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002208bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002209 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002210 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2211 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002212 // handle this as a context dependent token, instead we detect adjacent tokens
2213 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002214 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2215 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002216
Hans Wennborgce69d772013-10-18 20:46:28 +00002217 // Consume the prefix character, and check for a following identifier.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002218 Lex();
2219 if (Lexer.isNot(AsmToken::Identifier))
2220 return true;
2221
Hans Wennborgce69d772013-10-18 20:46:28 +00002222 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2223 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002224 return true;
2225
2226 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002227 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002228 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002229 Lex();
2230 return false;
2231 }
2232
Jim Grosbach4b905842013-09-20 23:08:21 +00002233 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002234 return true;
2235
Sean Callanan936b0d32010-01-19 21:44:56 +00002236 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002237
Sean Callanan686ed8d2010-01-19 20:22:31 +00002238 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002239
2240 return false;
2241}
2242
Jim Grosbach4b905842013-09-20 23:08:21 +00002243/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002244/// ::= .equ identifier ',' expression
2245/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002246/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002247bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002248 StringRef Name;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002249
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002250 if (parseIdentifier(Name))
Roman Divacky41e6ceb2010-10-28 16:57:58 +00002251 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencer530ce852010-10-09 11:00:50 +00002252
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002253 if (getLexer().isNot(AsmToken::Comma))
Roman Divacky41e6ceb2010-10-28 16:57:58 +00002254 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002255 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002256
Jim Grosbach4b905842013-09-20 23:08:21 +00002257 return parseAssignment(Name, allow_redef, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002258}
2259
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002260bool AsmParser::parseEscapedString(std::string &Data) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002261 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbaref668c12009-08-14 18:19:52 +00002262
2263 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002264 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002265 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2266 if (Str[i] != '\\') {
2267 Data += Str[i];
2268 continue;
2269 }
2270
2271 // Recognize escaped characters. Note that this escape semantics currently
2272 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2273 ++i;
2274 if (i == e)
2275 return TokError("unexpected backslash at end of string");
2276
2277 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002278 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002279 // Consume up to three octal characters.
2280 unsigned Value = Str[i] - '0';
2281
Jim Grosbach4b905842013-09-20 23:08:21 +00002282 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002283 ++i;
2284 Value = Value * 8 + (Str[i] - '0');
2285
Jim Grosbach4b905842013-09-20 23:08:21 +00002286 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002287 ++i;
2288 Value = Value * 8 + (Str[i] - '0');
2289 }
2290 }
2291
2292 if (Value > 255)
2293 return TokError("invalid octal escape sequence (out of range)");
2294
Jim Grosbach4b905842013-09-20 23:08:21 +00002295 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002296 continue;
2297 }
2298
2299 // Otherwise recognize individual escapes.
2300 switch (Str[i]) {
2301 default:
2302 // Just reject invalid escape sequences for now.
2303 return TokError("invalid escape sequence (unrecognized character)");
2304
2305 case 'b': Data += '\b'; break;
2306 case 'f': Data += '\f'; break;
2307 case 'n': Data += '\n'; break;
2308 case 'r': Data += '\r'; break;
2309 case 't': Data += '\t'; break;
2310 case '"': Data += '"'; break;
2311 case '\\': Data += '\\'; break;
2312 }
2313 }
2314
2315 return false;
2316}
2317
Jim Grosbach4b905842013-09-20 23:08:21 +00002318/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002319/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002320bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002321 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002322 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002323
Daniel Dunbara10e5192009-06-24 23:30:00 +00002324 for (;;) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002325 if (getLexer().isNot(AsmToken::String))
Rafael Espindola63760ba2010-10-28 20:02:27 +00002326 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002327
Daniel Dunbaref668c12009-08-14 18:19:52 +00002328 std::string Data;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002329 if (parseEscapedString(Data))
Daniel Dunbaref668c12009-08-14 18:19:52 +00002330 return true;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002331
Rafael Espindola64e1af82013-07-02 15:49:13 +00002332 getStreamer().EmitBytes(Data);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002333 if (ZeroTerminated)
Rafael Espindola64e1af82013-07-02 15:49:13 +00002334 getStreamer().EmitBytes(StringRef("\0", 1));
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002335
Sean Callanan686ed8d2010-01-19 20:22:31 +00002336 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002337
2338 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002339 break;
2340
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002341 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola63760ba2010-10-28 20:02:27 +00002342 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002343 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002344 }
2345 }
2346
Sean Callanan686ed8d2010-01-19 20:22:31 +00002347 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002348 return false;
2349}
2350
Jim Grosbach4b905842013-09-20 23:08:21 +00002351/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002352/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002353bool AsmParser::parseDirectiveValue(unsigned Size) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002354 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002355 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002356
Daniel Dunbara10e5192009-06-24 23:30:00 +00002357 for (;;) {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002358 const MCExpr *Value;
Jim Grosbach76346c32011-06-29 16:05:14 +00002359 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002360 if (parseExpression(Value))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002361 return true;
2362
Daniel Dunbar6738a2e2010-05-23 18:36:38 +00002363 // Special case constant expressions to match code generator.
Jim Grosbach76346c32011-06-29 16:05:14 +00002364 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2365 assert(Size <= 8 && "Invalid size");
2366 uint64_t IntValue = MCE->getValue();
2367 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2368 return Error(ExprLoc, "literal value out of range for directive");
Rafael Espindola64e1af82013-07-02 15:49:13 +00002369 getStreamer().EmitIntValue(IntValue, Size);
Jim Grosbach76346c32011-06-29 16:05:14 +00002370 } else
Kevin Enderby96918bc2014-04-22 17:27:29 +00002371 getStreamer().EmitValue(Value, Size, ExprLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002372
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002373 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002374 break;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002375
Daniel Dunbara10e5192009-06-24 23:30:00 +00002376 // FIXME: Improve diagnostic.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002377 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002378 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002379 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002380 }
2381 }
2382
Sean Callanan686ed8d2010-01-19 20:22:31 +00002383 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002384 return false;
2385}
2386
David Woodhoused6de0d92014-02-01 16:20:59 +00002387/// ParseDirectiveOctaValue
2388/// ::= .octa [ hexconstant (, hexconstant)* ]
2389bool AsmParser::parseDirectiveOctaValue() {
2390 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2391 checkForValidSection();
2392
2393 for (;;) {
2394 if (Lexer.getKind() == AsmToken::Error)
2395 return true;
2396 if (Lexer.getKind() != AsmToken::Integer &&
2397 Lexer.getKind() != AsmToken::BigNum)
2398 return TokError("unknown token in expression");
2399
2400 SMLoc ExprLoc = getLexer().getLoc();
2401 APInt IntValue = getTok().getAPIntVal();
2402 Lex();
2403
2404 uint64_t hi, lo;
2405 if (IntValue.isIntN(64)) {
2406 hi = 0;
2407 lo = IntValue.getZExtValue();
2408 } else if (IntValue.isIntN(128)) {
David Woodhouse6c9a6f92014-02-01 16:52:33 +00002409 // It might actually have more than 128 bits, but the top ones are zero.
2410 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002411 lo = IntValue.getLoBits(64).getZExtValue();
2412 } else
2413 return Error(ExprLoc, "literal value out of range for directive");
2414
2415 if (MAI.isLittleEndian()) {
2416 getStreamer().EmitIntValue(lo, 8);
2417 getStreamer().EmitIntValue(hi, 8);
2418 } else {
2419 getStreamer().EmitIntValue(hi, 8);
2420 getStreamer().EmitIntValue(lo, 8);
2421 }
2422
2423 if (getLexer().is(AsmToken::EndOfStatement))
2424 break;
2425
2426 // FIXME: Improve diagnostic.
2427 if (getLexer().isNot(AsmToken::Comma))
2428 return TokError("unexpected token in directive");
2429 Lex();
2430 }
2431 }
2432
2433 Lex();
2434 return false;
2435}
2436
Jim Grosbach4b905842013-09-20 23:08:21 +00002437/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00002438/// ::= (.single | .double) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002439bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
Daniel Dunbar2af16532010-09-24 01:59:56 +00002440 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002441 checkForValidSection();
Daniel Dunbar2af16532010-09-24 01:59:56 +00002442
2443 for (;;) {
2444 // We don't truly support arithmetic on floating point expressions, so we
2445 // have to manually parse unary prefixes.
2446 bool IsNeg = false;
2447 if (getLexer().is(AsmToken::Minus)) {
2448 Lex();
2449 IsNeg = true;
2450 } else if (getLexer().is(AsmToken::Plus))
2451 Lex();
2452
Michael J. Spencer530ce852010-10-09 11:00:50 +00002453 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby5bbe9572011-03-29 21:11:52 +00002454 getLexer().isNot(AsmToken::Real) &&
2455 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbar2af16532010-09-24 01:59:56 +00002456 return TokError("unexpected token in directive");
2457
2458 // Convert to an APFloat.
2459 APFloat Value(Semantics);
Kevin Enderby5bbe9572011-03-29 21:11:52 +00002460 StringRef IDVal = getTok().getString();
2461 if (getLexer().is(AsmToken::Identifier)) {
2462 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2463 Value = APFloat::getInf(Semantics);
2464 else if (!IDVal.compare_lower("nan"))
2465 Value = APFloat::getNaN(Semantics, false, ~0);
2466 else
2467 return TokError("invalid floating point literal");
2468 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Jim Grosbach4b905842013-09-20 23:08:21 +00002469 APFloat::opInvalidOp)
Daniel Dunbar2af16532010-09-24 01:59:56 +00002470 return TokError("invalid floating point literal");
2471 if (IsNeg)
2472 Value.changeSign();
2473
2474 // Consume the numeric token.
2475 Lex();
2476
2477 // Emit the value as an integer.
2478 APInt AsInt = Value.bitcastToAPInt();
2479 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
Rafael Espindola64e1af82013-07-02 15:49:13 +00002480 AsInt.getBitWidth() / 8);
Daniel Dunbar2af16532010-09-24 01:59:56 +00002481
2482 if (getLexer().is(AsmToken::EndOfStatement))
2483 break;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002484
Daniel Dunbar2af16532010-09-24 01:59:56 +00002485 if (getLexer().isNot(AsmToken::Comma))
2486 return TokError("unexpected token in directive");
2487 Lex();
2488 }
2489 }
2490
2491 Lex();
2492 return false;
2493}
2494
Jim Grosbach4b905842013-09-20 23:08:21 +00002495/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00002496/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002497bool AsmParser::parseDirectiveZero() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002498 checkForValidSection();
Rafael Espindola922e3f42010-09-16 15:03:59 +00002499
2500 int64_t NumBytes;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002501 if (parseAbsoluteExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00002502 return true;
2503
Rafael Espindolab91bac62010-10-05 19:42:57 +00002504 int64_t Val = 0;
2505 if (getLexer().is(AsmToken::Comma)) {
2506 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002507 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00002508 return true;
2509 }
2510
Rafael Espindola922e3f42010-09-16 15:03:59 +00002511 if (getLexer().isNot(AsmToken::EndOfStatement))
2512 return TokError("unexpected token in '.zero' directive");
2513
2514 Lex();
2515
Rafael Espindola64e1af82013-07-02 15:49:13 +00002516 getStreamer().EmitFill(NumBytes, Val);
Rafael Espindola922e3f42010-09-16 15:03:59 +00002517
2518 return false;
2519}
2520
Jim Grosbach4b905842013-09-20 23:08:21 +00002521/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00002522/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002523bool AsmParser::parseDirectiveFill() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002524 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002525
David Majnemer522d3db2014-02-01 07:19:38 +00002526 SMLoc RepeatLoc = getLexer().getLoc();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002527 int64_t NumValues;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002528 if (parseAbsoluteExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002529 return true;
2530
David Majnemer522d3db2014-02-01 07:19:38 +00002531 if (NumValues < 0) {
2532 Warning(RepeatLoc,
2533 "'.fill' directive with negative repeat count has no effect");
2534 NumValues = 0;
2535 }
2536
Roman Divackye33098f2013-09-24 17:44:41 +00002537 int64_t FillSize = 1;
2538 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002539
David Majnemer522d3db2014-02-01 07:19:38 +00002540 SMLoc SizeLoc, ExprLoc;
Roman Divackye33098f2013-09-24 17:44:41 +00002541 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2542 if (getLexer().isNot(AsmToken::Comma))
2543 return TokError("unexpected token in '.fill' directive");
2544 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002545
David Majnemer522d3db2014-02-01 07:19:38 +00002546 SizeLoc = getLexer().getLoc();
Roman Divackye33098f2013-09-24 17:44:41 +00002547 if (parseAbsoluteExpression(FillSize))
2548 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002549
Roman Divackye33098f2013-09-24 17:44:41 +00002550 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2551 if (getLexer().isNot(AsmToken::Comma))
2552 return TokError("unexpected token in '.fill' directive");
2553 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002554
David Majnemer522d3db2014-02-01 07:19:38 +00002555 ExprLoc = getLexer().getLoc();
Roman Divackye33098f2013-09-24 17:44:41 +00002556 if (parseAbsoluteExpression(FillExpr))
2557 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002558
Roman Divackye33098f2013-09-24 17:44:41 +00002559 if (getLexer().isNot(AsmToken::EndOfStatement))
2560 return TokError("unexpected token in '.fill' directive");
2561
2562 Lex();
2563 }
2564 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002565
David Majnemer522d3db2014-02-01 07:19:38 +00002566 if (FillSize < 0) {
2567 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
2568 NumValues = 0;
2569 }
2570 if (FillSize > 8) {
2571 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2572 FillSize = 8;
2573 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002574
David Majnemer522d3db2014-02-01 07:19:38 +00002575 if (!isUInt<32>(FillExpr) && FillSize > 4)
2576 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2577
Alexey Samsonov1b0713c2014-09-02 17:25:29 +00002578 if (NumValues > 0) {
2579 int64_t NonZeroFillSize = FillSize > 4 ? 4 : FillSize;
2580 FillExpr &= ~0ULL >> (64 - NonZeroFillSize * 8);
2581 for (uint64_t i = 0, e = NumValues; i != e; ++i) {
2582 getStreamer().EmitIntValue(FillExpr, NonZeroFillSize);
2583 if (NonZeroFillSize < FillSize)
2584 getStreamer().EmitIntValue(0, FillSize - NonZeroFillSize);
2585 }
David Majnemer522d3db2014-02-01 07:19:38 +00002586 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002587
2588 return false;
2589}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002590
Jim Grosbach4b905842013-09-20 23:08:21 +00002591/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002592/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002593bool AsmParser::parseDirectiveOrg() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002594 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002595
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002596 const MCExpr *Offset;
Jim Grosbachb5912772012-01-27 00:37:08 +00002597 SMLoc Loc = getTok().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002598 if (parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002599 return true;
2600
2601 // Parse optional fill expression.
2602 int64_t FillExpr = 0;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002603 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2604 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002605 return TokError("unexpected token in '.org' directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002606 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00002607
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002608 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002609 return true;
2610
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002611 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002612 return TokError("unexpected token in '.org' directive");
2613 }
2614
Sean Callanan686ed8d2010-01-19 20:22:31 +00002615 Lex();
Daniel Dunbar75630b32009-06-30 02:10:03 +00002616
Jim Grosbachb5912772012-01-27 00:37:08 +00002617 // Only limited forms of relocatable expressions are accepted here, it
2618 // has to be relative to the current section. The streamer will return
2619 // 'true' if the expression wasn't evaluatable.
2620 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2621 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002622
2623 return false;
2624}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002625
Jim Grosbach4b905842013-09-20 23:08:21 +00002626/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002627/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00002628bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002629 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002630
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002631 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002632 int64_t Alignment;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002633 if (parseAbsoluteExpression(Alignment))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002634 return true;
2635
2636 SMLoc MaxBytesLoc;
2637 bool HasFillExpr = false;
2638 int64_t FillExpr = 0;
2639 int64_t MaxBytesToFill = 0;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002640 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2641 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002642 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002643 Lex();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002644
2645 // The fill expression can be omitted while specifying a maximum number of
2646 // alignment bytes, e.g:
2647 // .align 3,,4
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002648 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002649 HasFillExpr = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002650 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002651 return true;
2652 }
2653
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002654 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2655 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002656 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00002657 Lex();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002658
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002659 MaxBytesLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002660 if (parseAbsoluteExpression(MaxBytesToFill))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002661 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002662
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002663 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002664 return TokError("unexpected token in directive");
2665 }
2666 }
2667
Sean Callanan686ed8d2010-01-19 20:22:31 +00002668 Lex();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002669
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002670 if (!HasFillExpr)
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002671 FillExpr = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002672
2673 // Compute alignment in bytes.
2674 if (IsPow2) {
2675 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002676 if (Alignment >= 32) {
2677 Error(AlignmentLoc, "invalid alignment value");
2678 Alignment = 31;
2679 }
2680
Benjamin Kramer63951ad2009-09-06 09:35:10 +00002681 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00002682 } else {
2683 // Reject alignments that aren't a power of two, for gas compatibility.
2684 if (!isPowerOf2_64(Alignment))
2685 Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002686 }
2687
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002688 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002689 if (MaxBytesLoc.isValid()) {
2690 if (MaxBytesToFill < 1) {
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00002691 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00002692 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00002693 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002694 }
2695
2696 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00002697 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00002698 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002699 MaxBytesToFill = 0;
2700 }
2701 }
2702
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002703 // Check whether we should use optimal code alignment for this .align
2704 // directive.
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00002705 const MCSection *Section = getStreamer().getCurrentSection().first;
2706 assert(Section && "must have section to emit alignment");
2707 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002708 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2709 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002710 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002711 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00002712 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00002713 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2714 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00002715 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002716
2717 return false;
2718}
2719
Jim Grosbach4b905842013-09-20 23:08:21 +00002720/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00002721/// ::= .file [number] filename
2722/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00002723bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00002724 // FIXME: I'm not sure what this is.
2725 int64_t FileNumber = -1;
2726 SMLoc FileNumberLoc = getLexer().getLoc();
2727 if (getLexer().is(AsmToken::Integer)) {
2728 FileNumber = getTok().getIntVal();
2729 Lex();
2730
2731 if (FileNumber < 1)
2732 return TokError("file number less than one");
2733 }
2734
2735 if (getLexer().isNot(AsmToken::String))
2736 return TokError("unexpected token in '.file' directive");
2737
2738 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002739 // Allow the strings to have escaped octal character sequence.
2740 std::string Path = getTok().getString();
2741 if (parseEscapedString(Path))
2742 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00002743 Lex();
2744
2745 StringRef Directory;
2746 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002747 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00002748 if (getLexer().is(AsmToken::String)) {
2749 if (FileNumber == -1)
2750 return TokError("explicit path specified, but no file number");
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00002751 if (parseEscapedString(FilenameData))
2752 return true;
2753 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00002754 Directory = Path;
2755 Lex();
2756 } else {
2757 Filename = Path;
2758 }
2759
2760 if (getLexer().isNot(AsmToken::EndOfStatement))
2761 return TokError("unexpected token in '.file' directive");
2762
2763 if (FileNumber == -1)
2764 getStreamer().EmitFileDirective(Filename);
2765 else {
David Blaikiedc3f01e2015-03-09 01:57:13 +00002766 if (getContext().getGenDwarfForAssembly())
Jim Grosbach4b905842013-09-20 23:08:21 +00002767 Error(DirectiveLoc,
2768 "input can't have .file dwarf directives when -g is "
2769 "used to generate dwarf debug info for assembly code");
Eli Bendersky17233942013-01-15 22:59:42 +00002770
David Blaikiec714ef42014-03-17 01:52:11 +00002771 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
2772 0)
Eli Bendersky17233942013-01-15 22:59:42 +00002773 Error(FileNumberLoc, "file number already allocated");
2774 }
2775
2776 return false;
2777}
2778
Jim Grosbach4b905842013-09-20 23:08:21 +00002779/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00002780/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00002781bool AsmParser::parseDirectiveLine() {
Eli Bendersky17233942013-01-15 22:59:42 +00002782 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2783 if (getLexer().isNot(AsmToken::Integer))
2784 return TokError("unexpected token in '.line' directive");
2785
2786 int64_t LineNumber = getTok().getIntVal();
Jim Grosbach4b905842013-09-20 23:08:21 +00002787 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00002788 Lex();
2789
2790 // FIXME: Do something with the .line.
2791 }
2792
2793 if (getLexer().isNot(AsmToken::EndOfStatement))
2794 return TokError("unexpected token in '.line' directive");
2795
2796 return false;
2797}
2798
Jim Grosbach4b905842013-09-20 23:08:21 +00002799/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00002800/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2801/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2802/// The first number is a file number, must have been previously assigned with
2803/// a .file directive, the second number is the line number and optionally the
2804/// third number is a column position (zero if not specified). The remaining
2805/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00002806bool AsmParser::parseDirectiveLoc() {
Eli Bendersky17233942013-01-15 22:59:42 +00002807 if (getLexer().isNot(AsmToken::Integer))
2808 return TokError("unexpected token in '.loc' directive");
2809 int64_t FileNumber = getTok().getIntVal();
2810 if (FileNumber < 1)
2811 return TokError("file number less than one in '.loc' directive");
2812 if (!getContext().isValidDwarfFileNumber(FileNumber))
2813 return TokError("unassigned file number in '.loc' directive");
2814 Lex();
2815
2816 int64_t LineNumber = 0;
2817 if (getLexer().is(AsmToken::Integer)) {
2818 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00002819 if (LineNumber < 0)
2820 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00002821 Lex();
2822 }
2823
2824 int64_t ColumnPos = 0;
2825 if (getLexer().is(AsmToken::Integer)) {
2826 ColumnPos = getTok().getIntVal();
2827 if (ColumnPos < 0)
2828 return TokError("column position less than zero in '.loc' directive");
2829 Lex();
2830 }
2831
2832 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2833 unsigned Isa = 0;
2834 int64_t Discriminator = 0;
2835 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2836 for (;;) {
2837 if (getLexer().is(AsmToken::EndOfStatement))
2838 break;
2839
2840 StringRef Name;
2841 SMLoc Loc = getTok().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002842 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00002843 return TokError("unexpected token in '.loc' directive");
2844
2845 if (Name == "basic_block")
2846 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2847 else if (Name == "prologue_end")
2848 Flags |= DWARF2_FLAG_PROLOGUE_END;
2849 else if (Name == "epilogue_begin")
2850 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2851 else if (Name == "is_stmt") {
2852 Loc = getTok().getLoc();
2853 const MCExpr *Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002854 if (parseExpression(Value))
Eli Bendersky17233942013-01-15 22:59:42 +00002855 return true;
2856 // The expression must be the constant 0 or 1.
2857 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2858 int Value = MCE->getValue();
2859 if (Value == 0)
2860 Flags &= ~DWARF2_FLAG_IS_STMT;
2861 else if (Value == 1)
2862 Flags |= DWARF2_FLAG_IS_STMT;
2863 else
2864 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00002865 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00002866 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2867 }
Craig Topperf15655b2013-04-22 04:22:40 +00002868 } else if (Name == "isa") {
Eli Bendersky17233942013-01-15 22:59:42 +00002869 Loc = getTok().getLoc();
2870 const MCExpr *Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002871 if (parseExpression(Value))
Eli Bendersky17233942013-01-15 22:59:42 +00002872 return true;
2873 // The expression must be a constant greater or equal to 0.
2874 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2875 int Value = MCE->getValue();
2876 if (Value < 0)
2877 return Error(Loc, "isa number less than zero");
2878 Isa = Value;
Craig Topperf15655b2013-04-22 04:22:40 +00002879 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00002880 return Error(Loc, "isa number not a constant value");
2881 }
Craig Topperf15655b2013-04-22 04:22:40 +00002882 } else if (Name == "discriminator") {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002883 if (parseAbsoluteExpression(Discriminator))
Eli Bendersky17233942013-01-15 22:59:42 +00002884 return true;
Craig Topperf15655b2013-04-22 04:22:40 +00002885 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00002886 return Error(Loc, "unknown sub-directive in '.loc' directive");
2887 }
2888
2889 if (getLexer().is(AsmToken::EndOfStatement))
2890 break;
2891 }
2892 }
2893
2894 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2895 Isa, Discriminator, StringRef());
2896
2897 return false;
2898}
2899
Jim Grosbach4b905842013-09-20 23:08:21 +00002900/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00002901/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00002902bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00002903 return TokError("unsupported directive '.stabs'");
2904}
2905
Jim Grosbach4b905842013-09-20 23:08:21 +00002906/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00002907/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00002908bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00002909 StringRef Name;
2910 bool EH = false;
2911 bool Debug = false;
2912
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002913 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00002914 return TokError("Expected an identifier");
2915
2916 if (Name == ".eh_frame")
2917 EH = true;
2918 else if (Name == ".debug_frame")
2919 Debug = true;
2920
2921 if (getLexer().is(AsmToken::Comma)) {
2922 Lex();
2923
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002924 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00002925 return TokError("Expected an identifier");
2926
2927 if (Name == ".eh_frame")
2928 EH = true;
2929 else if (Name == ".debug_frame")
2930 Debug = true;
2931 }
2932
2933 getStreamer().EmitCFISections(EH, Debug);
2934 return false;
2935}
2936
Jim Grosbach4b905842013-09-20 23:08:21 +00002937/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00002938/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00002939bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00002940 StringRef Simple;
2941 if (getLexer().isNot(AsmToken::EndOfStatement))
2942 if (parseIdentifier(Simple) || Simple != "simple")
2943 return TokError("unexpected token in .cfi_startproc directive");
2944
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00002945 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00002946 return false;
2947}
2948
Jim Grosbach4b905842013-09-20 23:08:21 +00002949/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00002950/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00002951bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00002952 getStreamer().EmitCFIEndProc();
2953 return false;
2954}
2955
Jim Grosbach4b905842013-09-20 23:08:21 +00002956/// \brief parse register name or number.
2957bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00002958 SMLoc DirectiveLoc) {
2959 unsigned RegNo;
2960
2961 if (getLexer().isNot(AsmToken::Integer)) {
2962 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2963 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00002964 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00002965 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002966 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00002967
2968 return false;
2969}
2970
Jim Grosbach4b905842013-09-20 23:08:21 +00002971/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00002972/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00002973bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00002974 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00002975 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00002976 return true;
2977
2978 if (getLexer().isNot(AsmToken::Comma))
2979 return TokError("unexpected token in directive");
2980 Lex();
2981
2982 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002983 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00002984 return true;
2985
2986 getStreamer().EmitCFIDefCfa(Register, Offset);
2987 return false;
2988}
2989
Jim Grosbach4b905842013-09-20 23:08:21 +00002990/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00002991/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00002992bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00002993 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002994 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00002995 return true;
2996
2997 getStreamer().EmitCFIDefCfaOffset(Offset);
2998 return false;
2999}
3000
Jim Grosbach4b905842013-09-20 23:08:21 +00003001/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003002/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003003bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003004 int64_t Register1 = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003005 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003006 return true;
3007
3008 if (getLexer().isNot(AsmToken::Comma))
3009 return TokError("unexpected token in directive");
3010 Lex();
3011
3012 int64_t Register2 = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003013 if (parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003014 return true;
3015
3016 getStreamer().EmitCFIRegister(Register1, Register2);
3017 return false;
3018}
3019
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003020/// parseDirectiveCFIWindowSave
3021/// ::= .cfi_window_save
3022bool AsmParser::parseDirectiveCFIWindowSave() {
3023 getStreamer().EmitCFIWindowSave();
3024 return false;
3025}
3026
Jim Grosbach4b905842013-09-20 23:08:21 +00003027/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003028/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003029bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003030 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003031 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003032 return true;
3033
3034 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3035 return false;
3036}
3037
Jim Grosbach4b905842013-09-20 23:08:21 +00003038/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003039/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003040bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003041 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003042 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003043 return true;
3044
3045 getStreamer().EmitCFIDefCfaRegister(Register);
3046 return false;
3047}
3048
Jim Grosbach4b905842013-09-20 23:08:21 +00003049/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003050/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003051bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003052 int64_t Register = 0;
3053 int64_t Offset = 0;
3054
Jim Grosbach4b905842013-09-20 23:08:21 +00003055 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003056 return true;
3057
3058 if (getLexer().isNot(AsmToken::Comma))
3059 return TokError("unexpected token in directive");
3060 Lex();
3061
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003062 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003063 return true;
3064
3065 getStreamer().EmitCFIOffset(Register, Offset);
3066 return false;
3067}
3068
Jim Grosbach4b905842013-09-20 23:08:21 +00003069/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003070/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003071bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003072 int64_t Register = 0;
3073
Jim Grosbach4b905842013-09-20 23:08:21 +00003074 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003075 return true;
3076
3077 if (getLexer().isNot(AsmToken::Comma))
3078 return TokError("unexpected token in directive");
3079 Lex();
3080
3081 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003082 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003083 return true;
3084
3085 getStreamer().EmitCFIRelOffset(Register, Offset);
3086 return false;
3087}
3088
3089static bool isValidEncoding(int64_t Encoding) {
3090 if (Encoding & ~0xff)
3091 return false;
3092
3093 if (Encoding == dwarf::DW_EH_PE_omit)
3094 return true;
3095
3096 const unsigned Format = Encoding & 0xf;
3097 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3098 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3099 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3100 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3101 return false;
3102
3103 const unsigned Application = Encoding & 0x70;
3104 if (Application != dwarf::DW_EH_PE_absptr &&
3105 Application != dwarf::DW_EH_PE_pcrel)
3106 return false;
3107
3108 return true;
3109}
3110
Jim Grosbach4b905842013-09-20 23:08:21 +00003111/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003112/// IsPersonality true for cfi_personality, false for cfi_lsda
3113/// ::= .cfi_personality encoding, [symbol_name]
3114/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003115bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003116 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003117 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003118 return true;
3119 if (Encoding == dwarf::DW_EH_PE_omit)
3120 return false;
3121
3122 if (!isValidEncoding(Encoding))
3123 return TokError("unsupported encoding.");
3124
3125 if (getLexer().isNot(AsmToken::Comma))
3126 return TokError("unexpected token in directive");
3127 Lex();
3128
3129 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003130 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003131 return TokError("expected identifier in directive");
3132
Jim Grosbach6f482002015-05-18 18:43:14 +00003133 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003134
3135 if (IsPersonality)
3136 getStreamer().EmitCFIPersonality(Sym, Encoding);
3137 else
3138 getStreamer().EmitCFILsda(Sym, Encoding);
3139 return false;
3140}
3141
Jim Grosbach4b905842013-09-20 23:08:21 +00003142/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00003143/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003144bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003145 getStreamer().EmitCFIRememberState();
3146 return false;
3147}
3148
Jim Grosbach4b905842013-09-20 23:08:21 +00003149/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00003150/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003151bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003152 getStreamer().EmitCFIRestoreState();
3153 return false;
3154}
3155
Jim Grosbach4b905842013-09-20 23:08:21 +00003156/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00003157/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00003158bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003159 int64_t Register = 0;
3160
Jim Grosbach4b905842013-09-20 23:08:21 +00003161 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003162 return true;
3163
3164 getStreamer().EmitCFISameValue(Register);
3165 return false;
3166}
3167
Jim Grosbach4b905842013-09-20 23:08:21 +00003168/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00003169/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00003170bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003171 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003172 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003173 return true;
3174
3175 getStreamer().EmitCFIRestore(Register);
3176 return false;
3177}
3178
Jim Grosbach4b905842013-09-20 23:08:21 +00003179/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00003180/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003181bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00003182 std::string Values;
3183 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003184 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003185 return true;
3186
3187 Values.push_back((uint8_t)CurrValue);
3188
3189 while (getLexer().is(AsmToken::Comma)) {
3190 Lex();
3191
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003192 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003193 return true;
3194
3195 Values.push_back((uint8_t)CurrValue);
3196 }
3197
3198 getStreamer().EmitCFIEscape(Values);
3199 return false;
3200}
3201
Jim Grosbach4b905842013-09-20 23:08:21 +00003202/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00003203/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00003204bool AsmParser::parseDirectiveCFISignalFrame() {
Eli Bendersky17233942013-01-15 22:59:42 +00003205 if (getLexer().isNot(AsmToken::EndOfStatement))
3206 return Error(getLexer().getLoc(),
3207 "unexpected token in '.cfi_signal_frame'");
3208
3209 getStreamer().EmitCFISignalFrame();
3210 return false;
3211}
3212
Jim Grosbach4b905842013-09-20 23:08:21 +00003213/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00003214/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00003215bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003216 int64_t Register = 0;
3217
Jim Grosbach4b905842013-09-20 23:08:21 +00003218 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003219 return true;
3220
3221 getStreamer().EmitCFIUndefined(Register);
3222 return false;
3223}
3224
Jim Grosbach4b905842013-09-20 23:08:21 +00003225/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00003226/// ::= .macros_on
3227/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00003228bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00003229 if (getLexer().isNot(AsmToken::EndOfStatement))
3230 return Error(getLexer().getLoc(),
3231 "unexpected token in '" + Directive + "' directive");
3232
Jim Grosbach4b905842013-09-20 23:08:21 +00003233 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00003234 return false;
3235}
3236
Jim Grosbach4b905842013-09-20 23:08:21 +00003237/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003238/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00003239bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003240 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003241 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003242 return TokError("expected identifier in '.macro' directive");
3243
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003244 if (getLexer().is(AsmToken::Comma))
3245 Lex();
3246
Eli Bendersky17233942013-01-15 22:59:42 +00003247 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00003248 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003249
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003250 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003251 return Error(Lexer.getLoc(),
3252 "Vararg parameter '" + Parameters.back().Name +
3253 "' should be last one in the list of parameters.");
3254
David Majnemer91fc4c22014-01-29 18:57:46 +00003255 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003256 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00003257 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003258
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003259 if (Lexer.is(AsmToken::Colon)) {
3260 Lex(); // consume ':'
3261
3262 SMLoc QualLoc;
3263 StringRef Qualifier;
3264
3265 QualLoc = Lexer.getLoc();
3266 if (parseIdentifier(Qualifier))
3267 return Error(QualLoc, "missing parameter qualifier for "
3268 "'" + Parameter.Name + "' in macro '" + Name + "'");
3269
3270 if (Qualifier == "req")
3271 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00003272 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003273 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003274 else
3275 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3276 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3277 }
3278
David Majnemer91fc4c22014-01-29 18:57:46 +00003279 if (getLexer().is(AsmToken::Equal)) {
3280 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003281
3282 SMLoc ParamLoc;
3283
3284 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003285 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00003286 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003287
3288 if (Parameter.Required)
3289 Warning(ParamLoc, "pointless default value for required parameter "
3290 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00003291 }
David Majnemer91fc4c22014-01-29 18:57:46 +00003292
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003293 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00003294
3295 if (getLexer().is(AsmToken::Comma))
3296 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003297 }
3298
3299 // Eat the end of statement.
3300 Lex();
3301
3302 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003303 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003304
3305 // Lex the macro definition.
3306 for (;;) {
3307 // Check whether we have reached the end of the file.
3308 if (getLexer().is(AsmToken::Eof))
3309 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3310
3311 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003312 if (getLexer().is(AsmToken::Identifier)) {
3313 if (getTok().getIdentifier() == ".endm" ||
3314 getTok().getIdentifier() == ".endmacro") {
3315 if (MacroDepth == 0) { // Outermost macro.
3316 EndToken = getTok();
3317 Lex();
3318 if (getLexer().isNot(AsmToken::EndOfStatement))
3319 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3320 "' directive");
3321 break;
3322 } else {
3323 // Otherwise we just found the end of an inner macro.
3324 --MacroDepth;
3325 }
3326 } else if (getTok().getIdentifier() == ".macro") {
3327 // We allow nested macros. Those aren't instantiated until the outermost
3328 // macro is expanded so just ignore them for now.
3329 ++MacroDepth;
3330 }
Eli Bendersky17233942013-01-15 22:59:42 +00003331 }
3332
3333 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003334 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00003335 }
3336
Jim Grosbach4b905842013-09-20 23:08:21 +00003337 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00003338 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3339 }
3340
3341 const char *BodyStart = StartToken.getLoc().getPointer();
3342 const char *BodyEnd = EndToken.getLoc().getPointer();
3343 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00003344 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003345 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00003346 return false;
3347}
3348
Jim Grosbach4b905842013-09-20 23:08:21 +00003349/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00003350///
3351/// With the support added for named parameters there may be code out there that
3352/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00003353/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00003354/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00003355/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00003356/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3357/// warning that the positional parameter found in body which have no effect.
3358/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00003359/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00003360/// intended or change the macro to use the named parameters. It is possible
3361/// this warning will trigger when the none of the named parameters are used
3362/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00003363void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00003364 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00003365 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00003366 // If this macro is not defined with named parameters the warning we are
3367 // checking for here doesn't apply.
3368 unsigned NParameters = Parameters.size();
3369 if (NParameters == 0)
3370 return;
3371
3372 bool NamedParametersFound = false;
3373 bool PositionalParametersFound = false;
3374
3375 // Look at the body of the macro for use of both the named parameters and what
3376 // are likely to be positional parameters. This is what expandMacro() is
3377 // doing when it finds the parameters in the body.
3378 while (!Body.empty()) {
3379 // Scan for the next possible parameter.
3380 std::size_t End = Body.size(), Pos = 0;
3381 for (; Pos != End; ++Pos) {
3382 // Check for a substitution or escape.
3383 // This macro is defined with parameters, look for \foo, \bar, etc.
3384 if (Body[Pos] == '\\' && Pos + 1 != End)
3385 break;
3386
3387 // This macro should have parameters, but look for $0, $1, ..., $n too.
3388 if (Body[Pos] != '$' || Pos + 1 == End)
3389 continue;
3390 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00003391 if (Next == '$' || Next == 'n' ||
3392 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00003393 break;
3394 }
3395
3396 // Check if we reached the end.
3397 if (Pos == End)
3398 break;
3399
3400 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00003401 switch (Body[Pos + 1]) {
3402 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00003403 case '$':
3404 break;
3405
Jim Grosbach4b905842013-09-20 23:08:21 +00003406 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00003407 case 'n':
3408 PositionalParametersFound = true;
3409 break;
3410
Jim Grosbach4b905842013-09-20 23:08:21 +00003411 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00003412 default: {
3413 PositionalParametersFound = true;
3414 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00003415 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00003416 }
3417 Pos += 2;
3418 } else {
3419 unsigned I = Pos + 1;
3420 while (isIdentifierChar(Body[I]) && I + 1 != End)
3421 ++I;
3422
Jim Grosbach4b905842013-09-20 23:08:21 +00003423 const char *Begin = Body.data() + Pos + 1;
3424 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00003425 unsigned Index = 0;
3426 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003427 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00003428 break;
3429
3430 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00003431 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3432 Pos += 3;
3433 else {
3434 Pos = I;
3435 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00003436 } else {
3437 NamedParametersFound = true;
3438 Pos += 1 + Argument.size();
3439 }
3440 }
3441 // Update the scan point.
3442 Body = Body.substr(Pos);
3443 }
3444
3445 if (!NamedParametersFound && PositionalParametersFound)
3446 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3447 "used in macro body, possible positional parameter "
3448 "found in body which will have no effect");
3449}
3450
Nico Weber155dccd12014-07-24 17:08:39 +00003451/// parseDirectiveExitMacro
3452/// ::= .exitm
3453bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
3454 if (getLexer().isNot(AsmToken::EndOfStatement))
3455 return TokError("unexpected token in '" + Directive + "' directive");
3456
3457 if (!isInsideMacroInstantiation())
3458 return TokError("unexpected '" + Directive + "' in file, "
3459 "no current macro definition");
3460
3461 // Exit all conditionals that are active in the current macro.
3462 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
3463 TheCondState = TheCondStack.back();
3464 TheCondStack.pop_back();
3465 }
3466
3467 handleMacroExit();
3468 return false;
3469}
3470
Jim Grosbach4b905842013-09-20 23:08:21 +00003471/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00003472/// ::= .endm
3473/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00003474bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00003475 if (getLexer().isNot(AsmToken::EndOfStatement))
3476 return TokError("unexpected token in '" + Directive + "' directive");
3477
3478 // If we are inside a macro instantiation, terminate the current
3479 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00003480 if (isInsideMacroInstantiation()) {
3481 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00003482 return false;
3483 }
3484
3485 // Otherwise, this .endmacro is a stray entry in the file; well formed
3486 // .endmacro directives are handled during the macro definition parsing.
3487 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00003488 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00003489}
3490
Jim Grosbach4b905842013-09-20 23:08:21 +00003491/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00003492/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00003493bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003494 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003495 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003496 return TokError("expected identifier in '.purgem' directive");
3497
3498 if (getLexer().isNot(AsmToken::EndOfStatement))
3499 return TokError("unexpected token in '.purgem' directive");
3500
Jim Grosbach4b905842013-09-20 23:08:21 +00003501 if (!lookupMacro(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003502 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3503
Jim Grosbach4b905842013-09-20 23:08:21 +00003504 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003505 return false;
3506}
Eli Benderskyf483ff92012-12-20 19:05:53 +00003507
Jim Grosbach4b905842013-09-20 23:08:21 +00003508/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00003509/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003510bool AsmParser::parseDirectiveBundleAlignMode() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003511 checkForValidSection();
Eli Benderskyf483ff92012-12-20 19:05:53 +00003512
3513 // Expect a single argument: an expression that evaluates to a constant
3514 // in the inclusive range 0-30.
3515 SMLoc ExprLoc = getLexer().getLoc();
3516 int64_t AlignSizePow2;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003517 if (parseAbsoluteExpression(AlignSizePow2))
Eli Benderskyf483ff92012-12-20 19:05:53 +00003518 return true;
3519 else if (getLexer().isNot(AsmToken::EndOfStatement))
3520 return TokError("unexpected token after expression in"
3521 " '.bundle_align_mode' directive");
3522 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3523 return Error(ExprLoc,
3524 "invalid bundle alignment size (expected between 0 and 30)");
3525
3526 Lex();
3527
3528 // Because of AlignSizePow2's verified range we can safely truncate it to
3529 // unsigned.
3530 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3531 return false;
3532}
3533
Jim Grosbach4b905842013-09-20 23:08:21 +00003534/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00003535/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00003536bool AsmParser::parseDirectiveBundleLock() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003537 checkForValidSection();
Eli Bendersky802b6282013-01-07 21:51:08 +00003538 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00003539
Eli Bendersky802b6282013-01-07 21:51:08 +00003540 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3541 StringRef Option;
3542 SMLoc Loc = getTok().getLoc();
3543 const char *kInvalidOptionError =
Jim Grosbach4b905842013-09-20 23:08:21 +00003544 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00003545
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003546 if (parseIdentifier(Option))
Eli Bendersky802b6282013-01-07 21:51:08 +00003547 return Error(Loc, kInvalidOptionError);
3548
3549 if (Option != "align_to_end")
3550 return Error(Loc, kInvalidOptionError);
3551 else if (getLexer().isNot(AsmToken::EndOfStatement))
3552 return Error(Loc,
3553 "unexpected token after '.bundle_lock' directive option");
3554 AlignToEnd = true;
3555 }
3556
Eli Benderskyf483ff92012-12-20 19:05:53 +00003557 Lex();
3558
Eli Bendersky802b6282013-01-07 21:51:08 +00003559 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00003560 return false;
3561}
3562
Jim Grosbach4b905842013-09-20 23:08:21 +00003563/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00003564/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00003565bool AsmParser::parseDirectiveBundleUnlock() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003566 checkForValidSection();
Eli Benderskyf483ff92012-12-20 19:05:53 +00003567
3568 if (getLexer().isNot(AsmToken::EndOfStatement))
3569 return TokError("unexpected token in '.bundle_unlock' directive");
3570 Lex();
3571
3572 getStreamer().EmitBundleUnlock();
3573 return false;
3574}
3575
Jim Grosbach4b905842013-09-20 23:08:21 +00003576/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00003577/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003578bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003579 checkForValidSection();
Eli Bendersky17233942013-01-15 22:59:42 +00003580
3581 int64_t NumBytes;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003582 if (parseAbsoluteExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00003583 return true;
3584
3585 int64_t FillExpr = 0;
3586 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3587 if (getLexer().isNot(AsmToken::Comma))
3588 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3589 Lex();
3590
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003591 if (parseAbsoluteExpression(FillExpr))
Eli Bendersky17233942013-01-15 22:59:42 +00003592 return true;
3593
3594 if (getLexer().isNot(AsmToken::EndOfStatement))
3595 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3596 }
3597
3598 Lex();
3599
3600 if (NumBytes <= 0)
Jim Grosbach4b905842013-09-20 23:08:21 +00003601 return TokError("invalid number of bytes in '" + Twine(IDVal) +
3602 "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003603
3604 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Rafael Espindola64e1af82013-07-02 15:49:13 +00003605 getStreamer().EmitFill(NumBytes, FillExpr);
Eli Bendersky17233942013-01-15 22:59:42 +00003606
3607 return false;
3608}
3609
Jim Grosbach4b905842013-09-20 23:08:21 +00003610/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00003611/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003612bool AsmParser::parseDirectiveLEB128(bool Signed) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003613 checkForValidSection();
Eli Bendersky17233942013-01-15 22:59:42 +00003614 const MCExpr *Value;
3615
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00003616 for (;;) {
3617 if (parseExpression(Value))
3618 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003619
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00003620 if (Signed)
3621 getStreamer().EmitSLEB128Value(Value);
3622 else
3623 getStreamer().EmitULEB128Value(Value);
Eli Bendersky17233942013-01-15 22:59:42 +00003624
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00003625 if (getLexer().is(AsmToken::EndOfStatement))
3626 break;
3627
3628 if (getLexer().isNot(AsmToken::Comma))
3629 return TokError("unexpected token in directive");
3630 Lex();
3631 }
Eli Bendersky17233942013-01-15 22:59:42 +00003632
3633 return false;
3634}
3635
Jim Grosbach4b905842013-09-20 23:08:21 +00003636/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00003637/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003638bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003639 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbara5508c82009-06-30 00:33:19 +00003640 for (;;) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00003641 StringRef Name;
Jim Grosbachebdf32f2011-09-15 17:56:49 +00003642 SMLoc Loc = getTok().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00003643
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003644 if (parseIdentifier(Name))
Jim Grosbachebdf32f2011-09-15 17:56:49 +00003645 return Error(Loc, "expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00003646
Jim Grosbach6f482002015-05-18 18:43:14 +00003647 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbara5508c82009-06-30 00:33:19 +00003648
Jim Grosbachebdf32f2011-09-15 17:56:49 +00003649 // Assembler local symbols don't make any sense here. Complain loudly.
3650 if (Sym->isTemporary())
3651 return Error(Loc, "non-local symbol required in directive");
3652
Saleem Abdulrasool4208b612013-08-09 01:52:03 +00003653 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
3654 return Error(Loc, "unable to emit symbol attribute");
Daniel Dunbara5508c82009-06-30 00:33:19 +00003655
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003656 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara5508c82009-06-30 00:33:19 +00003657 break;
3658
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003659 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara5508c82009-06-30 00:33:19 +00003660 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00003661 Lex();
Daniel Dunbara5508c82009-06-30 00:33:19 +00003662 }
3663 }
3664
Sean Callanan686ed8d2010-01-19 20:22:31 +00003665 Lex();
Jan Wen Voungc7682872010-09-30 01:09:20 +00003666 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00003667}
Chris Lattnera1e11f52009-07-07 20:30:46 +00003668
Jim Grosbach4b905842013-09-20 23:08:21 +00003669/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00003670/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003671bool AsmParser::parseDirectiveComm(bool IsLocal) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003672 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00003673
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003674 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00003675 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003676 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00003677 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00003678
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00003679 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00003680 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00003681
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003682 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00003683 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00003684 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00003685
3686 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003687 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003688 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00003689 return true;
3690
3691 int64_t Pow2Alignment = 0;
3692 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003693 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00003694 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003695 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003696 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00003697 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00003698
Benjamin Kramer68b9f052012-09-07 21:08:01 +00003699 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3700 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00003701 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3702
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00003703 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00003704 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3705 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00003706 if (!isPowerOf2_64(Pow2Alignment))
3707 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3708 Pow2Alignment = Log2_64(Pow2Alignment);
3709 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00003710 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00003711
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003712 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner28ad7542009-07-09 17:25:12 +00003713 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00003714
Sean Callanan686ed8d2010-01-19 20:22:31 +00003715 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00003716
Chris Lattner28ad7542009-07-09 17:25:12 +00003717 // NOTE: a size of zero for a .comm should create a undefined symbol
3718 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00003719 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00003720 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00003721 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00003722
Eric Christopherbc818852010-05-14 01:38:54 +00003723 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00003724 // may internally end up wanting an alignment in bytes.
3725 // FIXME: Diagnose overflow.
3726 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00003727 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00003728 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00003729
Daniel Dunbar6860ac72009-08-22 07:22:36 +00003730 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00003731 return Error(IDLoc, "invalid symbol redefinition");
3732
Chris Lattner28ad7542009-07-09 17:25:12 +00003733 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00003734 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00003735 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00003736 return false;
3737 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00003738
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003739 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00003740 return false;
3741}
Chris Lattner07cadaf2009-07-10 22:20:30 +00003742
Jim Grosbach4b905842013-09-20 23:08:21 +00003743/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00003744/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003745bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00003746 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003747 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00003748
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003749 StringRef Str = parseStringToEndOfStatement();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003750 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby56523ce2009-07-13 23:15:14 +00003751 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00003752
Sean Callanan686ed8d2010-01-19 20:22:31 +00003753 Lex();
Kevin Enderby56523ce2009-07-13 23:15:14 +00003754
Daniel Dunbareb6bb322009-07-27 23:20:52 +00003755 if (Str.empty())
3756 Error(Loc, ".abort detected. Assembly stopping.");
3757 else
3758 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00003759 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00003760
3761 return false;
3762}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00003763
Jim Grosbach4b905842013-09-20 23:08:21 +00003764/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00003765/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00003766bool AsmParser::parseDirectiveInclude() {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003767 if (getLexer().isNot(AsmToken::String))
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00003768 return TokError("expected string in '.include' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00003769
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003770 // Allow the strings to have escaped octal character sequence.
3771 std::string Filename;
3772 if (parseEscapedString(Filename))
3773 return true;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003774 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00003775 Lex();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00003776
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003777 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00003778 return TokError("unexpected token in '.include' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00003779
Chris Lattner693fbb82009-07-16 06:14:39 +00003780 // Attempt to switch the lexer to the included file before consuming the end
3781 // of statement to avoid losing it when we switch.
Jim Grosbach4b905842013-09-20 23:08:21 +00003782 if (enterIncludeFile(Filename)) {
Daniel Dunbard8a18452010-07-18 18:31:45 +00003783 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner693fbb82009-07-16 06:14:39 +00003784 return true;
3785 }
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00003786
3787 return false;
3788}
Kevin Enderby09ea5702009-07-15 15:30:11 +00003789
Jim Grosbach4b905842013-09-20 23:08:21 +00003790/// parseDirectiveIncbin
Kevin Enderby109f25c2011-12-14 21:47:48 +00003791/// ::= .incbin "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00003792bool AsmParser::parseDirectiveIncbin() {
Kevin Enderby109f25c2011-12-14 21:47:48 +00003793 if (getLexer().isNot(AsmToken::String))
3794 return TokError("expected string in '.incbin' directive");
3795
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003796 // Allow the strings to have escaped octal character sequence.
3797 std::string Filename;
3798 if (parseEscapedString(Filename))
3799 return true;
Kevin Enderby109f25c2011-12-14 21:47:48 +00003800 SMLoc IncbinLoc = getLexer().getLoc();
3801 Lex();
3802
3803 if (getLexer().isNot(AsmToken::EndOfStatement))
3804 return TokError("unexpected token in '.incbin' directive");
3805
Kevin Enderby109f25c2011-12-14 21:47:48 +00003806 // Attempt to process the included file.
Jim Grosbach4b905842013-09-20 23:08:21 +00003807 if (processIncbinFile(Filename)) {
Kevin Enderby109f25c2011-12-14 21:47:48 +00003808 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3809 return true;
3810 }
3811
3812 return false;
3813}
3814
Jim Grosbach4b905842013-09-20 23:08:21 +00003815/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00003816/// ::= .if{,eq,ge,gt,le,lt,ne} expression
3817bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00003818 TheCondStack.push_back(TheCondState);
3819 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00003820 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003821 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00003822 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00003823 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003824 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00003825 return true;
3826
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003827 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00003828 return TokError("unexpected token in '.if' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00003829
Sean Callanan686ed8d2010-01-19 20:22:31 +00003830 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00003831
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00003832 switch (DirKind) {
3833 default:
3834 llvm_unreachable("unsupported directive");
3835 case DK_IF:
3836 case DK_IFNE:
3837 break;
3838 case DK_IFEQ:
3839 ExprValue = ExprValue == 0;
3840 break;
3841 case DK_IFGE:
3842 ExprValue = ExprValue >= 0;
3843 break;
3844 case DK_IFGT:
3845 ExprValue = ExprValue > 0;
3846 break;
3847 case DK_IFLE:
3848 ExprValue = ExprValue <= 0;
3849 break;
3850 case DK_IFLT:
3851 ExprValue = ExprValue < 0;
3852 break;
3853 }
3854
Kevin Enderbyd9f95292009-08-07 22:46:00 +00003855 TheCondState.CondMet = ExprValue;
3856 TheCondState.Ignore = !TheCondState.CondMet;
3857 }
3858
3859 return false;
3860}
3861
Jim Grosbach4b905842013-09-20 23:08:21 +00003862/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00003863/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00003864bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00003865 TheCondStack.push_back(TheCondState);
3866 TheCondState.TheCond = AsmCond::IfCond;
3867
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00003868 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003869 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00003870 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003871 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00003872
3873 if (getLexer().isNot(AsmToken::EndOfStatement))
3874 return TokError("unexpected token in '.ifb' directive");
3875
3876 Lex();
3877
3878 TheCondState.CondMet = ExpectBlank == Str.empty();
3879 TheCondState.Ignore = !TheCondState.CondMet;
3880 }
3881
3882 return false;
3883}
3884
Jim Grosbach4b905842013-09-20 23:08:21 +00003885/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00003886/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00003887/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00003888bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00003889 TheCondStack.push_back(TheCondState);
3890 TheCondState.TheCond = AsmCond::IfCond;
3891
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00003892 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003893 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00003894 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00003895 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00003896
3897 if (getLexer().isNot(AsmToken::Comma))
3898 return TokError("unexpected token in '.ifc' directive");
3899
3900 Lex();
3901
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003902 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00003903
3904 if (getLexer().isNot(AsmToken::EndOfStatement))
3905 return TokError("unexpected token in '.ifc' directive");
3906
3907 Lex();
3908
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00003909 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00003910 TheCondState.Ignore = !TheCondState.CondMet;
3911 }
3912
3913 return false;
3914}
3915
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00003916/// parseDirectiveIfeqs
3917/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00003918bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00003919 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00003920 if (ExpectEqual)
3921 TokError("expected string parameter for '.ifeqs' directive");
3922 else
3923 TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00003924 eatToEndOfStatement();
3925 return true;
3926 }
3927
3928 StringRef String1 = getTok().getStringContents();
3929 Lex();
3930
3931 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00003932 if (ExpectEqual)
3933 TokError("expected comma after first string for '.ifeqs' directive");
3934 else
3935 TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00003936 eatToEndOfStatement();
3937 return true;
3938 }
3939
3940 Lex();
3941
3942 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00003943 if (ExpectEqual)
3944 TokError("expected string parameter for '.ifeqs' directive");
3945 else
3946 TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00003947 eatToEndOfStatement();
3948 return true;
3949 }
3950
3951 StringRef String2 = getTok().getStringContents();
3952 Lex();
3953
3954 TheCondStack.push_back(TheCondState);
3955 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00003956 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00003957 TheCondState.Ignore = !TheCondState.CondMet;
3958
3959 return false;
3960}
3961
Jim Grosbach4b905842013-09-20 23:08:21 +00003962/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00003963/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00003964bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00003965 StringRef Name;
3966 TheCondStack.push_back(TheCondState);
3967 TheCondState.TheCond = AsmCond::IfCond;
3968
3969 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003970 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00003971 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003972 if (parseIdentifier(Name))
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00003973 return TokError("expected identifier after '.ifdef'");
3974
3975 Lex();
3976
Jim Grosbach6f482002015-05-18 18:43:14 +00003977 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00003978
3979 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00003980 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00003981 else
Craig Topper353eda42014-04-24 06:44:33 +00003982 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00003983 TheCondState.Ignore = !TheCondState.CondMet;
3984 }
3985
3986 return false;
3987}
3988
Jim Grosbach4b905842013-09-20 23:08:21 +00003989/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00003990/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003991bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00003992 if (TheCondState.TheCond != AsmCond::IfCond &&
3993 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper2172ad62013-04-22 04:24:02 +00003994 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3995 " an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00003996 TheCondState.TheCond = AsmCond::ElseIfCond;
3997
Kevin Enderbyd9f95292009-08-07 22:46:00 +00003998 bool LastIgnoreState = false;
3999 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004000 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004001 if (LastIgnoreState || TheCondState.CondMet) {
4002 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004003 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004004 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004005 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004006 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004007 return true;
4008
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004009 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004010 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004011
Sean Callanan686ed8d2010-01-19 20:22:31 +00004012 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004013 TheCondState.CondMet = ExprValue;
4014 TheCondState.Ignore = !TheCondState.CondMet;
4015 }
4016
4017 return false;
4018}
4019
Jim Grosbach4b905842013-09-20 23:08:21 +00004020/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004021/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004022bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004023 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004024 return TokError("unexpected token in '.else' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004025
Sean Callanan686ed8d2010-01-19 20:22:31 +00004026 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004027
4028 if (TheCondState.TheCond != AsmCond::IfCond &&
4029 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper2172ad62013-04-22 04:24:02 +00004030 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4031 ".elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004032 TheCondState.TheCond = AsmCond::ElseCond;
4033 bool LastIgnoreState = false;
4034 if (!TheCondStack.empty())
4035 LastIgnoreState = TheCondStack.back().Ignore;
4036 if (LastIgnoreState || TheCondState.CondMet)
4037 TheCondState.Ignore = true;
4038 else
4039 TheCondState.Ignore = false;
4040
4041 return false;
4042}
4043
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004044/// parseDirectiveEnd
4045/// ::= .end
4046bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
4047 if (getLexer().isNot(AsmToken::EndOfStatement))
4048 return TokError("unexpected token in '.end' directive");
4049
4050 Lex();
4051
4052 while (Lexer.isNot(AsmToken::Eof))
4053 Lex();
4054
4055 return false;
4056}
4057
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004058/// parseDirectiveError
4059/// ::= .err
4060/// ::= .error [string]
4061bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4062 if (!TheCondStack.empty()) {
4063 if (TheCondStack.back().Ignore) {
4064 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004065 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004066 }
4067 }
4068
4069 if (!WithMessage)
4070 return Error(L, ".err encountered");
4071
4072 StringRef Message = ".error directive invoked in source file";
4073 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4074 if (Lexer.isNot(AsmToken::String)) {
4075 TokError(".error argument must be a string");
4076 eatToEndOfStatement();
4077 return true;
4078 }
4079
4080 Message = getTok().getStringContents();
4081 Lex();
4082 }
4083
4084 Error(L, Message);
4085 return true;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004086}
4087
Nico Weber404012b2014-07-24 16:26:06 +00004088/// parseDirectiveWarning
4089/// ::= .warning [string]
4090bool AsmParser::parseDirectiveWarning(SMLoc L) {
4091 if (!TheCondStack.empty()) {
4092 if (TheCondStack.back().Ignore) {
4093 eatToEndOfStatement();
4094 return false;
4095 }
4096 }
4097
4098 StringRef Message = ".warning directive invoked in source file";
4099 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4100 if (Lexer.isNot(AsmToken::String)) {
4101 TokError(".warning argument must be a string");
4102 eatToEndOfStatement();
4103 return true;
4104 }
4105
4106 Message = getTok().getStringContents();
4107 Lex();
4108 }
4109
4110 Warning(L, Message);
4111 return false;
4112}
4113
Jim Grosbach4b905842013-09-20 23:08:21 +00004114/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004115/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00004116bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004117 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004118 return TokError("unexpected token in '.endif' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004119
Sean Callanan686ed8d2010-01-19 20:22:31 +00004120 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004121
Jim Grosbach4b905842013-09-20 23:08:21 +00004122 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004123 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4124 ".else");
4125 if (!TheCondStack.empty()) {
4126 TheCondState = TheCondStack.back();
4127 TheCondStack.pop_back();
4128 }
4129
4130 return false;
4131}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00004132
Eli Bendersky17233942013-01-15 22:59:42 +00004133void AsmParser::initializeDirectiveKindMap() {
4134 DirectiveKindMap[".set"] = DK_SET;
4135 DirectiveKindMap[".equ"] = DK_EQU;
4136 DirectiveKindMap[".equiv"] = DK_EQUIV;
4137 DirectiveKindMap[".ascii"] = DK_ASCII;
4138 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4139 DirectiveKindMap[".string"] = DK_STRING;
4140 DirectiveKindMap[".byte"] = DK_BYTE;
4141 DirectiveKindMap[".short"] = DK_SHORT;
4142 DirectiveKindMap[".value"] = DK_VALUE;
4143 DirectiveKindMap[".2byte"] = DK_2BYTE;
4144 DirectiveKindMap[".long"] = DK_LONG;
4145 DirectiveKindMap[".int"] = DK_INT;
4146 DirectiveKindMap[".4byte"] = DK_4BYTE;
4147 DirectiveKindMap[".quad"] = DK_QUAD;
4148 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00004149 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00004150 DirectiveKindMap[".single"] = DK_SINGLE;
4151 DirectiveKindMap[".float"] = DK_FLOAT;
4152 DirectiveKindMap[".double"] = DK_DOUBLE;
4153 DirectiveKindMap[".align"] = DK_ALIGN;
4154 DirectiveKindMap[".align32"] = DK_ALIGN32;
4155 DirectiveKindMap[".balign"] = DK_BALIGN;
4156 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4157 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4158 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4159 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4160 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4161 DirectiveKindMap[".org"] = DK_ORG;
4162 DirectiveKindMap[".fill"] = DK_FILL;
4163 DirectiveKindMap[".zero"] = DK_ZERO;
4164 DirectiveKindMap[".extern"] = DK_EXTERN;
4165 DirectiveKindMap[".globl"] = DK_GLOBL;
4166 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00004167 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4168 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4169 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4170 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4171 DirectiveKindMap[".reference"] = DK_REFERENCE;
4172 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4173 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4174 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4175 DirectiveKindMap[".comm"] = DK_COMM;
4176 DirectiveKindMap[".common"] = DK_COMMON;
4177 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4178 DirectiveKindMap[".abort"] = DK_ABORT;
4179 DirectiveKindMap[".include"] = DK_INCLUDE;
4180 DirectiveKindMap[".incbin"] = DK_INCBIN;
4181 DirectiveKindMap[".code16"] = DK_CODE16;
4182 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4183 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004184 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00004185 DirectiveKindMap[".irp"] = DK_IRP;
4186 DirectiveKindMap[".irpc"] = DK_IRPC;
4187 DirectiveKindMap[".endr"] = DK_ENDR;
4188 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4189 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4190 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4191 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004192 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4193 DirectiveKindMap[".ifge"] = DK_IFGE;
4194 DirectiveKindMap[".ifgt"] = DK_IFGT;
4195 DirectiveKindMap[".ifle"] = DK_IFLE;
4196 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00004197 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00004198 DirectiveKindMap[".ifb"] = DK_IFB;
4199 DirectiveKindMap[".ifnb"] = DK_IFNB;
4200 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004201 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00004202 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00004203 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00004204 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4205 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4206 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4207 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4208 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004209 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00004210 DirectiveKindMap[".endif"] = DK_ENDIF;
4211 DirectiveKindMap[".skip"] = DK_SKIP;
4212 DirectiveKindMap[".space"] = DK_SPACE;
4213 DirectiveKindMap[".file"] = DK_FILE;
4214 DirectiveKindMap[".line"] = DK_LINE;
4215 DirectiveKindMap[".loc"] = DK_LOC;
4216 DirectiveKindMap[".stabs"] = DK_STABS;
4217 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4218 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4219 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4220 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4221 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4222 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4223 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4224 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4225 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4226 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4227 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4228 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4229 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4230 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4231 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4232 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4233 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4234 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4235 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4236 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4237 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00004238 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00004239 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4240 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4241 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00004242 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00004243 DirectiveKindMap[".endm"] = DK_ENDM;
4244 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4245 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004246 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004247 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00004248 DirectiveKindMap[".warning"] = DK_WARNING;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00004249}
4250
Jim Grosbach4b905842013-09-20 23:08:21 +00004251MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004252 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004253
Rafael Espindola34b9c512012-06-03 23:57:14 +00004254 unsigned NestLevel = 0;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004255 for (;;) {
4256 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00004257 if (getLexer().is(AsmToken::Eof)) {
4258 Error(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00004259 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004260 }
4261
Rafael Espindola34b9c512012-06-03 23:57:14 +00004262 if (Lexer.is(AsmToken::Identifier) &&
4263 (getTok().getIdentifier() == ".rept")) {
4264 ++NestLevel;
4265 }
4266
4267 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00004268 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004269 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004270 EndToken = getTok();
4271 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004272 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4273 TokError("unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00004274 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004275 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004276 break;
4277 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004278 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004279 }
4280
Rafael Espindola34b9c512012-06-03 23:57:14 +00004281 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004282 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004283 }
4284
4285 const char *BodyStart = StartToken.getLoc().getPointer();
4286 const char *BodyEnd = EndToken.getLoc().getPointer();
4287 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4288
Rafael Espindola34b9c512012-06-03 23:57:14 +00004289 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004290 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00004291 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004292}
4293
Jim Grosbach4b905842013-09-20 23:08:21 +00004294void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00004295 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004296 OS << ".endr\n";
4297
Rafael Espindola3560ff22014-08-27 20:03:13 +00004298 std::unique_ptr<MemoryBuffer> Instantiation =
4299 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004300
Rafael Espindola34b9c512012-06-03 23:57:14 +00004301 // Create the macro instantiation object and add to the current macro
4302 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00004303 MacroInstantiation *MI = new MacroInstantiation(
4304 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00004305 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004306
Rafael Espindola34b9c512012-06-03 23:57:14 +00004307 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00004308 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00004309 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00004310 Lex();
4311}
4312
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004313/// parseDirectiveRept
4314/// ::= .rep | .rept count
4315bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004316 const MCExpr *CountExpr;
4317 SMLoc CountLoc = getTok().getLoc();
4318 if (parseExpression(CountExpr))
4319 return true;
4320
Rafael Espindola34b9c512012-06-03 23:57:14 +00004321 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00004322 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004323 eatToEndOfStatement();
4324 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4325 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004326
4327 if (Count < 0)
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004328 return Error(CountLoc, "Count is negative");
Rafael Espindola34b9c512012-06-03 23:57:14 +00004329
4330 if (Lexer.isNot(AsmToken::EndOfStatement))
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004331 return TokError("unexpected token in '" + Dir + "' directive");
Rafael Espindola34b9c512012-06-03 23:57:14 +00004332
4333 // Eat the end of statement.
4334 Lex();
4335
4336 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004337 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00004338 if (!M)
4339 return true;
4340
4341 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4342 // to hold the macro body with substitutions.
4343 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004344 raw_svector_ostream OS(Buf);
4345 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00004346 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4347 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00004348 return true;
4349 }
Jim Grosbach4b905842013-09-20 23:08:21 +00004350 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004351
4352 return false;
4353}
4354
Jim Grosbach4b905842013-09-20 23:08:21 +00004355/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00004356/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00004357bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00004358 MCAsmMacroParameter Parameter;
Rafael Espindola768b41c2012-06-15 14:02:34 +00004359
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004360 if (parseIdentifier(Parameter.Name))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004361 return TokError("expected identifier in '.irp' directive");
4362
Rafael Espindola768b41c2012-06-15 14:02:34 +00004363 if (Lexer.isNot(AsmToken::Comma))
4364 return TokError("expected comma in '.irp' directive");
4365
4366 Lex();
4367
Eli Bendersky38274122013-01-14 23:22:36 +00004368 MCAsmMacroArguments A;
Craig Topper353eda42014-04-24 06:44:33 +00004369 if (parseMacroArguments(nullptr, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004370 return true;
4371
4372 // Eat the end of statement.
4373 Lex();
4374
4375 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004376 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00004377 if (!M)
4378 return true;
4379
4380 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4381 // to hold the macro body with substitutions.
4382 SmallString<256> Buf;
4383 raw_svector_ostream OS(Buf);
4384
Eli Bendersky38274122013-01-14 23:22:36 +00004385 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
Toma Tabacu217116e2015-04-27 10:50:29 +00004386 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4387 // This is undocumented, but GAS seems to support it.
4388 if (expandMacro(OS, M->Body, Parameter, *i, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004389 return true;
4390 }
4391
Jim Grosbach4b905842013-09-20 23:08:21 +00004392 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00004393
4394 return false;
4395}
4396
Jim Grosbach4b905842013-09-20 23:08:21 +00004397/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004398/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00004399bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00004400 MCAsmMacroParameter Parameter;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004401
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004402 if (parseIdentifier(Parameter.Name))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004403 return TokError("expected identifier in '.irpc' directive");
4404
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004405 if (Lexer.isNot(AsmToken::Comma))
4406 return TokError("expected comma in '.irpc' directive");
4407
4408 Lex();
4409
Eli Bendersky38274122013-01-14 23:22:36 +00004410 MCAsmMacroArguments A;
Craig Topper353eda42014-04-24 06:44:33 +00004411 if (parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004412 return true;
4413
4414 if (A.size() != 1 || A.front().size() != 1)
4415 return TokError("unexpected token in '.irpc' directive");
4416
4417 // Eat the end of statement.
4418 Lex();
4419
4420 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004421 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004422 if (!M)
4423 return true;
4424
4425 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4426 // to hold the macro body with substitutions.
4427 SmallString<256> Buf;
4428 raw_svector_ostream OS(Buf);
4429
4430 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004431 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00004432 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004433 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004434
Toma Tabacu217116e2015-04-27 10:50:29 +00004435 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
4436 // This is undocumented, but GAS seems to support it.
4437 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004438 return true;
4439 }
4440
Jim Grosbach4b905842013-09-20 23:08:21 +00004441 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004442
4443 return false;
4444}
4445
Jim Grosbach4b905842013-09-20 23:08:21 +00004446bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004447 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00004448 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004449
4450 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00004451 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004452 assert(getLexer().is(AsmToken::EndOfStatement));
4453
Jim Grosbach4b905842013-09-20 23:08:21 +00004454 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004455 return false;
4456}
Rafael Espindola12d73d12010-09-11 16:45:15 +00004457
Jim Grosbach4b905842013-09-20 23:08:21 +00004458bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00004459 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00004460 const MCExpr *Value;
4461 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004462 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00004463 return true;
4464 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4465 if (!MCE)
4466 return Error(ExprLoc, "unexpected expression in _emit");
4467 uint64_t IntValue = MCE->getValue();
4468 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4469 return Error(ExprLoc, "literal value out of range for directive");
4470
Chad Rosierc7f552c2013-02-12 21:33:51 +00004471 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4472 return false;
4473}
4474
Jim Grosbach4b905842013-09-20 23:08:21 +00004475bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00004476 const MCExpr *Value;
4477 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004478 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00004479 return true;
4480 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4481 if (!MCE)
4482 return Error(ExprLoc, "unexpected expression in align");
4483 uint64_t IntValue = MCE->getValue();
4484 if (!isPowerOf2_64(IntValue))
4485 return Error(ExprLoc, "literal value not a power of two greater then zero");
4486
Jim Grosbach4b905842013-09-20 23:08:21 +00004487 Info.AsmRewrites->push_back(
4488 AsmRewrite(AOK_Align, IDLoc, 5, Log2_64(IntValue)));
Eli Friedman0f4871d2012-10-22 23:58:19 +00004489 return false;
4490}
4491
Chad Rosierf43fcf52013-02-13 21:27:17 +00004492// We are comparing pointers, but the pointers are relative to a single string.
4493// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00004494static int rewritesSort(const AsmRewrite *AsmRewriteA,
4495 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00004496 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4497 return -1;
4498 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4499 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004500
Chad Rosierfce4fab2013-04-08 17:43:47 +00004501 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
4502 // rewrite to the same location. Make sure the SizeDirective rewrite is
4503 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
4504 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00004505 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
4506 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004507 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00004508
Jim Grosbach4b905842013-09-20 23:08:21 +00004509 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
4510 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00004511 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00004512 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00004513}
4514
Jim Grosbach4b905842013-09-20 23:08:21 +00004515bool AsmParser::parseMSInlineAsm(
4516 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
4517 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4518 SmallVectorImpl<std::string> &Constraints,
4519 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
4520 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00004521 SmallVector<void *, 4> InputDecls;
4522 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00004523 SmallVector<bool, 4> InputDeclsAddressOf;
4524 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00004525 SmallVector<std::string, 4> InputConstraints;
4526 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00004527 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00004528
Benjamin Kramer1a136112013-02-15 20:37:21 +00004529 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00004530
4531 // Prime the lexer.
4532 Lex();
4533
4534 // While we have input, parse each statement.
4535 unsigned InputIdx = 0;
4536 unsigned OutputIdx = 0;
4537 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00004538 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00004539 if (parseStatement(Info, &SI))
Chad Rosierf1f6a722012-10-19 22:57:33 +00004540 return true;
Chad Rosier8bce6642012-10-18 15:49:34 +00004541
Chad Rosier149e8e02012-12-12 22:45:52 +00004542 if (Info.ParseError)
4543 return true;
4544
Benjamin Kramer1a136112013-02-15 20:37:21 +00004545 if (Info.Opcode == ~0U)
4546 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00004547
Benjamin Kramer1a136112013-02-15 20:37:21 +00004548 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00004549
Benjamin Kramer1a136112013-02-15 20:37:21 +00004550 // Build the list of clobbers, outputs and inputs.
4551 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00004552 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00004553
Benjamin Kramer1a136112013-02-15 20:37:21 +00004554 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00004555 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00004556 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00004557
Benjamin Kramer1a136112013-02-15 20:37:21 +00004558 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00004559 if (Operand.isReg() && !Operand.needAddressOf() &&
4560 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00004561 unsigned NumDefs = Desc.getNumDefs();
4562 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00004563 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
4564 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00004565 continue;
4566 }
4567
4568 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00004569 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00004570 if (SymName.empty())
4571 continue;
4572
David Blaikie960ea3f2014-06-08 16:18:35 +00004573 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00004574 if (!OpDecl)
4575 continue;
4576
4577 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00004578 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00004579 if (isOutput) {
4580 ++InputIdx;
4581 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00004582 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00004583 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Chad Rosiere81309b2013-04-09 17:53:49 +00004584 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Start, SymName.size()));
Benjamin Kramer1a136112013-02-15 20:37:21 +00004585 } else {
4586 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00004587 InputDeclsAddressOf.push_back(Operand.needAddressOf());
4588 InputConstraints.push_back(Operand.getConstraint().str());
Chad Rosiere81309b2013-04-09 17:53:49 +00004589 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Start, SymName.size()));
Chad Rosier8bce6642012-10-18 15:49:34 +00004590 }
Chad Rosier8bce6642012-10-18 15:49:34 +00004591 }
Reid Kleckneree088972013-12-10 18:27:32 +00004592
4593 // Consider implicit defs to be clobbers. Think of cpuid and push.
David Majnemer8114c1a2014-06-23 02:17:16 +00004594 ArrayRef<uint16_t> ImpDefs(Desc.getImplicitDefs(),
4595 Desc.getNumImplicitDefs());
4596 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00004597 }
4598
4599 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00004600 NumOutputs = OutputDecls.size();
4601 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00004602
4603 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00004604 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4605 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4606 ClobberRegs.end());
4607 Clobbers.assign(ClobberRegs.size(), std::string());
4608 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4609 raw_string_ostream OS(Clobbers[I]);
4610 IP->printRegName(OS, ClobberRegs[I]);
4611 }
Chad Rosier8bce6642012-10-18 15:49:34 +00004612
4613 // Merge the various outputs and inputs. Output are expected first.
4614 if (NumOutputs || NumInputs) {
4615 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00004616 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00004617 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00004618 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00004619 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00004620 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00004621 }
4622 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00004623 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00004624 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00004625 }
4626 }
4627
4628 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00004629 std::string AsmStringIR;
4630 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00004631 StringRef ASMString =
4632 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
4633 const char *AsmStart = ASMString.begin();
4634 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00004635 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00004636 for (const AsmRewrite &AR : AsmStrRewrites) {
4637 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00004638 if (Kind == AOK_Delete)
4639 continue;
4640
David Majnemer8114c1a2014-06-23 02:17:16 +00004641 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00004642 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00004643
Chad Rosier120eefd2013-03-19 17:32:17 +00004644 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00004645 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00004646 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00004647
Chad Rosier37e755c2012-10-23 17:43:43 +00004648 // Skip the original expression.
4649 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00004650 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00004651 continue;
4652 }
4653
Chad Rosierff10ed12013-04-12 16:26:42 +00004654 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00004655 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00004656 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004657 default:
4658 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00004659 case AOK_Imm:
David Majnemer8114c1a2014-06-23 02:17:16 +00004660 OS << "$$" << AR.Val;
Chad Rosier11c42f22012-10-26 18:04:20 +00004661 break;
4662 case AOK_ImmPrefix:
Benjamin Kramer1a136112013-02-15 20:37:21 +00004663 OS << "$$";
Chad Rosier8bce6642012-10-18 15:49:34 +00004664 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00004665 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00004666 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00004667 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00004668 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00004669 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00004670 break;
4671 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00004672 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00004673 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00004674 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00004675 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00004676 default: break;
4677 case 8: OS << "byte ptr "; break;
4678 case 16: OS << "word ptr "; break;
4679 case 32: OS << "dword ptr "; break;
4680 case 64: OS << "qword ptr "; break;
4681 case 80: OS << "xword ptr "; break;
4682 case 128: OS << "xmmword ptr "; break;
4683 case 256: OS << "ymmword ptr "; break;
4684 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00004685 break;
4686 case AOK_Emit:
4687 OS << ".byte";
4688 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00004689 case AOK_Align: {
David Majnemer8114c1a2014-06-23 02:17:16 +00004690 unsigned Val = AR.Val;
Chad Rosierc7f552c2013-02-12 21:33:51 +00004691 OS << ".align " << Val;
4692
4693 // Skip the original immediate.
Benjamin Kramer1a136112013-02-15 20:37:21 +00004694 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00004695 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4696 break;
4697 }
Chad Rosierf0e87202012-10-25 20:41:34 +00004698 case AOK_DotOperator:
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00004699 // Insert the dot if the user omitted it.
Alp Tokere69170a2014-06-26 22:52:05 +00004700 OS.flush();
4701 if (AsmStringIR.back() != '.')
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00004702 OS << '.';
David Majnemer8114c1a2014-06-23 02:17:16 +00004703 OS << AR.Val;
Chad Rosierf0e87202012-10-25 20:41:34 +00004704 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00004705 }
Chad Rosier0f48c552012-10-19 20:57:14 +00004706
Chad Rosier8bce6642012-10-18 15:49:34 +00004707 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00004708 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00004709 }
4710
4711 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00004712 if (AsmStart != AsmEnd)
4713 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00004714
4715 AsmString = OS.str();
4716 return false;
4717}
4718
Pete Cooper80d21cb2015-06-22 19:35:57 +00004719namespace llvm {
4720namespace MCParserUtils {
4721
4722/// Returns whether the given symbol is used anywhere in the given expression,
4723/// or subexpressions.
4724static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
4725 switch (Value->getKind()) {
4726 case MCExpr::Binary: {
4727 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
4728 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
4729 isSymbolUsedInExpression(Sym, BE->getRHS());
4730 }
4731 case MCExpr::Target:
4732 case MCExpr::Constant:
4733 return false;
4734 case MCExpr::SymbolRef: {
4735 const MCSymbol &S =
4736 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
4737 if (S.isVariable())
4738 return isSymbolUsedInExpression(Sym, S.getVariableValue());
4739 return &S == Sym;
4740 }
4741 case MCExpr::Unary:
4742 return isSymbolUsedInExpression(
4743 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
4744 }
4745
4746 llvm_unreachable("Unknown expr kind!");
4747}
4748
4749bool parseAssignmentExpression(StringRef Name, bool allow_redef,
4750 MCAsmParser &Parser, MCSymbol *&Sym,
4751 const MCExpr *&Value) {
4752 MCAsmLexer &Lexer = Parser.getLexer();
4753
4754 // FIXME: Use better location, we should use proper tokens.
4755 SMLoc EqualLoc = Lexer.getLoc();
4756
4757 if (Parser.parseExpression(Value)) {
4758 Parser.TokError("missing expression");
4759 Parser.eatToEndOfStatement();
4760 return true;
4761 }
4762
4763 // Note: we don't count b as used in "a = b". This is to allow
4764 // a = b
4765 // b = c
4766
4767 if (Lexer.isNot(AsmToken::EndOfStatement))
4768 return Parser.TokError("unexpected token in assignment");
4769
4770 // Eat the end of statement marker.
4771 Parser.Lex();
4772
4773 // Validate that the LHS is allowed to be a variable (either it has not been
4774 // used as a symbol, or it is an absolute symbol).
4775 Sym = Parser.getContext().lookupSymbol(Name);
4776 if (Sym) {
4777 // Diagnose assignment to a label.
4778 //
4779 // FIXME: Diagnostics. Note the location of the definition as a label.
4780 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
4781 if (isSymbolUsedInExpression(Sym, Value))
4782 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
4783 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
4784 ; // Allow redefinitions of undefined symbols only used in directives.
4785 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
4786 ; // Allow redefinitions of variables that haven't yet been used.
4787 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
4788 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
4789 else if (!Sym->isVariable())
4790 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
4791 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
4792 return Parser.Error(EqualLoc,
4793 "invalid reassignment of non-absolute variable '" +
4794 Name + "'");
4795
4796 // Don't count these checks as uses.
4797 Sym->setUsed(false);
4798 } else if (Name == ".") {
4799 if (Parser.getStreamer().EmitValueToOffset(Value, 0)) {
4800 Parser.Error(EqualLoc, "expected absolute expression");
4801 Parser.eatToEndOfStatement();
4802 return true;
4803 }
4804 return false;
4805 } else
4806 Sym = Parser.getContext().getOrCreateSymbol(Name);
4807
4808 Sym->setRedefinable(allow_redef);
4809
4810 return false;
4811}
4812
4813} // namespace MCParserUtils
4814} // namespace llvm
4815
Daniel Dunbar01e36072010-07-17 02:26:10 +00004816/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00004817MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
4818 MCStreamer &Out, const MCAsmInfo &MAI) {
Jim Grosbach345768c2011-08-16 18:33:49 +00004819 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbar01e36072010-07-17 02:26:10 +00004820}